0% found this document useful (0 votes)
6 views243 pages

CSO101 Lecture Slides

CS0 101: Computer Programming is a course aimed at providing basic programming skills and understanding of computers, with a focus on writing C programs. The course includes evaluations based on theory and laboratory work, with resources such as standard ANSI C books recommended. Students will learn to use Linux/Ubuntu for programming and will complete various lab exercises to reinforce their learning.

Uploaded by

bansalrajat730
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views243 pages

CSO101 Lecture Slides

CS0 101: Computer Programming is a course aimed at providing basic programming skills and understanding of computers, with a focus on writing C programs. The course includes evaluations based on theory and laboratory work, with resources such as standard ANSI C books recommended. Students will learn to use Linux/Ubuntu for programming and will complete various lab exercises to reinforce their learning.

Uploaded by

bansalrajat730
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 243

CS0 101 : Computer Programming

Instructor & Course Convener


Dr. Bidyut Kr. Patra, Associate Professor
Department of Computer Science & Engineering

3/16/2023 1
How the courses are run?

■ There are 20 TAs, who are M.Tech and IDD


students of the CSE dept.
■ TAs will primarily help you in the Lab. Part
and Tutorial Classes.
■ Students in CSO 101 is divided into 10
sections.
■ Five sections will attend this course in this
semester.

3/16/2023 2
Objectives

■ To give basic programming skills.


■ To give conceptual understanding of
computers and their working.
■ At the end of the course the student is
expected to write a moderately complex
C program.

3/16/2023 3
Evaluation Criteria
Theory (60%)
■ Mid Semester Exam : 30% [18]
■ End Semester Exam : 50% [30]
■ Assignment Sheet I /Quiz : 10% [06]
■ Assignment Sheet II/Quiz : 10% [06]
Laboratory (40%):
■ Continuous Evaluation: Every Alternate Week : 75% [30]

■ Viva-voce: 25% [10]

3/16/2023 4
Books and Course Page
■ You may follow any standard ANSI C book.
❖ E. Balaguruswamy. Programming in ANCI C, Tata
McGraw-Hill (Latest Edition)

❖ Brian W. Kernighan, Dennis M. Ritchie. The C


Programming Language, Prentice Hall (2nd Edition)

❖ V. Rajaraman and Neeharika Adabela. Fundamentals of


Computers, Eastern Economy Edition

■ Course Page
■ https://sites.google.com/site/patrabidyutkr/teachingiitbhu/odd2023-24-cso10
1

3/16/2023 5
Lab. Part

■ Use only Linux/Ubuntu/Fedora Operating


System.
[ Do not use Microsoft windows ! ]
■ Use ANSI C (Standard C).
■ A brief about the 1st exercise will be given
towards the end of this class.

3/16/2023 6
Policies, Guidelines,…

■ Questions in the examinations will be from


what will be taught in the classes.
■ Ask your doubts and questions to me. Do not
discuss in the class with your friends.
■ Attendance for Lab. Part is important and will
be counted.
■ Grading will be strictly according to your
performance, attendance, etc.

3/16/2023 7
Introduction: Computer

■ A device basically meant to do computations.


■ A machine that can follow a sequence of
instructions to accomplish a task.
■ Parts which physically does the execution are
called Hardware.
■ The sequence of steps (instructions) can be
called as Software.

3/16/2023 8
Hardware and Software
•Hardware: Keyboard, Mouse, Monitor, Printer, CPU,
Memory, etc.

•Software: Set of programs, like –

OS: Interface between hardware & user.

Compiler: Translates from high level language to machine


Language.

Tools: Internet access, Voice, Video, Games, etc.

3/16/2023 9
Computer (Conceptually)

3/16/2023 10
An Example

Work to be done: Buy 1 kg Alu.


Sequence of Steps:
1. Take Bag, Money.
2. Go to Market.
3. Search for good Alu.
4. Buy 1kg Alu.
5. Go home.
6. Stop.

3/16/2023 11
A Model ( Human)

• Body 🡺 Hardware
• Thinking Process (Mind) 🡺 Software

3/16/2023 12
Early Computers

■ Fixed-program computer: Can do specific


task(s) which is wired (fixed) into the
hardware. E.g.: A Calculator.
Drawback: No flexibility
■ Stored-program computer: By creating an
instruction set architecture and detailing the
computation as a series of instructions (the
program), the machine becomes much more
flexible.

3/16/2023 13
Stored-Program Computers

■ Program is also seen as data.


■ Program is also stored in memory as data.
■ The ability to treat instructions as data is what
makes assemblers, compilers and other
automated programming tools possible.

3/16/2023 14
Von Neumann Architecture

3/16/2023 15
Are there other architectures?

■ Harvard architecture Stores program in a


separate memory and data in a separate
memory.
■ But, these are rarely used in general purpose
computers.

3/16/2023 16
What you have to do?

■ Learn basic commands to work with the


linux/Ubuntu operating system.
■ Learn vi editor. (This is a software tool which
is used to create files, edit them).

3/16/2023 17
Your first lab exercise
■ Create a file named first.c whose contents should be:

■ #include<stdio.h>
int main()
{
printf(“ Hello IIT(BHU)”);
return 0;
}

3/16/2023 18
How to Run a Program

■ After you create the file whose name is first.c


you need to compile this file to get
executable file.
■ At the command prompt do
■ $ cc first.c
■ If the compilation is successful this gives a
file called a.out
■ $ ./a.out
■ The above command executes it.

3/16/2023 19
Homework

■ Read some book on C language and


understand first.c
■ In the lab the TAs will verify your programs,
and they will ask you some questions related to
your programs. You will be awarded some
marks in alternative of the lab classes.
■ The lecture slides will be kept in a web site.

3/16/2023 20
Your 2nd lab exercise
■ Create a file named second.c whose contents should be:
■ #include<stdio.h>
int main( )
{
int a, b;
printf(“Enter an integer value for variable a:”);
scanf(“%d”, &a);
printf(“Enter an integer value for variable b:”);
scanf(“%d”, &b);
printf(“a+b = %d\n”, a+b);
return 0;
}
▪ This will find sum of two integers.
▪ Extend this to find their difference, product and division.

3/16/2023 21
Next Class …

■ Introduction to Languages, algorithms, etc.

3/16/2023 22
Introduction …

Languages, Algorithms, Flowcharts


Language

■ A set of symbols (alphabet) are needed to


represent the instructions.
■ Computer uses two symbols (0 and 1) to
represent both instructions and data. This
language is called machine language (low
level language).
■ Since it is difficult for human beings to use
the machine language, high level languages
are invented.

10/31/2022 2
High Level Language (HLL)

■ Similar to English which can be used easily


by human beings.
■ E.g.: C, Pascal, Java, Cobol, etc.
■ HLL is independent of the Hard-Ware.
■ A translator is needed to convert a program
written in a HLL to the low level language.

10/31/2022 3
Translators

■ Compiler : Converts the entire program from


high level to machine level.
E.g. : C compilers like cc, gcc
■ Interpreter : Converts an instruction into
machine language and executes it, then goes
to the next instruction.
E.g. : Shell is a command interpreter.

10/31/2022 4
Algorithm

■ A finite sequence of unambiguous,


executable steps which when followed
achieves the specific objective.

■ Always algorithm terminates.

10/31/2022 5
Algorithm: Five Characteristics

■ Input: Externally supplied quantity(s).


■ Output: Produces at least one quantity.
■ Finiteness: Finite number of instructions.
■ Definiteness: Each instruction must be clear
and unambiguous.

■ Effectiveness: Each instruction must be basic


and feasible.

10/31/2022 6
Algorithm: Largest of 3 Numbers
1. READ A, B, C
2. IF ( A > B ) THEN goto 8
3. IF ( B > C ) THEN goto 6
4. PRINT C
5. STOP
6. PRINT B
7. STOP
8. IF ( A > C ) THEN goto 10
9. Goto 4
10. PRINT A
11. STOP

10/31/2022 7
Flowchart: A representational
scheme for Algorithm
Symbol Name Function

Start/End An Oval representing


a start/end point.

Input/Output A parallelogram
indicates input/output.

Decision A diamond indicates


decision

Process A rectangle represents


process.

Arrow A connector between


representative shapes.
10/31/2022 8
Flowchart: A representational scheme
for algorithms
• To find largest of three given numbers

10/31/2022 9
Largest of a set of numbers.

10/31/2022 10
Largest of a set of numbers.

1. READ number
2. largest = number
3. IF ( any more numbers) THEN goto 6
4. PRINT largest
5. STOP
6. READ number
7. IF ( number > largest ) then goto 2
8. Goto 3

10/31/2022 11
C-Programming Language

History, Types, Variables and Constants


Brief History

■ C evolved from two previous languages,


BCPL and B.
■ BCPL was developed in 1967 by Martin
Richards.
■ B, in 1970 by Ken Thompson.
■ Both BCPL and B were “typeless” languages.
■ C, in 1972 by Dennis Ritchie at Bell Labs.
■ C is widely used with UNIX operating system.

10/31/2022 2
History …

■ Many versions of the language C was


created by many people.
■ This created problems with portability.
■ In 1999, ANSI (American National Standards
Committee) standardized the language and is
called ANSI-C.

10/31/2022 3
C program

■ C program is a set of functions.


■ Every C program should have a function with
name main( )
■ Execution of the program starts with main( )
■ Some functions to do common tasks comes
along with the C language. These functions
are kept in libraries.
❑ For e.g. the functions to do input and output are in
the library called stdio.h

10/31/2022 4
C Standard Library

■ Libraries that comes along with C are called


standard libraries.
■ So, you need to learn C language and also
how to use the standard libraries.

10/31/2022 5
A Simple C Program

/* This program Prints Hello word */


#include <stdio.h>

main()
{
printf(“Hello.\n”);
} /* End of main */

10/31/2022 6
test.c
/* This program finds the area & perimeter
of a rectangle */

#include <stdio.h>

main()
{
int l, b, area, perimeter;
b = 4;
l = 6;
area = l*b;
perimeter = 2*(l+b);
printf(“Area = %d \n”, area);
printf (“Perimeter = %d \n”, perimeter);
} /* End of main */

