Conditional Statements
Conditional Statements
1
Statements in a C program
Parts of C program that tell the computer what to do
Different types
Declaration statements
Declares variables etc.
Assignment statement
Assignment expression, followed by a ;
Control statements
For branching and looping, like if-else, for, while, do-
while (to be seen later)
Input/Output
Read/print, like printf/scanf
2
Example
Declaration statement
int a, b, larger;
scanf(“%d %d”, &a, &b);
larger = b;
Control Assignment
if (a > b) statement statement
larger = a; Input/Output
statement
printf(“Larger number is %d\n”, larger);
3
Compound statements
A sequence of statements enclosed within { and }
We will also call it block of statements informally
Each statement in a block can be an assignment
statement, control statement, input/output statement,
or another compound statement
There may be only one statement inside a block also
4
Example
int n;
scanf(“%d”, &n);
while(1) {
if (n > 0) break;
Compound statement
scanf(“%d”, &n);
}
5
Conditional Statements
Allow different sets of instructions to be executed
depending on truth or falsity of a logical condition
Also called Branching
How do we specify conditions?
Using expressions
non-zero value means condition is true
value 0 means condition is false
Usually logical expressions, but can be any
expression
The value of the expression will be used
6
Branching: if Statement
if (expression)
statement;
if (expression) {
Block of statements;
}
7
Branching: if Statement
if (expression)
statement;
if (expression) {
Block of statements;
}
false
9
A decision can be
made on any
print “Passed” expression.
true print “Good luck”
marks >= 40 zero - false
nonzero - true
false
10
A decision can be
made on any
print “Passed” expression.
true print “Good luck”
marks >= 40 zero - false
nonzero - true
false
11
Branching: if-else Statement
if (expression) { if (expression) {
Block of Block of statements;
statements; }
} else if (expression) {
else { Block of statements;
Block of }
statements; else {
} Block of statements;
}
12
Grade Computation
int main() {
int marks;
scanf(“%d”, &marks);
if (marks >= 80)
printf (”A”) ;
else if (marks >= 70)
printf (”B”) ;
else if (marks >= 60)
printf (”C”) ;
else printf (”Failed”);
return 0;
} 13
Outputs for different inputs
int main () { 90
int marks; A: Good Job!
scanf (“%d”, &marks) ;
if (marks>= 80) { 65
C
printf (“A: ”) ;
printf (“Good Job!”) ;
50
} Failed: Study hard!
else if (marks >= 70) printf (“B ”) ;
else if (marks >= 60) printf (“C ”) ;
else {
printf (“Failed: ”) ;
printf (“Study hard!”) ;
}
return 0;
} 14
Find the larger of two numbers
START
READ X, Y
YES IS NO
X>Y?
OUTPUT X OUTPUT Y
STOP STOP
15
Find the larger of two numbers
START int main () {
int x, y;
scanf (“%d%d”, &x, &y);
READ X, Y
if (x > y)
printf (“%d\n”, x);
YES IS NO else
X>Y?
printf (“%d\n”, y);
return 0;
OUTPUT X OUTPUT Y }
STOP STOP
16
Largest of three numbers
START
READ X, Y, Z
YES IS NO
X > Y?
Max = X Max = Y
YES IS NO
Max > Z?
OUTPUT Max OUTPUT Z
STOP STOP
17
START
READ X, Y, Z
YES IS NO
X > Y?
Max = X Max = Y
YES IS NO
Max > Z?
OUTPUT Max OUTPUT Z
STOP STOP
18
int main () {
START
int x, y, z, max;
scanf (“%d%d%d”,&x,&y,&z);
READ X, Y, Z
if (x > y)
YES IS NO
max = x;
X > Y? else max = y;
Max = X Max = Y if (max > z)
printf (“%d”, max) ;
YES IS NO else printf (“%d”,z);
Max > Z? return 0;
OUTPUT Max OUTPUT Z
}
STOP STOP
19
Another version
int main() {
int a,b,c;
scanf (“%d%d%d”, &a, &b, &c);
if ((a >= b) && (a >= c))
printf (“\n The largest number is: %d”, a);
if ((b >= a) && (b >= c))
printf (“\n The largest number is: %d”, b);
if ((c >= a) && (c >= b))
printf (“\n The largest number is: %d”, c);
return 0;
}
20
Confusing Equality (==) and
Assignment (=) Operators
Dangerous error
Does not ordinarily cause syntax errors
Any expression that produces a value can be used in
control structures
Nonzero values are true, zero values are false
Example:
if ( payCode = 4 )
printf( "You get a bonus!\n" );
WRONG! Will always print the line
21
Nesting of if-else Structures
It is possible to nest if-else statements, one within
another
All “if” statements may not be having the “else” part
Confusion??
Rule to be remembered
An “else” clause is associated with the closest
preceding unmatched “if”
22
Dangling else problem
if (exp1) if (exp2) stmta else stmtb
if (exp1) { if (exp1) {
if (exp2) if (exp2)
else
stmta OR
}
stmta ?
stmtb else
} stmtb
if e1 s1
else if e2 s2
else s3
?
if e1 if e2 s1
else s2
else s3
24
Answers
if e1 s1 if e1 s1
else if e2 s2 else { if e2 s2 }
if e1 s1 if e1 s1
else if e2 s2 else { if e2 s2
else s3 else s3 }
if e1 if e2 s1 if e1 { if e2 s1
else s2 else s2 }
else s3 else s3
29
More Examples
if (((a >10) && (b < 5))
x = a + b;
else x = 0;
30
The switch Statement
31
Syntax
switch (expression) {
case const-expr-1: S-1
case const-expr-2: S-2
:
case const-expr-m: S-m
default: S
}
expression is any integer-valued expression
const-expr-1, const-expr-2,…are any constant integer-
valued expressions
Values must be distinct
S-1, S-2, …,S-m, S are statements/compound
statements
Default is optional, and can come anywhere (not
necessarily at the end as shown) 32
Behavior of switch
expression is first evaluated
It is then compared with const-expr-1, const-expr-
2,…for equality in order
If it matches any one, all statements from that point till
the end of the switch are executed (including
statements for default, if present)
Use break statements if you do not want this (see
example)
Statements corresponding to default, if present, are
executed if no other expression matches
33
int main() Example
{
int x;
scanf(“%d”, &x);
switch (x) {
case 1: printf(“One\n”);
case 2: printf(“Two\n”);
default: printf(“Not one or two\n”);
};
}
If x = 1 is entered, this will print
One
Two
Not one or two
switch-1.c
Not what we want 34
Correct Program
int main()
{
int x;
scanf(“%d”, &x);
switch (x) {
case 1: printf(“One\n”);
break;
case 2: printf(“Two\n”);
break;
default: printf(“Not one or two\n”);
};
} If x = 1 is entered, this will print
One
switch-2.c 35
Rounding a Digit
Since there isn’t a break statement
switch (digit) { here, the control passes to the next
statement without checking
case 0: the next condition.
case 1:
case 2: It will come here if digit is any of 0 to 4.
Round to 0, then break as done.
case 3:
case 4: result = 0; printf (“Round down\n”); break;
case 5:
case 6:
case 7:
case 8:
case 9: result = 10; printf(“Round up\n”); break;
36
}
The break Statement
37
More on Data Types
38
More Data Types in C
Some of the basic data types can be augmented by
using certain data type qualifiers:
short
size qualifier
long
signed
unsigned sign qualifier
Typical examples:
short int (usually 2 bytes)
long int (usually 4 bytes)
unsigned int (usually 4 bytes, but no way to store + or
-)
39
Some typical sizes (some of these can vary
depending on type of machine)
Integer data
#Bits Minimum value Maximum value
type
char 8 -27 = -128 27-1 = 127
short int 16 -215 = -32768 215-1 = 32767
int 32 -231 = -2147483648 231-1 = 2147483647
long int 32 -231 = -2147483648 231-1 = 2147483647
-263= - 263-1 =
long long int 64
9223372036854775808 9223372036854775807
unsigned char 8 0 28-1 = 255
unsigned short int 16 0 216-1 = 65535
unsigned int 32 0 232-1 = 4294967295
unsigned long int 32 0 232-1 = 4294967295
264-1 =
unsigned long long int 64 0
18446744073709551615
40
More on the char type
Is actually stored as an integer internally
Each character has an integer code associated with it
(ASCII code value)
Internally, storing a character means storing its
integer code
All operators that are allowed on int are allowed on
char
32 + ‘a’ will evaluate to 32 + 97 (the integer ascii code
of the character ‘a’) = 129
Same for other operators
Can switch on chars constants in switch, as they are
integer constants 41
Another example
int a;
Will print 302 (99*3 + 5)
a = ‘c’ * 3 + 5;
(ASCII code of ‘c’ = 99
printf(“%d”, a);
33 21 00100001 ! 81 51 01010001 Q
35 23 00100011 # 83 53 01010011 S
36 24 00100100 $ 84 54 01010100 T
37 25 00100101 % 85 55 01010101 U
40 28 00101000 ( 88 58 01011000 X
41 29 00101001 ) 89 59 01011001 Y
42 2a 00101010 * 90 5a 01011010 Z
43 2b 00101011 + 91 5b 01011011 [
44 2c 00101100 , 92 5c 01011100 \
45 2d 00101101 - 93 5d 01011101 ]
46 2e 00101110 . 94 5e 01011110 ^
47 2f 00101111 / 95 5f 01011111 _
48 30 00110000 0 96 60 01100000 `
49 31 00110001 1 97 61 01100001 a
50 32 00110010 2 98 62 01100010 b
44
51 33 00110011 3 99 63 01100011 c
45
71 47 01000111 G 119 77 01110111 w
72 48 01001000 H 120 78 01111000 x
73 49 01001001 I 121 79 01111001 y
74 4a 01001010 J 122 7a 01111010 z
75 4b 01001011 K 123 7b 01111011 {
76 4c 01001100 L 124 7c 01111100 |
77 4d 01001101 M 125 7d 01111101 }
78 4e 01001110 N 126 7e 01111110 ~
79 4f 01001111 O 127 7f 01111111 DELETE
46
Example: checking if a character is a
lowercase alphabet
int main()
{
char c1;
scanf(“%c”, &c1);
/* the ascii code of c1 must lie between the
ascii codes of ‘a’ and ‘z’ */
if (c1 >= ‘a’ && c1<= ‘z’)
printf(“%c is a lowercase alphabet\n”, c1);
else printf(“%c is not a lowercase alphabet\n”, c1);
return 0;
}
47
Example: converting a character from
lowercase to uppercase
int main()
{
char c1;
scanf(“%c”, &c1);
/* convert to uppercase if lowercase, else leave as it is */
if (c1 >= ‘a’ && c1<= ‘z’)
/* since ascii codes of uppercase letters are contiguous, the
uppercase version of c1 will be as far away from the ascii code
of ‘A’ as it is from the ascii code of ‘a’ */
c1 = ‘A’ + (c1 – ‘a’);
printf((“The letter is %c\n”, c1);
return 0;
}
48
Switching with char type
char letter;
scanf(“%c”, &letter);
switch ( letter ) {
case 'A':
printf ("First letter \n");
break;
case 'Z':
printf ("Last letter \n");
break;
default :
printf ("Middle letter \n");
} 49
Switching with char type
char letter;
scanf(“%c”, &letter);
switch ( letter ) {
case 'A':
printf ("First letter \n");
break;
case 'Z':
printf ("Last letter \n");
break;
default : Will print this statement
printf ("Middle letter \n"); for all letters other than
A or Z
} 50
Another Example
switch (choice = getchar()) {
case ‘r’ :
case ‘R’: printf(“Red”);
break;
case ‘b’ :
case ‘B’ : printf(“Blue”);
break;
case ‘g’ :
case ‘G’: printf(“Green”);
break;
default: printf(“Black”);
}
51
Another Example
switch (choice = getchar()) {
case ‘r’ : Since there isn’t a break statement
here, the control passes to the next
case ‘R’: printf(“Red”); statement (printf) without checking
break; the next condition.
case ‘b’ :
case ‘B’ : printf(“Blue”);
break;
case ‘g’ :
case ‘G’: printf(“Green”);
break;
default: printf(“Black”);
}
52
Evaluating expressions case ‘-’ :
result=operand1-operand2;
int main () { break;
int operand1, operand2; case ‘*’ :
int result = 0; result=operand1*operand2;
break;
char operation ;
case ‘/’ :
/* Get the input values */
if (operand2 !=0)
printf (“Enter operand1 :”);
result=operand1/operand2;
scanf(“%d”,&operand1) ; else
printf (“Enter operation :”); printf(“Divide by 0 error”);
scanf (“\n%c”,&operation); break;
printf (“Enter operand 2 :”); default:
scanf (“%d”, &operand2); printf(“Invalid operation\n”);
switch (operation) { return;
case ‘+’ : }
result=operand1+operand2; printf (“The answer is %d\n”,result);
return 0;
break;
} 53
Practice Problems
1. Read in 3 integers and print a message if any one of them is equal to the sum of the
other two.
2. Read in the coordinates of two points and print the equation of the line joining them in
y = mx +c form.
3. Read in the coordinates of 3 points in 2-d plane and check if they are collinear. Print
a suitable message.
4. Read in the coordinates of a point, and the center and radius of a circle. Check and
print if the point is inside or outside the circle.
5. Read in the coefficients a, b, c of the quadratic equation ax2 + bx + c = 0, and print its
roots nicely (for imaginary roots, print in x + iy form)
6. Suppose the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 are mapped to the lowercase letters a, b,
c, d, e, f, g, h, i, j respectively. Read in a single digit integer as a character (using %c
in scanf) and print its corresponding lowercase letter. Do this both using switch and
without using switch (two programs). Do not use any ascii code value directly.
7. Suppose that you have to print the grades of a student, with >= 90 marks getting EX,
80-89 getting A, 70-79 getting B, 60-69 getting C, 50-59 getting D, 35-49 getting P
and <30 getting F. Read in the marks of a student and print his/her grade.
54