CSO101 Lecture Slides
CSO101 Lecture Slides
3/16/2023 1
How the courses are run?
3/16/2023 2
Objectives
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]
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)
■ Course Page
■ https://sites.google.com/site/patrabidyutkr/teachingiitbhu/odd2023-24-cso10
1
3/16/2023 5
Lab. Part
3/16/2023 6
Policies, Guidelines,…
3/16/2023 7
Introduction: Computer
3/16/2023 8
Hardware and Software
•Hardware: Keyboard, Mouse, Monitor, Printer, CPU,
Memory, etc.
3/16/2023 9
Computer (Conceptually)
3/16/2023 10
An Example
3/16/2023 11
A Model ( Human)
• Body 🡺 Hardware
• Thinking Process (Mind) 🡺 Software
3/16/2023 12
Early Computers
3/16/2023 13
Stored-Program Computers
3/16/2023 14
Von Neumann Architecture
3/16/2023 15
Are there other architectures?
3/16/2023 16
What you have to do?
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
3/16/2023 19
Homework
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 …
3/16/2023 22
Introduction …
10/31/2022 2
High Level Language (HLL)
10/31/2022 3
Translators
10/31/2022 4
Algorithm
10/31/2022 5
Algorithm: Five Characteristics
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
Input/Output A parallelogram
indicates input/output.
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
10/31/2022 2
History …
10/31/2022 3
C program
10/31/2022 4
C Standard Library
10/31/2022 5
A Simple C Program
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
Area = 24
Perimeter = 20
10/31/2022 8
Variables and Constants
10/31/2022 9
Names (Identifiers) …
10/31/2022 10
Names …
■ Invalid names :
❑ $total
❑ 1st
❑ no.
❑ case
■ Are the following valid?
❑ _total
❑ \new
❑ end
10/31/2022 11
Constants
10/31/2022 12
Data Types
10/31/2022 13
Basic data types
10/31/2022 14
Declarations
10/31/2022 15
Declarations …
10/31/2022 16
Declarations …
10/31/2022 17
Declarations …
10/31/2022 18
Declarations …
10/31/2022 19
Declarations …
10/31/2022 20
How to find the size?
10/31/2022 21
sizeof
■ int i,j;
j = sizeof i; /* but, j = sizeof int; is wrong */
10/31/2022 22
Declarations …
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
10/31/2022 26
Constants …
10/31/2022 27
Constants …
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)
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)
char variable
Format string
int variable
float num;
scanf(“%f ”, &num);
printf(“%f ”, num);
What is 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
2
Information in a computer -- Data
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..)
7
Arithmetic and logic unit (ALU)
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.
Memory Printer
Graphics display
Speakers
……
Output Unit
Processor
9
Control unit
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.
Bus
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
Make-Up Class I
Review
● Activity in Computer is governed by Instructions.
● Individual instructions are brought from memory into the processor, which executes
specified operations.
char unsigned
char
%c %u 4
int
• Can store integers between -2,147,483,648 and 2,147,483,647
▪ 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
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
} }
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)
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
Highest Number: ?
Least Positive Number: ?
Least Number: ?
Conceptual Example
Normalization and biasing
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.
Biased Exponent!
IEEE 754 Floating Point Representation
Single-precision (float)
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
* 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)
■^ 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
* 10
Precedence Table with Bitwise Operators
Operators Description Associativity
&& Logical AND Left to Right
* 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))
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
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
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
16
Logical Operators
Logical Op Function Allowed Types
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
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
LOW
7
Quiz
0 <= 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 */
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;
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;
}
11/14/2022 25
Arrays
11/18/2022 1
Arrays
11/18/2022 2
Initializing arrays (for static arrays)
11/18/2022 3
Initializing character arrays
11/18/2022 4
arrays
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++ ){
……;
}
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
……;
……;
}
}
……;
……;
}
}
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
11/18/2022 12
Functions with arrays
11/18/2022 14
Multi-dimensional arrays
11/18/2022 15
2 dimensional array
Number of rows
■ Declaration
❑ int mat[2][4];
Number of columns
11/18/2022 16
2 dimensional arrays: initialization
11/18/2022 17
2 dimensional arrays: initialization
11/18/2022 18
2 dimensional arrays: initialization
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];
■ 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
11/18/2022 26
Recap: Arrays
▪ A collection of elements all of which have the same data type
float marks[500];
1 2 3 4 5
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