10/31/2022 7
• Complier ignores comments
• #include line must not end with semicolon
• Every statement is terminated by semicolon

Output of the program

Area = 24
Perimeter = 20

cc test.c compile program test.c


a.out execute the program

10/31/2022 8
Variables and Constants

■ Basic data objects manipulated in a program.


■ Variable should have a name (identifier) and a value.
■ Names are made up of letters and digits; the first
character must be a letter.
■ E.g.: total, n, sum1, sum2
■ “_” (underscore) is also a letter.
■ E.g.: val_1 is a valid name.
■ But don’t begin variable names with underscore,
since library functions often uses such names.

10/31/2022 9
Names (Identifiers) …

■ Upper case and lower case letters are


distinct. That is x and X are two different
letters.
■ There are reserve words in the C language,
like if, else, int, float, etc., which should not
be used as variable names.

10/31/2022 10
Names …

■ Invalid names :
❑ $total
❑ 1st
❑ no.
❑ case
■ Are the following valid?
❑ _total
❑ \new
❑ end

10/31/2022 11
Constants

■ A data item whose value does not change.


■ Constants also can have names following the
same rules as that for variable names.
■ Simple numbers like 123, 0.24 are of course
constants (which are without name).

❑ More about constants follows later …

10/31/2022 12
Data Types

■ There are various categories of data items,


like integers, real numbers, character strings,
etc.
■ Each category is called a type.
■ There are inbuilt types (basic types) and user
defined types.

10/31/2022 13
Basic data types

■ character (char) 🡪 single character

■ integer (int) 🡪 an integer number

■ real (float) 🡪 a real valued number


(double) 🡪 a real valued number with
higher precision.

10/31/2022 14
Declarations

■ An identifier which you want to use should be


declared first.
■ A declaration specifies type and identifiers
name.
■ Optionally a declaration for a variable can
contain its initial value also.

10/31/2022 15
Declarations …

■ int count; /* declares that count is a


variable which can hold integer values */
■ char s, c; /* s and c are variables which can
hold a single character each */
■ float sum_1 = 0.5;
■ double d, total, sum;

❑ Declaration is a statement and every statement in C should


end with a semicolon ;

10/31/2022 16
Declarations …

■ Syntax for a declaration is:


type var_1, var_2, …,var_n;

E.g: int i, j,k;


Or, write three separate lines like: int i;
int j;
int k;

■ All the variables that you are using should be


declared first.

10/31/2022 17
Declarations …

■ Declaration specifies type and also the size


(the number of bits that should be allocated
to store the declared variable).
■ These sizes are machine (Hardware)
dependant.
■ Size determines the range of values you can
use.

10/31/2022 18
Declarations …

■ For example, if size of char is 1 byte (8 bits)


then there can be only 28 different characters
that you can use.
■ Sizes
char 🡪 1 byte
int 🡪 4 bytes
float 🡪 normally 4 bytes
double🡪 double the size of float

10/31/2022 19
Declarations …

■ For some types, you can increase (or


decrease) the size relatively by adding some
optional qualifiers to the type.
■ For int 🡺 short int
🡺 long int

■ For double 🡺 long double

10/31/2022 20
How to find the size?

■ sizeof is an operator which you can use.


E.g:
-------------------------
#include<stdio.h>
main()
{
int s;
s = sizeof( int );
printf(“The size of an int is: %d”, s);
}

10/31/2022 21
sizeof

■ sizeof is an unary operator.


■ The operand is either an expression, which is
not evaluated, or a paranthesized type name.

■ int i,j;
j = sizeof i; /* but, j = sizeof int; is wrong */

10/31/2022 22
Declarations …

■ Some other qualifiers can be used to specify the


range …

■ E.g: int 🡺 signed int


unsigned int

▪ char can also be signed or unsigned, but this


discussion is deferred.

10/31/2022 23
Declarations…

■ Some examples:
■ unsigned short int sum;
if short int is of size 1 byte, what is the range of
values that sum can hold ?
■ long double avg;

10/31/2022 24
Modifiers in C
■ The amount of memory space to be allocated for a variable is
derived by modifiers.
■ Modifiers are prefixed with basic data types to modify (either
increase or decrease) the amount of storage space allocated to a
variable.
■ For example, storage space for int data type is 4 byte for 32 bit
processor. We can increase the range by using long int which is 8
byte. We can decrease the range by using short int which is 2 byte
■ There are 5 modifiers available in C language. They are,
❑ short
❑ long
❑ signed
❑ unsigned
❑ long long

10/31/2022 25
Constants

■ Constants also has type.


■ 1234 is an int
■ A long int constant is written with a terminal l
or L. Eg: 123456789L
■ An integer too big to fit into an int will also be
taken as long.
■ Unsigned constants are written with a
terminal u or U, and the suffix ul or UL
indicates unsigned long.

10/31/2022 26
Constants …

■ Floating point constants contain a decimal


point (123.4) or an exponent (1e-2) or both;
and their default type is double, unless
suffixed.
■ The suffixes f or F indicate a float constant;
l or L indicate a long double.

10/31/2022 27
Constants …

■ An integer can be specified in octal or


hexadecimal instead of decimal.
▪ A leading 0 (zero) on an integer constant
means octal; a leading 0x or 0X means
hexadecimal.
■ Eg: decimal 31 = 037 (octal)
= 0x1f = 0X1f (hexa)
▪ What is 0XFUL in decimal?
10/31/2022 28
Constants …

■ A character constant is written within a single


quotes, like ‘x’
■ Actually a character is stored as an integer.
■ The integer value of a character is often
called as its ASCII value. (In ASCII character
set each character is given an integer value.)
■ ‘0’ 🡪 character zero 🡪 ASCII value is 48
■ ‘0’ is unrelated to the numeric value 0

10/31/2022 29
Constants
■ Some characters can not be written normally,
hence they have special codes called escape
sequences.
■ ‘\n’ 🡪 newline; ‘\a’ 🡪 bell; ‘\\’ 🡪 backslash
‘\t’ 🡪 tab; ‘\0’ 🡪 null
‘\’’ 🡪 single quote; ‘\”’ 🡪 double quote;
▪ There are some more escape characters
which you should read in the book as an
exercise.

10/31/2022 30
Constants … (Named constants)

■ The qualifier const can be applied to the


declaration of any variable to specify that its
value will not be changed.
■ Eg: const int sum = 100;

■ Some other way is through #define directive whose


discussion is deferred.

10/31/2022 31
Input and Output
int scanf (formatted input)
int i;
char ch;
scanf(“%d”, &i); /* read an integer from
stdin into i */
scanf(“%c”, &ch); /* read a char from stdin
into ch */
scanf (formatted input)

/* both can be read in a single scanf */


scanf(“%d %c”, &i, &ch);

char variable
Format string
int variable

Why there is ‘&’ character before i and ch ?


Why ‘&’ in scanf ?
⬥ Every variable should have a location in the
memory.
⬥ If i is variable’s name then &i is its address in
the memory.
⬥ scanf should be given the addresses of the
locations where it should store the read values.
scanf
⬥ Different values should be separated with a
space or newline.
■ More about this is deferred.
int printf (formatted output)

int i; char ch;


i = 125;
ch = ‘a’;
$./a.out
printf(“%d %c \n”, i, ch); 125 a
printf(“%c\n%d”,ch,i); a
125
$

Output on the screen


printf
char ch = ‘a’;
printf(“%d”, ch);

What will be the output?


How to read or write a float?
%f 🡪 float

float num;
scanf(“%f ”, &num);
printf(“%f ”, num);
What is a computer?

 a computer is a sophisticated electronic calculating machine


that:
 Accepts input information,
 Processes the information according to a list of internally
stored instructions and
 Produces the resulting output information.
 Functions performed by a computer are:
 Accepting information to be processed as input.
 Storing a list of instructions to process the information.
 Processing the information according to the list of
instructions.
 Providing the results of the processing as output.
 What are the functional units of a computer?

0
Functional units of a computer
Input unit accepts Arithmetic and logic unit(ALU):
information: •Performs the desired
•Human operators, operations on the input
•Electromechanical devices (keyboard) information as determined
•Other computers by instructions in the memory

Arithmetic Memory
Input & Logic Instr1
Instr2
Instr3
Data1
Output Data2
Control
I/O Processor
Control unit coordinates Stores
Output unit produces various actions information:
results of processing: •Input, •Instructions,
•To a monitor display, •Output •Data
•To a printer •Processing

1
Information in a computer -- Instructions

 Instructions specify commands to:


 Transfer information within a computer (e.g., from memory to
ALU)
 Transfer of information between the computer and I/O devices
(e.g., from keyboard to computer, or computer to printer)
 Perform arithmetic and logic operations (e.g., Add two numbers,
Perform a logical AND).
 A sequence of instructions to perform a task is called a
program, which is stored in the memory.
 Processor fetches instructions that make up a program from
the memory and performs the operations stated in those
instructions.
 What do the instructions operate upon?

2
Information in a computer -- Data

 Data are the “operands” upon which instructions operate.


 Data could be:
 Numbers,
 Encoded characters.
 Data, in a broad sense means any digital information.
 Computers use data that is encoded as a string of binary
digits called bits.

3
Input unit
Binary information must be presented to a computer in a specific format. This
task is performed by the input unit:
- Interfaces with input devices.
- Accepts binary information from the input devices.
- Presents this binary information in a format expected by the computer.
- Transfers this information to the memory or processor.
Real world Computer

Memory

Keyboard
Audio input
Input Unit
……

Processor

4
Memory unit
 Memory unit stores instructions and data.
 Recall, data is represented as a series of bits.
 To store data, memory unit thus stores bits.
 Processor reads instructions and reads/writes data from/to
the memory during the execution of a program.
 In theory, instructions and data could be fetched one bit at a
time.
 In practice, a group of bits is fetched at a time.
 Group of bits stored or retrieved at a time is termed as “word”
 Number of bits in a word is termed as the “word length” of a
computer.
 In order to read/write to and from memory, a processor
should know where to look:
 “Address” is associated with each word location.

5
Memory unit (contd..)
 Processor reads/writes to/from memory based on the
memory address:
 Access any word location in a short and fixed amount of time
based on the address.
 Random Access Memory (RAM) provides fixed access time
independent of the location of the word.
 Access time is known as “Memory Access Time”.
 Memory and processor have to “communicate” with each
other in order to read/write information.
 In order to reduce “communication time”, a small amount of
RAM (known as Cache) is tightly coupled with the processor.
 Modern computers have three to four levels of RAM units with
different speeds and sizes:
 Fastest, smallest known as Cache
 Slowest, largest known as Main memory.

6
Memory unit (contd..)

 Primary storage of the computer consists of RAM units.


 Fastest, smallest unit is Cache.
 Slowest, largest unit is Main Memory.
 Primary storage is insufficient to store large amounts of
data and programs.
 Primary storage can be added, but it is expensive.
 Store large amounts of data on secondary storage devices:
 Magnetic disks and tapes,
 Optical disks (CD-ROMS).
 Access to the data stored in secondary storage in slower, but
take advantage of the fact that some information may be
accessed infrequently.
 Cost of a memory unit depends on its access time, lesser
access time implies higher cost.

7
Arithmetic and logic unit (ALU)

 Operations are executed in the Arithmetic and Logic Unit


(ALU).
 Arithmetic operations such as addition, subtraction.
 Logic operations such as comparison of numbers.
 In order to execute an instruction, operands need to be
brought into the ALU from the memory.
 Operands are stored in general purpose registers available in
the ALU.
 Access times of general purpose registers are faster than the
cache.
 Results of the operations are stored back in the memory or
retained in the processor for immediate use.

8
Output unit
•Computers represent information in a specific binary form. Output units:
- Interface with output devices.
- Accept processed results provided by the computer in specific binary form.
- Convert the information in binary form to a form understood by an
output device.

Computer Real world

Memory Printer
Graphics display
Speakers
……
Output Unit

Processor

9
Control unit

 Operation of a computer can be summarized as:


 Accepts information from the input units (Input unit).
 Stores the information (Memory).
 Processes the information (ALU).
 Provides processed results through the output units (Output
unit).
 Operations of Input unit, Memory, ALU and Output unit are
coordinated by Control unit.
 Instructions control “what” operations take place (e.g. data
transfer, processing).
 Control unit generates timing signals which determines
“when” a particular operation takes place.

10
How are the functional units connected?
•For a computer to achieve its operation, the functional units need to
communicate with each other.
•In order to communicate, they need to be connected.

Input Output Memory Processor

Bus

•Functional units may be connected by a group of parallel wires.


•The group of parallel wires is called a bus.
•Each wire in a bus can transfer one bit of information.
•The number of parallel wires in a bus is equal to the word length of
a computer

11
Computer Components: Top-Level View
Software
 In order for a user to enter and run an application
program, the computer must already contain some system
software in its memory

 System software is a collection of programs that are


executed as needed to perform functions such as
 Receiving and interpreting user commands
 Running standard application programs such as word
processors, etc, or games
 Managing the storage and retrieval of files in
secondary storage devices
 Controlling I/O units to receive input information and
produce output results
Software

 Translating programs from source form prepared by


the user into object form consisting of machine
instructions

 Linking and running user-written application programs


with existing standard library routines, such as
numerical computation packages

 System software is thus responsible for the


coordination of all activities in a computing system
Operating System
 Operating system (OS)
 This is a large program, or actually a collection of routines,
that is used to control the sharing of and interaction among
various computer units as they perform application programs
 The OS routines perform the tasks required to assign computer
resource to individual application programs
 These tasks include assigning memory and magnetic disk
space to program and data files, moving data between
memory and disk units, and handling I/O operations
 In the following, a system with one processor, one disk, and one
printer is given to explain the basics of OS
 Assume that part of the program’s task involves reading a
data file from the disk into the memory, performing some
computation on the data, and printing the results
Basic Operational Concepts of Computer System

Make-Up Class I
Review
● Activity in Computer is governed by Instructions.

● To perform a task, an appropriate program consisting of a list of instructions is stored in the


memory.

● Individual instructions are brought from memory into the processor, which executes
specified operations.

● Data to be used as operands are also stored in the memory.


Connection Between Processor and Memory, I/O
Components
Set of Registers

● IR: Instruction Register.


● PC: Program Counter.
● MAR: Memory Address Register.
● MDR: Memory Data Register.
● General Purpose Registers: R0-R_{n-1}
Operating Steps

1. Program resides in the memory.


2. PC is set to point to the 1st instruction.
3. Content of PC is transferred to MAR.
4. A Read signal is sent to memory.
5. First instruction is read out and loaded into MDR.
6. The content of MDR transferred to IR.
7. Decode and Execute the instruction.
Operating Steps(Contd.)

❖ Get Operands for ALU


➢ General Purpose Registers
➢ Memory (Address->MAR; Read->MDR->ALU)
❖ Perform Operation in ALU.
❖ Store the result back.
➢ To the General Purpose Registers
➢ To Memory (Address->MAR; Result to MDR; Write)
❖ PC is incremented to Next Instruction.
Data Types in C
(a deeper dive)

This slide deck is influenced by Prof. Nisheeth Srivastava , IIT Kanpur.


Basic Data Types in C
▪ Int: %d specifier
▪ Integers like 156, -3, etc
▪ float (short form of “floating point number”) and double: %f specifier
▪ Real numbers like 3.14, 2.0, -1.3, etc
▪ double is like float but has larger range
▪ char (short form of “character”): %c specifier
▪ Single letter (a-z or A-Z), single digit, or single special character
▪ A char is always enclosed in inverted single commas
▪ Some examples: ‘a’, ‘A’, ‘2’, ‘$’, ‘=‘
▪ These basic data types can also be used with a modifier
▪ Modifiers change the normal behaviour of a data type (e.g., its range of values) and
memory storage space required (more on next slides)
Type Modifiers in C
▪ signed (used with int, float/double, char)
▪ signed means the data type can have positive and negative values
▪ int, float/double, char are signed by default (no need to write ‘signed’)
▪ unsigned (used with int, char)
▪ unsigned means the data type can have only take positive values
▪ short (used with int)
▪ short means it uses only half of the memory size of a normal int
▪ long (used with int)
▪ long means it uses twice the memory size of a normal int
▪ Can store a larger range of values of that type
3
Various C Data Types without/with Modifiers
int (signed unsigned short int long int
int) int (short) (long)
%d %u %d %ld
short long Yes, multiple
modifiers also
unsigned unsigned allowed
%u %lu

float double long double


%f %lf %Lf

char unsigned
char
%c %u 4
int
• Can store integers between -2,147,483,648 and 2,147,483,647

#include <stdio.h> Range: -2^31 to (2^31)-1


int main(){
%d signed int uses 32 bits
int a; (4 bytes, 8 bits = 1 byte)
a on recent compilers)
scanf(“%d”, &a);
printf(“My first int %d”, a); Integer arithmetic applies to
return 0; integers +, -, /, *, %, ()
}
Printing well-formatted outputs using printf
▪ When printing an int value, place a number between % and d (say
%5d) which will specify number of columns to use for displaying that
value Output
int x = 2345, y=123; 2345
printf("%d\n",x); //Usual (and left aligned) 2345
123
printf("%6d\n",x); //Display using 6 columns (right aligned)
2345
printf("%6d\n",y);

printf("%2d\n",x); //Less columns than digits, same as %d

Note: So far, we have only seen how to print integers.


We will see how to print other types of variables later today 6
printf : Controlled printing of float/double
▪ Already saw how to use printf for well-formatted int display
▪ Can also control how to display a float/double using printf
▪ Can do it using “%a.bf ” specifier where a and b are numbers
▪ Here a is the total field width (number of columns) in which the float will be
displayed, b is the number of digits printed after decimal

float pi = 3.141592; Output


printf("%f\n",pi); //Usual
3.141592
printf("%6.2f\n", pi); //2 decimal
3.14
printf("%0.4f\n",pi); //4 decimal 3.1416
// Note rounding off!
7
long int (usually written just long)
• Really long – can store integers between
• -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807
Range: -2^63 to (2^63)-1
#include <stdio.h>
int main(){ long int uses 64 bits
on recent compilers
long a; //long int also
scanf(“%ld”, &a);
a Integer arithmetic applies to long
int as well +, -, /, *, %, ()
printf(“My first long int %ld”, a);
return 0; %ld
}
Mixing Types in C Expressions
▪ We can have C expression with variables/constants of several types
▪ Certain rules exist that decide the type of the final value computed
•▪ int
Demotion
a = 2/3;and Promotion are// atwo
willcommon rules
be 0 (no demotion/promotion)
• float a = 2/3; // a will be 0.0 (RHS is int with value 0,
promoted to float with value 0.0)
• int a = 2/3.0; // a will be 0 (RHS is float with value 0.66,
becomes int with value 0)
• float a = 2/3.0; // a will be 0.66 (RHS is float with value 0.66, no
demotion/promotion)
• int a = 9/2; // a will be 4 (RHS is int with value 4, no
demotion/promotion)
•▪ float
Duringa =demotion/promotion,
9/2; thebeRHS
// a will 4.0 value doesn’t
(RHS is change,
int with only
value 4, the
becomes
data with
float type value
of the4.0)
RHS value changes to the data type of LHS variable
9
Type Casting or Typecasting
▪ Converting values of one type to other.
▪ Example: int to float and float to int (also applies to other types)
▪ Conversion can be implicit or explicit. Typecasting is the explicit way
Automatic
(compiler) By us

▪ int k =5;
▪ float x = k; // good implicit conversion, x gets 5.0
▪ float y = k/10; // poor implicit conversion, y gets 0.0
▪ float z = ((float) k)/10; // Explicit conversion by typecasting, z gets 0.5
▪ float z = k/10.0; // this works too (explicit without typecasting), z gets 0.5
10
Typecasting: An Example Program

#include <stdio.h> #include <stdio.h> Typecasting


int main(){ int main(){ makes it
50.0/100
int total = 100, marks = 50; int total = 100, marks=50;
Equals which
float percentage; 0 float percentage; equals 0.5
percentage = (marks/total)*100; percentage = (float)marks/total*100;
printf("%.2f",percentage); printf("%.2f",percentage);
return 0; 0.0 return 0; 50.0
} 0 0
}

11
Typecasting is Nice. But Take Care..
#include <stdio.h> #include <stdio.h>
int main(){ int main(){
float x; int y; float x; int y;
x = 5.67; x = 1.0e50; // 10^50
y = (int) x; // typecast (convert) float to int y = (int) x; // typecast (convert) float to int
printf(“%d”,y); printf(“%d”,y);
-2147483
return 0; 5 return 0;
648
} }

No. 1.0e50 is too big


to be cast as an int
(or even long – try
yourself)
12
int and long 13
Very good friends since both store integers
Can add/subtract/multiply/divide/remainder two ints,
two longs, as well as an int and a long
In fact, even if we try to print an int using %ld or print a
long using %d, Compiler will only warn us, not throw an
error (but results at run-time may be unexpected
sometimes)
long can store much So I don’t have to be
larger integers than int careful about anything?

long can store smaller


integers too ☺
int and long Why not just define a
long variable? No
need for typecasting!
14
#include
I often create<stdio.h>
such Thankfully,#include
Dotted line means we now <stdio.h>
Often, you don’t have I create know
these typecasting. It I should try this too:
variables
int main(){ but you int main(){
control over the kind of data variables
Too big ☹ can
myself
I will save us here. long b = 2*(long)a;
never get to know
you int
receive. long b = (long)a + a;
a =☺Typecasting
2000000000; do my best but ☺ int a = 2000000000; ☺
helps convert data to a form there will be
These
long variables
your like bto =work
a +with
a; errors long b = (long)a + (long)a;
4000000000
-294967296
help me carry out
yourprintf("%ld",b);
requests nicely printf("%ld",b);
40000
} } 00000

20000 40000
-
02949 20000
00000 67296 00000
00000
a b a b
Mixed Type Operations (Already Saw Some
Cases)
15
Hmm … An int being multiplied to a long.
What if we have mixed types in a formula?
Let me take care to convert the int to a int a = 2;
c = a * b; long before performing the operation ☺
long c, b = 5;
Can typecast int to long
b = (long) a; Be careful! If b was storing
a very large integer that
Can typecast long to int won’t fit into int, this
typecast will cause errors
a = (int) b;
In general, we should typecast weaker types
like int into more powerful types like long and
2 5 10
float that can store larger numbers

a b c
Note: When printing a char
Arithmetic on char data type using printf, the quote symbols ‘
‘ are not shown
▪ Recall that each char is associated with an integer value
Note: When giving
char input for scanf,
▪ Example: char ‘A’ to ’Z’ are associated with integers 65 to 90 we don’t type the
quote symbols ‘ ‘
▪ Refer to the ASCII table.
▪ Note: signed char range is -128 to 127, unsigned char range is 0 to 255 Try in
Prutor
and see
#include <stdio.h> #include <stdio.h> First number yourself
from the
int main(){ int main(){
-12 negative side
int x = ‘B’ - ‘A’ + 2; 3 char x = 128;
8 Second number
printf(“x = %d\n”, a); printf(“x = %d\n”, x); from the positive
char y = 68; D char y = -130; 126 side
What if x
printf(“y = %c”,y); printf(“y = %d\n”,y);
and y are
return 0; return 0; unsigned
128 and -130 are out of the
} } range of signed char char ? 16
Arithmetic on char data type: More Examples
▪ Keep in mind that char and int are inter-convertible
So if you want, I can
Output:
use/print a char as int
printf("%d\n", 'A'); 65 and int as char (within
55 char limits of course
printf("%d\n", '7'); F ☺)
printf("%c\n", 70); 321 is out of range of signed Try it and see
printf("%c\n", 321); char (and even unsigned what happens
char)

Output:
printf("%c\n", ‘C’+5); H
printf("%c\n", ‘D’ - ‘A’ + d
53 * and / are also
‘a’ ); valid but should
printf("%d\n", ‘3’ + 2); avoid with char 17
Representing Negative Integers
• Mainly three ways
• - Signed Magnitude
• - One’s Complement
• - Two’s Complement (used in modern computers)

• The Signed Magnitude approach is straightforward: To represent –x,


take binary representation of x and make the left-most bit 1. So -7
(7 in binary = 111) will be
1 0 0 0 0 0 1 1 1 (-7 in signed magnitude)

Position reserved
as sign bit
One’s Complement
• The
Theone’s
first complement
bit acts as a signof abit
binary number
– if the first bitisissimply
1, it is the bitwise
treated as a
complement
negative number, of that binary
if the number
first bit is 0, it is treated as a positive number
• A long time ago (25-30 years ago) one’s complement used to be
usedIftowerepresent
have n bits, then using
negative numbers one’s complement, we can
represent numbers between –(2n-1 – 1) and +(2n-1 – 1)
• 35 as a 4 byte int is represented as
0000 0000positive
Largest 0000integer
0000 is0000 0000 11111111
01111111 0010 0011 11111111 11111111
So, in those
• Smallest old computers,
negative -35 used00000000
integer is 1000000 to be represented
00000000as 00000000
1111 1111 1111 1111 Weird 1111
thing – 1111
negative11010☺ 1100
• Note that b + ~b 11111111
= 11111111 11111111 11111111
11111111 1111111111111111
11111111
• Used no more. These days, computers use two’s complement to
represent negative integers
Two’s Complement
• Two’s complement of an n-bit binary number is the number which when
added to this number, gives 2n
• 2n =1 0 0 0 0 0 0 0 …… 0 (1 followed by n zero bits)
• This means two’s complement of b is 2n – b
• Recall that b + ~b = all ones = 2n – 1 i.e. two’s complement of b is 2n – b =
~b + 1
• So a way of calculating two’s complement – take the one’s complement
and add 1 to the binary string
• These days two’s complement of an integer n represents its negative (that
is –n)
• So for any integer n, one’s complement of n will be -(n+1)
Two’s Complement
The first bit acts as a sign bit – if the first bit is 1, it is treated as a
negative number, if the first bit is 0, it is treated as a positive number

Largest positive number is 01111111 11111111 11111111 11111111


Smallest negative number is 1000000 00000000 00000000 00000000
11111111 11111111 11111111 11111111 now represents -1 ☺

If we have n bits, then using two’s complement, we can


represent numbers between –2n-1 and +(2n-1 – 1)
Floating Point Representation
▪ Have to represent three things
▪ sign
▪ Exponent
▪ Number

▪ Assign some bits of memory for each


▪ 1 bit for sign
▪ E bits bits for exponent
▪ M for mantissa
Conceptual Example
• Consider a 4 bit memory
– What can you assign with unsigned int?
• 0,1,.....15
– What can you assign with signed int?
• Use twos complement notation
• -8,-7,.... ,7
– What can you assign with float?

s e m m 1.0, 1.1, 1.2, 1.3


2.0, 2.2, 2.4, 2.6
-1.0, -1.1, -1.2, -1.3
(-1)s * 1.m* 2e-0 -2.0, -2.2, -2.4, -2.6

This m is the decimal equivalent of 2 bits m m


Conceptual Example
● Let M and E be 3 bits for each. M and E are in Signed Magnitude.

Highest Number: ?
Least Positive Number: ?

Least Number: ?
Conceptual Example
Normalization and biasing

1.0 x 10^2 =0.1 x 10^3 =10.0x10^1


Issue with Representing Zeros
● Argument I:

1. M x B^E; M=0; E can be any values.

A=0.1x2^(-2); B=0.1x2^(-2);

M=0.00 1 x2^(-3)
M=0; E=-K;
Issue with Representing Zeros
● Argument II: Desirability of representing zero with sequence of 0
bits.

Desired Exponent= Actual +K;

Biased Exponent!
IEEE 754 Floating Point Representation
Single-precision (float)

This is what you’re using when you are invoking float


Practical demonstration
• 12.375 = 12 + 0.375
• In binary = 1100 + .011 = 1100.011
• In IEEE notation = 1.100011 x 23
• So, the bias is 3, which means the exponent must be 127+3 =
130, which in binary format is 10000010
• So, the number, in IEEE single precision format will be
– 0 – 10000010 - 10001100000000000000000

30
math.h 31
A really nice library of lots of mathematical functions
abs(x): absolute value of integer x
fabs(x): absolute value of x if x is float or double
ceil(x): ceiling function (smallest integer greater than x)
floor(x): floor function (largest integer smaller than x)
log(x): logarithm of x (do not give negative value of x)
pow(x,y): x to the power y (both doubles – typecast if int)
sqrt(x): square root of double x (typecast if not double)
cos(x), sin(x), tan(x) etc are also present – explore!
Operators 32
We have seen quite a few math operators till now
+, -, *, /, %
All take two numbers and give one number as answer
Called binary operators for this reason. Binary = two
Many unary operators also exist
Have seen two till now:
Unary negation int a = -21; b = -a;
Typecasting c = (int) a;
Will see several more operators in the next class
Also will start expanding our programming power
Conditional statements and relational operators
The Loop Control Structure

* 1
Bitwise Operators
Operation C Code a b c d e f

BITWISE c=a&b 0000 1111 0000 1111 1111 1111


AND

BITWISE d=a|b 0101 1100 0100 1101 1001 1010


OR

BITWISE e=a^b 1010 1110 1010 1110 0100 0101


XOR

BITWISE f = ~a 1001 0111 0001 1111 1110 0110


COMPLEMENT

* 2
Bitwise Operators
• The output of bitwise AND is 1 if the corresponding bits of two operands
are both 1. If either bit of an operand is 0, the result of corresponding bit is
evaluated to 0
• In C Programming, bitwise AND operator is denoted by &
■12 = 00001100 (In Binary) ■#include <stdio.h>
■25 = 00011001 (In Binary)
■int main(){
■Bitwise AND of 12 and 25
■ int a = 12, b = 25;
■ 0000 1100
■ printf("Output = %d", a & b);
■& 0001 1001
■ return 0;
■ ________
■}
■ 0000 1000 = 8 (In decimal)

* 3
Bitwise OR Operator |
• The output of bitwise OR is 1 if at least one of the
corresponding bit of two operands is 1
• In C Programming, bitwise OR operator is denoted by |
■12 = 00001100 (In Binary) ■ #include <stdio.h>
■25 = 00011001 (In Binary)

■Bitwise AND of 12 and 25


■ int main(){
■ 0000 1100 ■ int a = 12, b = 25;
■| 0001 1001
■ printf("Output = %d", a | b);
■ ________
■ 00011101 = 29 (In decimal)
■ return 0;
■ }
* 4
Bitwise XOR Operator ^
• The result of bitwise XOR operator is 1 if the corresponding bits of two
operands are opposite i.e. one is 1 and the other is 0
• In C Programming, bitwise XOR operator is denoted by ^

■12 = 00001100 (In Binary) ■ #include <stdio.h>


■25 = 00011001 (In Binary)
■ int main(){
■Bitwise XOR of 12 and 25
■ int a = 12, b = 25;
■ 00001100

■^ 00011001
■ printf("Output = %d", a ^ b);
■ ________ ■ return 0;
■ 00010101 = 21 (In decimal)
■ }
* 5
Bitwise Complement Operator ~
• A unary operator that simply flips each bit of the input
• In C Programming, bitwise complement operator is denoted by ~

■12 = 0000 0000 0000 0000 0000 0000 0000 1100 ■ #include <stdio.h>
Bitwise complement of 12
■~ 0000 0000 0000 0000 0000 0000 0000 1100
■ int main(){
■ _____________________________________ ■ int a = 12;
■ 1111 1111 1111 1111 1111 1111 1111 0011 ■ printf("Output = %d", ~a);
■= -13 (decimal)
■ return 0;
■ }

* 6
Right Shift Operator >>
• Right shift operator shifts all bits towards right by a certain number of
locations
• Bits that “fall off” from the right most end are lost
• Blank spaces in the leftmost positions are filled with sign bits
• 212 = 0000 0000 0000 0000 0000 0000 1101 0100
• 212 >> 0 = 0000 0000 0000 0000 0000 0000 1101 0100
• 212 >> 4 = 0000 0000 0000 0000 0000 0000 0000 1101
• 212 >> 6 = 0000 0000 0000 0000 0000 0000 0000 0011
• 212 >> 3 = 0000 0000 0000 0000 0000 0000 0001 1010
• Right shift by k is equivalent to integer division with 2k

* 7
Left Shift Operator <<
• Left shift operator shifts all bits towards left by a certain number of
locations
• Bits that “fall off” from the left most end are lost
• Blank spaces in the right positions are filled with 0s
• 212 = 0000 0000 0000 0000 0000 0000 1101 0100
• 212 << 0 = 0000 0000 0000 0000 0000 0000 1101 0100
• 212 << 4 = 0000 0000 0000 0000 0000 1101 0100 0000
• 212 << 6 = 0000 0000 0000 0000 0011 0101 0000 0000
• 212 << 28 = 0100 0000 0000 0000 0000 0000 0000 0000
• Left shift by k is equivalent to integer multiplication with 2k

* 8
Example use of bitwise operators
• Can use “masks” to extract certain bits of a number
• Suppose I want to look at the last 6 bits of a number a
• Create a mask with only last bits set to 1 and take & with a
■int a = 427;
■a = 0000 0000 0000 0000 0000 0001 1010 1011
■int p = 1;
■p = 0000 0000 0000 0000 0000 0000 0000 0001
■int q = p << 6;
■q = 0000 0000 0000 0000 0000 0000 0100 0000
■int m = q – 1;
■m = 0000 0000 0000 0000 0000 0000 0011 1111
■int r = a & m;
■r = 0000 0000 0000 0000 0000 0000 0010 1011
■printf("%d", r); // 43

* 9
Precedence Table with Bitwise Operators
Operators Description Associativity
unary + -, ++, --, type, Unary plus/minus, increment/decrement, typecast, Right to left
sizeof, ~ sizeof, bitwise complement
*/% Arithmetic: Multiply, divide, remainder Left to right
+- Arithmetic: Add, subtract Left to right
<< >> Bitwise left-shift, bitwise right shift Left to right
< > >= <= Relational operators Left to right
== != Relational operators Left to right
& Bitwise AND Left to right
^ Bitwise XOR Left to right

| Bitwise OR Left to right

* 10
Precedence Table with Bitwise Operators
Operators Description Associativity
&& Logical AND Left to Right

|| Logical OR Left to Right


?:: Conditional Right to Left
= Assignment Right to Left

* 11
Loops
■ It is useful to repeatedly execute a
subsequence of statements based on a
condition.
■ There are three methods:
❑ Using a while statement
❑ Using a for statement
❑ Using a do-while statement
* 12
while
■ syntax:
while (expression)
statement
■ the expression is evaluated. If it is non-zero,
statement is executed. This process is repeated.
■ The cycle continues until the expression
becomes zero.

* 13
while
■ To count number of characters
❑ int count = 0;
char ch;
ch = getchar( );
while ( ch != ‘\n’ ) {
count ++;
ch = getchar( );
*
} 14
while
■ To count number of characters
❑ int count = 0;
char ch;
while ( (ch = getchar( ) ) != ‘\n’ )
count ++;
printf(“you entered %d characters”, count);

* 15
while
■ To count number of characters
❑ int count = 0;
char ch;
ch = getchar( );
while ( ch != ‘\n’ ) {
count ++;
}
printf(“you entered %d characters”, count);

❑ This could result into an infinite loop and as a result the program can not
terminate !
* 16
Breaking with break;
■ To count number of characters
❑ int count = 0;
char ch;
while ( 1 ) {
ch = getchar( );
if ( ch == ‘\n’ ) break;
else count ++;
}
printf(“you entered %d characters”, count);
* 17
for loop
■ The for statement syntax is:
❑ for(expr1; expr2; expr3)
statement
■ This is equivalent to:
❑ expr1;
while (expr2) {
statement
expr3; }

* 18
for
■ for(expr1; expr2; expr3)
statement
▪ expr1 is the initialiser
▪ expr2 is the test condition
▪ expr3 is the increment expression
* 19
for
■ To read 10 integers and sum them
■ int sum=0,s;
int j;
for(j=0; j<10; j++)
{ scanf(“%d”,&s);
sum=sum+s;
}
▪ j retains its value after the for loop
* 20
for to replace a while
int count = 0;
char ch;
ch = getchar( );
while ( ch != ‘\n’ )
{ count ++; ch = getchar( ); }
printf(“you entered %d characters”, count);
This is equivalent to
int count = 0;
char ch;
for (ch = getchar( ); ch != ‘\n’; count++ )
ch = getchar( );
printf(“you entered %d characters”, count);
* 21
for
■ for(expr1; expr2; expr3) statement
■ Either expr1 or expr2 or expr3 could be
empty.
■ if expr2 is empty it means true.
■ for(;;) statement 🡺 infinite loop; has to be
broken by break;

* 22
Comma ,
■ comma can be used both as an operator and
as a separator.
■ int j,k,l; /* , is a separator */
■ printf(“%d %d %c”, j, k, c); /* , is a
separator*/
■ expr1,expr2 🡪 is an expression and has value
equal to expr2
■ comma has precedence less than = (assignment).
*
■ Associativity is from left to right 23
Comma
■ j = (2,3); /* what is the value of j*/
It is 3
■ j = 2,3; /* what is the value of j */
It is 2 because (j=2),3;
■ j = (2,3,4,5); /* value of j ? */
It is 5 because j = (((2,3),4),5)
■ comma is often used with for loops
* 24
for
■ /* a[ ] is an array of 10 elements */
for(j=0, k=9; j < k; j++,k--) {
t = a[j];
a[j] = a[k];
a[k] = t;
}
* ▪ This will reverse the order of elements in the 25
Do-while
■ Do it first and then test the condition
■ Syntax :
❑ do
statement
while ( expression );
■ The statement is executed, then expression is evaluated. It it is
true, statement is evaluated again, and so on.
■ When the expression becomes false the loop terminates.

* 26
Do-while
■ char ch[128];
int j = 0;
do {
ch[j ++] = getchar( );
} while(ch[j -1] != ‘\n’);
ch[j -1] = ‘\0’;

*
remember that there is ; after while( … ) 27
Break and continue
■ break; breaks, continue; continues
■ Just like in switch, break; exits the loop
■ In case of nested loops like
❑ while(exp1){
while(exp2) {
statement1
beak;
}
statement2
}
■ break; causes the innermost loop to be exited.
* 28
continue;
■ It skips the rest in the loop and continues with next
iteration of the loop.
■ In case of for loop it skips the rest of the loop, but it
does the increment step before continuing with next
iteration.
■ The continue statement applies only to loops, not to
switch.

* 29
continue example
■ This reads ten numbers but prints roots for only +ve numbers.
■ for( j=0; j < 10; j++) {
scanf(“%f”, &v);
if (v < 0) continue;
else {
sv = sqrt(v); /* include<math.h> */
printf(“root is %f\n”, sv);
}
}
* 30
Nested loops
int j, a[5];
int m;
do{
char ch;
for(j=0;j<5;j++)
scanf(“%d”, &a[j]);
m=a[0]; j =1;
while(j<5){
if(m < a[j]) m = a[j];
j ++;
}
printf(“Max is %d \n Want to enter another five ints:”,m);
ch = getchar();
}while(ch == ‘y’ || ch == ‘Y’);

* 31
Nested loops; sorting
/* a[ ] is an int array of 10 elements */
int j,k;
int t;
for(j=10; j >1; j--) {
for(k=0; k < j -1; k++) {
if(a[k] > a[k+1]) {
t = a[k]; a[k] = a[k+1]; a[k+1] = t;
}
}
} /* this is called bubble sort */

* 32
Nested loops; sorting
/* a[ ] is an int array of 10 elements */
int j,k;
int t;
for(j=10; j >1; j--)
for(k=0; k < j -1; k++)
if(a[k] > a[k+1])
t = a[k], a[k] = a[k+1], a[k+1] = t;

* 33
Expressions and Operators in C
Expressions in C
▪ We use math formulae all the time in physics, chem,
math
▪ a=b/5
▪ x=y*y+z*z
▪ x = (int)(pow((double)y, 2.0) + pow((double)z, 2.0))

▪ these formulae expressions


▪ x = y * y + z * z is an expression for C
▪ y * y + z * z is also an expression for C
▪ y * y is also an expression for C
▪ z * z is also an expression for C

2
Expressions and Operators
▪ Expressions in C consist of one or more variables/constants
▪ An expression contains one or more operators, such as
c = a + b - 2;
▪ Operators in C can be one of the following type
Yes.
▪ Arithmetic But I will tell you
▪ Unary some other I think I have
interesting things already seen/used
▪ Relational and logical about them and Arithmetic and
▪ Assignment other operators Assignment
▪ Conditional operators in
previous
lectures/labs! 3
Arithmetic operators
▪ Already seen. Operate on int, float, double (and char)
Op Meaning Example Remarks

+ Addition 9+2 is 11
9.1+2.0 is 11.1
- Subtraction 9-2 is 7
9.1-2.0 is 7.1
* Multiplication 9*2 is 18
9.1*2.0 is 18.2
/ Division 9/2 is 4 Integer division
9.1/2.0 is 4.55 Real division
% Remainder 9%2 is 1 Only for int
4
Unary operators
Operator
- Negative of an expression

++/-- Increment/decrement a variable

sizeof Output memory box size for a variable

type (examples: int, float, double, etc) Type-casting

5
Unary Operators - Negative
▪ Operators that take only one argument (or operand)
▪ -5
▪ -b
▪ Observe that – is both an arithmetic and unary operator
▪ Meaning depends on context
▪ This is called overloading

6
Unary operators – increment and decrement
▪ Increment (++) increases a variable by 1
▪ Decrement (--) decreases a variable by 1 Note: The variable’s
▪ ++variable is the pre-increment operator value will change
for the rest of the
▪ Means increment, then use program
▪ variable++ is the post-increment operator
▪ Means use, then increment Work with
▪ Likewise, the -- can be pre/post decrement all data
types
int main(){
char a = ‘A’; float b = 3.31;
printf("%c\t%f\n",++a,b++); B 3.31
printf("%c\t%f",--a,b--);
return 0; A 4.31
}
7
Unary operators - sizeof
▪ Syntax
▪ sizeof var
▪ sizeof(type)
▪ Returns size of the operand in bytes
▪ sizeof(char) will return 1
▪ sizeof(float) will (mostly) return 4
▪ Very useful when you are porting programs across computers

8
Unary operators - typecast
▪ Syntax
▪ (type) var, for example – (int) a, (float) a, etc
▪ We have already seen this Size is 8
▪ What will be the output of this program? Size is 1
C
int main(){
double a = 67.2;
printf("size is %d\n", sizeof a);
printf("size is %d\n", sizeof((char) a));
printf("%c", (char) a);
return 0;
} 9
Precedence Rules for Unary Operators
▪ Precedence rules tell us the order in which the operators will be
applied in any C expression
Bracket
▪ Unary ops are above arithmetic ops, only below brackets has the
▪ If a is 1 and b is 2, what will a + -b be evaluated as? highest
precedenc
-1
e
▪ What about this program?
3
int main(){
int a = 1; int b = 2;
printf("%d", a + - + - b);
return 0;
} 10
Note +x is x
Associativity Rules for Unary Operators
▪ Associativity rules tell us how the operators of same precedence are
grouped (e.g., a+b+c will be evaluated as (a+b)+c, not a+(b+c))
▪ For unary operators, the associativity is from right to left
▪ Important to remember this
▪ Most other operators’ associativity is left to right (e.g., + operator)
▪ What will this program print?
-2
int main(){
int a = 1;
printf("%d", - ++a);
return 0;
} 11
Relational Operators
▪ Compare two quantities Result
Operator Function is 0 or
> Strictly greater than 1
>= Greater than or equal to
< Strictly less than
<= Less than or equal to
== Equal to
1 means
!= Not equal to condition
▪ Work on int, char, float, double… true, 0
means
false
12
Relational Operators: Some Examples
Rel. Expr. Result Remark
3>2 1
3>3 0
‘z’ > ‘a’ 1 ASCII values used for char
2 == 3 0
‘A’ <= 65 1 'A' has ASCII value 65
‘A’ == ‘a’ 0 Different ASCII values
(‘a’ – 32) == ‘A’ 1
5 != 10 1
1.0 == 1 AVOID May give unexpected result due to
approximation

Avoid mixing int and float values while comparing.


Comparison with floats is not exact! 13
Assignment Operator
• Basic assignment (variable = expression)

Variant Meaning
Var += a Var = Var + a
Var -= a Var = Var – a
Var *=a Var = Var *a
Var /=a Var = Var/a
Var %=a Var = Var%a
14
Precedence of Assign Operators
▪ Always the last to be evaluated
▪ x *= -2 *(y+z)/3
▪ x = x*(-2*(y+z)/3)
▪ Seldom need to worry about it

15
Earlier the ASCII
table. Now this
Operator Precedence table? Have to
memorize this??
Operators Description Associativity

HIGH (unary) + - Unary plus/minus Right to left


*/% Multiply, divide, remainder Left to right
No.
+- Add, subtract Left to right
Write it
< > >= <= less, greater comparison Left to right
== != Equal, not equal Left to right
in your
= Assignment Right to left noteboo
LOW
k
Example: a + b – c * d % e /f
(a+b) - (((c *d ) % e) / f)

16
Logical Operators
Logical Op Function Allowed Types

&& Logical AND char, int, float, double


|| Logical OR char, int, float, double
! Logical NOT char, int, float, double
▪ Remember
▪ value 0 represents false.
▪ any other value represents true.
Compiler returns 1 by default
17
Logical Operators: Truth Table
“E” for
expression E1 E2 E1 && E2 E1 || E2
0 0 0 0
0 Non-0 0 1
Non-0 0 0 1
Non-0 Non-0 1 1

E !E
0 1
Non-0 0
18
Logical Operators: Some Examples
Expr Result Remark
2 && 3 1
2 || 0 1
‘A’ && ‘0’ 1 ASCII value of ‘0’≠0
‘A’ && 0 0
‘A’ && ‘b’ 1
! 0.0 1 0.0 == 0 is guaranteed
! 10.05 0 Any real ≠ 0.0
(2<5) && (6>5) 1 Compound expr

19
Logical Operators: Precedence and Associativity
▪ NOT has same precedence as equality operator
▪ AND and OR are lower than relational operators
▪ OR has lower precedence than AND
▪ Associativity goes left to right
2 == 2 && 3 == 1 || 1==1 || 5==4

1 && 0 || 1 || 0

0 || 1 || 0 1 || 0 1 20
Operator Precedence for various operators
Note: Precedence of brackets () are above every other operator
Note: This list
Operators Description Associativity doesn’t include
unary + unary - Unary plus/minus Right to left some other
HIGH operators that
*/% Multiply, divide, remainder Left to right
I we have not
N +- Add, subtract Left to right yet seen
C
R < > >= <= Relational operators Left to right
E
== != Equal, not equal Left to right
A
S && And Left to right
I
N || Or Left to right
G
= Assignment Right to left
LOW
21
Decision and Branching

11/14/2022 1
Recap:Logical Operators: Precedence and Associativity
▪NOT has same precedence as unary operators (thus very high
precedence)
▪AND and OR have lower precedence than relational operators
▪OR has lower precedence than AND (important)
▪Associativity for logical operators is left to right

2 == 2 && 3 == 1 || 1==1 || 5==4


1 && 0 || 1 || 0
0 || 1 || 0 1 || 0 1
The Conditional Operator
▪ The conditional operator is of the form

Expression 1 ? Expression 2 : Expression 3


▪ Meaning: Evaluate expression 1, if it is true (non-zero), evaluate expression 2,
otherwise evaluate expression 3
▪ The operator generates the value of expression 2 or expression 3
▪ Often, we assign the result to another variable (a = exp1 ? exp2 : exp3)
▪ Data type of generated value ? Whichever of exp2 or exp3 is of higher type
▪ Precedence of cond. operator is just above assignment operators
▪ Associativity of cond. operator is right to left

3
Conditional Operator: Examples
■ z = (a > b) ? a : b; /* z = max(a, b) */
■ x = 5 ? 0:1; /* what is value of x */

11/01/2022 4
Conditional Operator: Examples
■ a = (i>0) ? 100 : 10; /* a will be 100
or 10 depending on i */
▪ a = (i>0)? 10.0 : 5; /* RHS result
will be a float */

11/01/2022 5
Conditional Operator: Examples
■ A sophisticated example (expression 1
consisting of multiple operators)
▪ c += ( a>0 && a<=10 ) ? ++a : a/b;
▪ The above will first evaluate a>0 && a<=10 and
then choose ++a or a/b
▪ Result from RHS will be added to c (c = c + result)

11/01/2022 6
Now our table is..
Note: Precedence of brackets () is above every other operator
HIGH
Operators Description Associativity

(unary) + -, ! Unary plus/minus, logical NOT Right to left

*/% Multiply, divide, remainder Left to right

+- Add, subtract Left to right


Precedence

< > >= <= Relational operators Left to right

== != Equal, not equal Left to right

&& Logical And Left to right

|| Logical Or Left to right

?: Conditional Right to left

= Assignment Right to left

LOW
7
Quiz
0 <= 10 <= 4

0 <= 10 && 10 <= 4

11/01/2022 8
Statements
■ An expression such as x = 0 or j++ becomes
a statement when it is followed by a semicolon ;
■ Braces { and } are used to group declarations
and statements together into a compound
statement.
❑ { int j; j=2+3; j++; } /*this entire thing now is a statement */

■ Compound statement is also called block.

11/14/2022 9
Compound Statement
■ Variables can be declared in any block.
Discussion of this is deferred.
■ There is no semicolon after the right brace
that ends a block.

11/14/2022 10
If-Else
■ The if-else statement is used to express decisions.
■ Formally the syntax is,
❑ if (expression)
statement1
else
statement2
▪ The else part is optional
▪ The expression is evaluated; If it is true (non-zero) then
statement1 is executed, otherwise (if there is an else part)
statement2 is executed.
11/14/2022 11
If-Else
■ if (x != 0) is same as if (x)

■Check ■Check
int y = 5, k = 10; int y = 5, k = 10;
if (y == 5) if (y == 5)
{ k ++; k ++;
j = k * k; j = k * k;
}
else else
j = k; j = k;
11/14/2022 12
If-Else
■ Check ■ Syntax : if
❑ x = 0; if (2 (expr) statement
!= 1+1) ; x=
5; ■ ; /* a null statement*/
printf(“%d”,x);
■So the output is 5

11/14/2022 13
If-Else
■ Check ■What is the output?
❑ int j = 200; A
if (j = 5) ■ because j=5 has value 5
printf(“A”); which is non-zero(true)
else
printf(“B”);
■This is a common pit-fall. Beware!
11/14/2022 14
If-Else
■ if( n > 0 )
■ if( n > 0 ) if
{ if ( a > b)
( a > b)
z = a;
z = a; else z = b;
else z= }
b;

■else associates with the closest previous


else-less if.
11/14/2022 15
If-Else ■ if( n > 0 )
{ if ( a > b)
■ if( n > 0 ) z = a;
if ( a > b) z= else z = b;
a; }
else z = b; else
else {
z = c; z = c;
}

11/14/2022 16
If-Else ladder
■ if (exp1)
stmt1{
}
else { if (exp2) ■These are useful for
stmt2 multi-way decisions
else if (exp3)
stmt3
else
}
stmt4
11/14/2022 17
If-Else Ladder ■Only one statement in the
ladder is executed
■ if (exp1) ■Ifexp1 is true then stmt1
stmt1 is executed and all other
else if (exp2) in the ladder are ignored.
stmt2 ■Ifexp1 is false and exp2
else if (exp3) is true then only stmt2 is
stmt3 executed
else ■Stmt4 can be seen as a
stmt4 default
11/14/2022 18
Switch
■ The switch statement is a multi-way
decision that tests whether an expression
matches one of a number of constant integer
values, and branches accordingly.
■ switch (expression) { case
const-expr : statements case
const-expr : statements default :
statements }
11/14/2022 19
Switch
int j; $./a.out
scanf (“%d”, &j); 0
switch(j) {
zero
case 0: printf(“ zero\n”);
case 1: printf(“ one\n”); one
case 2: printf(“ two\n”); two
default: printf(“ other\n”); other
■ switch
} simply transfers control once
$ to the
matching case.
11/14/2022 20
breaking a switch
■ break; /*this is a statement which can
break a switch */
■ break exits the switch block.
■ break can be used with other control flow
structures, but discussion is deferred.

11/14/2022 21
Use break statements $./a.out
0
int j;
zero
scanf (“%d”, &j);
$./a.out
switch(j) {
1
case 0: printf(“ zero\n”);
one
break;
case 1: printf(“ one\n”); $./a.out
break; 2
case 2: printf(“ two\n”); two
default: printf(“ other\n”); other
}
11/14/2022 $ 22
Switch
■ default: statements /*optional*/
■ The control is transferred to default, if it exists and none of
the cases matches the expression value.
■ Even if there are multiple statements to be executed in
each case there is no need to use { and } (i.e., no need
for a compound statement as in if-else).
■ One can not have something like case j <= 20:
■ All that we can have after the case is a constant
expression.

11/14/2022 23
switch
■ You can also use char values.
■ char c ; c = getchar ( );
switch (c)
{
case ‘a’:
case ‘A’: printf(“apple”); break;
case ‘b’:
case ‘B’: printf(“banana”); break;
}

■Empty cases might be useful


11/14/2022 24
goto
■ goto label; /* label is similar
identifier like a variable name
*/
/* this transfers control
to */
label:

11/14/2022 25
Arrays

11/18/2022 1
Arrays

■ A sequence of elements of same type which share a


single name.
■ Two categories of arrays are there
❑ 1. Static arrays
❑ 2. Dynamic arrays.
■ Declaration for static array specifies the array size,
which cannot be altered afterwards.
■ But for dynamic arrays the size can be altered.
❑ There is something called as dynamic memory using
which dynamic array’s size can be modified.
❑ This can be discussed only after pointers.

11/18/2022 2
Initializing arrays (for static arrays)

■ int n[4] = { 10, 20, 30, 40};


❑ n[0] = 10, n[1] = 20, n[2] = 30, n[3] = 40
■ int n[4] = { 10, 20};
❑ n[0] = 10, n[1] = 20, n[2] = 0, n[3] = 0
■ If initialization is done (which implicitly
specifies the size) then one can omit size.
■ int a[ ] = { 0, 1, 2};
❑ a is of size 3 elements and a[0] = 0, a[1] = 1,
a[2] = 2

11/18/2022 3
Initializing character arrays

■ char str[ ] = “cat”;


■ This is equivalent to
char str[ ] = {‘c’, ‘a’, ‘t’, ‘\0’};

which is in turn equivalent to


char str[4] = {‘c’, ‘a’, ‘t’, ‘\0’};

11/18/2022 4
arrays

■ int n[10] = {0};


■ First element of n[ ] is explicitly initialized to 0, and
the remaining elements by default are initialized to 0.
■ int n[10];
■ In this all 10 elements contains junk values.
■ Forgetting to initialize the elements of an array
whose elements should be initialized is a common
mistake.
■ int a[3] = {1,2,3,4,5}; /* syntax error */

11/18/2022 5
arrays Let the number of
students are increased to
#include<stdio.h> 66
main( )
{
int marks[54]; This should be modified
from 54 to 66
/* to find average */
for( j = 0; j < 54; j++ ){
……;
} This also should be modified.

……;
Like this if at many places 54 is hard coded, then they all
}
should be modified to avoid errors. This is a potential problem.

11/18/2022 6
One dimensional arrays: addresses
This is the important number which is collected
from the declaration
■ int a[4];
■ When you say a[3], the location accessed is at address
(a + 3*sizeof(int) )
■ Let a = 100 and sizeof(int) = 2 then the addresses of
consecutive cells are as:
0 1 2 3 4
100 102 104 106 108

11/18/2022 7
Symbolic constants
#include<stdio.h>
#define is a preprocessing directive
#define SIZE 54
main( )
{
int marks[SIZE]; It is used to define
/* to find average */
symbolic constants
for( j = 0; j < SIZE; j++ ){
……;
}

……; #include is also a preprocessing


directive which is used to include
}
contents of a file.

11/18/2022 8
Preprocessing
#include<stdio.h> /* contents of stdio.h are kept
here */
#define SIZE 54
main( )
main( )
{
{
int marks[54];
int marks[SIZE];

/* to find average */
/* to find average */
for( j = 0; j < 54; j++ ){
for( j = 0; j < SIZE; j++ ){ Preprocessor
……;
……;
}
}

……;
……;
}
}

❖Simply SIZE is replaced by 54 in the source file.


❖Preprocessing is done first and then compilation is done.
11/18/2022 9
Preprocessing

■ Remember that it is an error to end #include or


#define with a semicolon. These are not C
statements.
■ A symbolic constant like SIZE is not a variable.
■ Advise: Use only UPPERCASE LETTERS for
symbolic constants. This distinguishes them from
other identifiers.
■ There are many more preprocessing directives
which are often called as macros, but discussion of
these are as usual postponed.

11/18/2022 10
Passing arrays to functions

■ int count[5];
■ count is the name of the array and value of count
is a constant which is the starting address of the
array.
■ When we say count[3] = 33;
what happens is 33 is stored in the memory
location whose address is :
(count + 3* sizeof (int))
■ So, when we pass count to a function, then we
are actually passing an address.
■ So, the function which uses this address can in
fact modify the original array !

11/18/2022 11
Passing arrays to functions

■ Function prototype which takes an array as


argument:
❑ return-type function( array-type array-name[ ] );
❑ Optionally array-name can be omitted.
❑ Eg: float find_average(float marks[ ]);
❑ Or, float find_average(float [ ]);
■ Function definition
❑ float find_average(float marks[ ])
{
…….;
}

11/18/2022 12
Functions with arrays

void f_1(int [ ]);


main( )
{
int a[10]; This is function call
… …;
f_1(a);
printf(“%d ”, a[4]);
… …;
}
void f_1(int b[ ])
{
b[4] = 20;/* in fact a[4] in main is assigned with 20 */
.. …;
}
11/18/2022 13
See the difference
void swap(int [ ]);
void swap(int, int);
main( )
main( )
{
{ int a[2] = {10, 20};
int a[2] = {10, 20}; swap(a);
swap(a[0], a[1]); printf(“%d %d”, a[0], a[1]);
printf(“%d %d”, a[0], a[1]); }
} void swap(int b[ ])
void swap(int b0, int b1) {
{ int t;
int t; t = b[0], b[0] = b[1],
t = b0, b0 = b1, b1 = t; b[1] = t;
return; return;
} }

11/18/2022 14
Multi-dimensional arrays

■ Until now what we saw are one dimensional


arrays.
❑ An element is indexed with a single subscript.
❑ A list of elements can be stored.
■ To store a table of elements (for example, a
matrix) we require a two dimensional array.

11/18/2022 15
2 dimensional array
Number of rows

■ Declaration
❑ int mat[2][4];

Number of columns

mat[0][0] mat[0][1] mat[0][2] mat[0][3]

mat[1][0] mat[1][1] mat[1][2] mat[1][3]

11/18/2022 16
2 dimensional arrays: initialization

■ int mat[2][4] = { {1,2,3,4} , {5,6,7,8} };


■ mat[0][0] = 1, mat[0][1] = 2, …, mat[1][3] = 8

■ int a[2][2] = { {1}, {3,4} };


■ a[0][0] = 1, a[0][1] = 0, a[1][0] = 3, a[1][1] = 4

■ int b[2][2] = { 1,3,4};


■ b[0][0] = 1, b[0][1] = 3, b[1][0] = 4, b[1][1] = 0

11/18/2022 17
2 dimensional arrays: initialization

■ In one dimensional arrays we said that


int a[ ] = {1,2,3}; /* same as int a[3] = {1,2,3}; */
■ Can we do for 2 dim arrays also like that
int b[ ][ ] = {1,2,3,4,5,6};
■ b could be of 2 rows and 3 columns, or of 3 rows and 2
columns.
■ To avoid this ambiguity, the column size (second
subscript) must be specified explicitly in the declaration.
■ int b[ ][2] = {1,2,3,4,5,6}; /*this is OK*/
■ b has two columns and three rows

11/18/2022 18
2 dimensional arrays: initialization

■ Check the following declaration


■ int a[ ][2] = {1,2,3};

■ a has 2 rows and 2 columns.


■ a[1][1] = 0

■ But declaring, int a[2][ ] = {1,2,3};


will not work !

11/18/2022 19
2 dimensional arrays: addresses
This is the important number which is collected
from the declaration
■ int a[4][5];
■ When you say a[2][3], the location accessed is at
address (a + 2*(5*sizeof(int)) + 3*sizeof(int) )
■ Let a = 100 and sizeof(int) = 2 then the addresses of
consecutive cells are as:
0 1 2 3 4
0 100 102 104 106 108
1 110 112 114 116 118
2 120 122 124 126 128
3 130 132 134 136 138

11/18/2022 20
2 dimensional arrays: addresses
This is the important number which is collected
from the declaration
■ int a[4][5];
■ When you say a[2][3], the location accessed is at
address (a + 2*(5*sizeof(int)) + 3*sizeof(int) )
■ Let a = 100 and sizeof(int) = 2 then the addresses of
consecutive cells are as:
0 1 2 3 4
0 100 102 104 106 108
1 110 112 114 116 118
2 120 122 124 126 128
3 130 132 134 136 138

11/18/2022 21
2 dimensional arrays: addresses

■ int a[4][5];

■ a is the starting address of the 2 dim. array


■ a[k] is the starting address of the k th row

a = 100 100 102 104 106 108


a[0] = 100 110 112 114 116 118
a[1] = 110 120 122 124 126 128
a[2] = 120 130 132 134 136 138
a[3] = 130
11/18/2022 22
2 dimensional arrays: functions

■ Function prototype
double f_1(char [ ][4]);
■ Number of columns in the argument array must be
specified. Otherwise address calculations are not
possible.
■ Function definition
double f_1(char names[ ][4])
{
… …;
}

11/18/2022 23
2 dimensional arrays: functions

■ Function call
double f_1(char [ ][4]); double f_1(char names[ ][4])
main( ) {
{
… …;
char str[10][4];
… …; }
v = f_1(str);
}

11/18/2022 24
2 dim arrays: Example: Read 10
words from keyboard
■ void read_names(char [ ][16]); /*func protorype*/
main( )
{
char name[40][16];
read_names(name);
}
void read_names(char str[ ][16])
{
for( j =0; j<40; j++)
scanf(“%s”, str[ j] );
}

11/18/2022 25
Multi-dimensional arrays

■ This is simply generalization of 2


dimensional arrays.
■ For example
❑ int a[2][4][9];
❑ int b[ ][3][2] = {1,2,3,4,5,6,7};

This can be left blank if initialization


is given

❑ Similar rules for functions as for 2 dim. arrays

11/18/2022 26
Recap: Arrays
▪ A collection of elements all of which have the same data type
float marks[500];

marks[0] marks[1] marks[2] marks[499]

▪ Each array element is accessed using the array index (integer-valued)


▪ For the above example, marks[0], marks[2], marks[499], marks[int_expr] where
int_expr is integer-valued expression such that 0 <= int_expr <= 499
1
Recap: Array: Declaration and Initialization
Can be initialized at time of declaration itself
int a[6] = {3,7,6,2,1,0}; a 3 7 6 2 1 0
Can be partly initialized as well
int a[6] = {3,7,6}; a 3 7 6
Over initialization may crash I will figure out how
int a[6] = {1,2,3,4,5,6,7,8,9};
No need to specify much space needed
the array size during
Better way to initialize is the following
declaration

int a[] = {1,2,3,4,5,6,7,8,9};


Warning: uninitialized arrays contain garbage, not zeros
2
Array: Declaration and Initialization
▪ Can declare the array first and initialize its elements later
▪ The later initialization can be done using user-provided values (e.g.,
using scanf), or some expression, or using some fixed values
Can I run the
int i,tmp,a[5]; loop as
Read a for(i=1;i<=5;i++)?
use-provided
for(i=0;i<5;i++){
value scanf(“%d”,&tmp);
Assign the read
value to the ith a[i] = tmp; Yes, if you use
element of the a[i-1] = tmp; in
array } loop’s body 3
Array: Declaration and Initialization
▪ Can declare the array first and initialize its elements later
▪ The later initialization can be done using user-provided values (e.g.,
using scanf), or some expression, or using some fixed value
Note: &a[i] is evaluated
as &(a[i]) since [] has
int i,a[5]; higher precedence than &

Directly read a user


for(i=0;i<5;i++){ provided value into the
ith element of the array
A shortcut for scanf(“%d”,&a[i]); (the tmp variable is not
needed)
reading user
provided
}
values 4
Operator Name Symbol/Sign Associativity
Brackets, array subscript, Post (), [] ++, -- Left
increment/decrement
Unary negation, Pre -, ++, --, ! Right
increment/decrement, NOT
Multiplication/division/ *, /, % Left
remainder
Addition/subtraction +, - Left
Relational <, <=, >, >= Left
Relational ==, != Left
AND && Left
OR || Left
Conditional ?: Right
Assignment, Compound =, +=, -=, *=, /=, Right
assignment %= 5
Array: Declaration and Initialization
▪ Can declare the array first and initialize its elements later
▪ The later initialization can be done using user-provided values (e.g.,
using scanf), or some expression, or using some fixed value
1 2 3 4 5
int i,a[5]; a[0] a[1] a[2] a[3] a[4]
for(i=0;i<5;i++){
a[i] = i+1; Assign a value of
expression i+1 to
} the ith element of
the array
6
Array: Declaration and Initialization
▪ Can declare the array first and initialize its elements later
▪ The later initialization can be done using user-provided values (e.g.,
using scanf), or some expression, or using some fixed value
10 10 10 10 10
int i,a[5]; a[0] a[1] a[2] a[3] a[4]

for(i=0;i<5;i++){ Assign a fixed


(constant) value 10
a[i] = 10; to the ith element of
the array
}
7
Tracing the execution of an array based program
include <stdio.h> Let us trace the
int main () { execution of the program.
int a[5];
int i;

for (i=0; i < 5; i= i+1) {


a[i] = i+1; i
} 5
2
0
1
3
4
return 0;
}
a[0] a[1] a[2] a[3] a[4]

1 2 3 4 5

Statement becomes a[0] =0+1;


Statement becomes a[1] =1+1; Statement becomes a[3] = 3+1;
Statement becomes a[2] =2+1; Statement becomes a[4] = 4+1; 8
Arrays: Some Example Programs
▪ Create an integer array of size 100
▪ Initialize elements with even index as 0
▪ Initialize elements with odd index as 1

int i,a[100];
for(i=0; i<100; i=i+1){
Method 1
if(i%2==0) a[i] = 0;
else a[i] = 1;
} 9
Arrays: Some Example Programs
▪ Create an integer array of size 100
▪ Initialize elements with even index as 0
Incrementing the
▪ Initialize elements with odd index as 1 loop counter by 2

int i,a[100];
Method 2,
for(i=0; i<100; i=i+2){
This for loop will run
without if-else a[i] = 0; 50 times. Each
iteration will assign
a[i+1] = 1; values to 2 elements,
one at odd index, one
} at even index
10
Greek origin word:
palin = again,
Arrays: Some Example Programs dromos = direction

▪ Check whether a sequence of numbers is a palindrome sequence


Let’s specify a maximum flag = 1 assumes that sequence is
int main(){ sequence size palindrome (set 0 if later found otherwise)
Palindrome: Forward and int a[100], temp, len = 0, i, flag = 1;
The while(1) loop keeps reading numbers
Reverse gives the same until user enters -1, store each number as an
while(1){
sequence scanf("%d", &temp);
element of the array named a
if(temp == -1) This line does a[len] = temp;
break; and then increments len
Some palindromes:
a[len++] = temp;
123454321 } After the while(1) loop exits, len is the
123321 size of the array (indices are 0 to len-1)
for(i = 0; i < len; i++)
if(a[i] != a[len-i-1]) Compares a[0] with a[len-1], then a[1]
Some non-palindromes: flag = 0; with a[len-2], and so on. If any pair does
12345 if(flag) printf("YES"); not match, set flag variable to 0

123341 else printf("NO");


90408 return 0;
} a[0] a[1] a[2] a[len-2] a[len-1] 11
Arrays: Some Example Programs
#include <stdio.h>
Read until user has
int main() {
entered 100 chars or char s[100];
the end-of-file (EOF) /* the array of 100 char */
int count = 0; /* counts number of input chars read */
special character int ch; /* current character read */
has been read. int i; /* index for printing array backwards */
ch = getchar();
Now print the characters while ( ch != EOF && count < 100) {
in reverse order s[count] = ch;
count = count + 1; /*read_into_array */
ch = getchar();
}
getchar() returns a
single character i = count-1;
entered by the user while (i >=0) {
putchar(s[i]); /*print_in_reverse */
i=i-1;
}
return 0; putchar() prints a single character
}
12

You might also like