PDS 3
PDS 3
1
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Branching / Conditionals: What do they do?
• Allow different sets of instructions to be executed depending on the outcome of a logical
condition / test
2
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
How do we specify the condition?
Using logical operators / connectives. ( (sex == ’M’) && (age >= 21) )
( (marks >== 80) && (marks < 90) )
• Two logical connectives: &&, | |
• Unary negation operator: ! ( (balance > 5000) | | (no_of_trans > 25) )
( !(grade == ’A’) )
3
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Branching: The if Statement
if (expression)
statement; Note: indentation (after opening a brace,
leave some horizontal space in the following
lines, till you close that brace)
if (expression) {
Block of statements
}
The condition to be tested is any expression enclosed in parentheses. The expression is evaluated,
and if its value is non-zero, the statement is executed.
4
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
A decision can be made on
any expression.
zero :- false
print “Passed” nonzero :- true
true
print “Good luck”
marks >= 40
false if (marks>=40) {
printf(“Passed \n”);
printf(“Good luck\n”);
}
printf (“End\n”) ;
5
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Branching: if-else Statement
if (expression) {
Note: indentation (after opening a brace,
Block of statements;
leave some horizontal space in the following
} lines, till you close that brace)
else {
Block of statements;
}
6
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Branching: if-else Statement
if (expression) {
if (expression) { Block of statements;
Block of statements;
}
}
else if (expression) {
else {
Block of statements;
Block of statements;
} }
else {
Block of statements;
7
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Grade Computation
if (marks >= 80) printf (“A”) ;
else if (marks >= 70) printf (“B”) ;
else if (marks >= 60) printf (“C”) ;
else printf (“Failed”) ;
START
printf (“\nEnd\n”) ;
READ MARKS
8
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Grade Computation int main ()
{
int marks;
scanf(“%d”, &marks);
if (marks >= 80) {
printf(“A: ”);
printf(“Good Job!”);
}
else if (marks >= 70)
START printf(“B ”);
else if (marks >= 60)
printf(“C ”);
READ else {
MARKS printf(“Failed: ”);
printf(“Study Hard!”);
MARKS NO MARKS NO MARKS NO }
≥ 80? ≥ 70? ≥ 60? return 0;
}
YES YES YES
OUTPUT OUTPUT OUTPUT
OUTPUT
“A” “B” “C”
“F”
9
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Largest of three numbers
START
YES IS NO
X > Y?
Max = X Max = Y
YES IS NO
Max > Z?
OUTPUT Max OUTPUT Z
STOP STOP
10
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
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
11
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Another version
There are many different ways to
write the same program correctly
int main() {
int a,b,c;
scanf (“%d%d%d”, &a, &b, &c);
return 0;
}
12
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
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" );
if ( payCode = 4 )
printf( "You get a bonus!\n" ); X
13
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Dangling else problem
if (exp1) { if (exp1) {
if (exp2) OR if (exp2) ?
stmta stmta
else }
stmtb else
stmtb X
} An “else” clause is associated
with the closest preceding
unmatched “if”.
14
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example – wrong program
Print “ABC” if a number is between 0 and 100, or “XYZ”
if it is –ve. Do not print anything in other cases.
int main()
{
Outputs for different inputs
int x;
scanf(“%d”, &x); 150
XYZ
if (x >= 0)
if (x <= 100) Not what we want, should not have
printed anything
printf(“ABC\n”);
else -20
printf(“XYZ\n”);
return 0; Not what we want, should have
printed XYZ
}
15
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example - Correct Program
int main()
{
Outputs for different inputs
int x;
scanf(“%d”, &x); 150
if (x >= 0) {
if (x <= 100)
printf(“ABC\n”);
-20
} XYZ
else
printf(“XYZ\n”);
return 0;
}
16
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
More examples
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
if e1 if e2 s1 if e1 { if e2 s1
While programming, it is always good to
else s2 explicitly give the { and } to avoid any mistakes else s2 }
17
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
The Conditional Operator ? :
This makes use of an expression that is either true or false. An appropriate value is selected,
depending on the outcome of the logical expression.
Example:
interest = (balance>5000) ? balance*0.2 : balance*0.1;
Returns a value
Equivalent to: if (balance > 5000) interest = balance * 0.2; else interest = balance * 0.1;
Equivalent also to: interest = balance * ((balance > 5000) ? 0.2 : 0.1);
18
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
More Examples
19
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
The switch statement
This causes a particular group of statements to be chosen from several available groups.
• Uses “switch” statement and “case” labels.
switch (expression) {
• expression is any integer-valued expression
case const-expr-1: S-1
case const-expr-2: S-2 • const-expr-1, const-expr-2,…are any constant integer-valued
expressions
:
• Values must be distinct
case const-expr-m: S-m
default: S • 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), but put it at the end only (as shown)
20
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Behavior of switch
switch (expression) {
case const-expr-1: S-1
case const-expr-2: S-2
:
case const-expr-m: S-m
default: S
}
21
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Examples
switch ( letter ) {
case 'A':
printf ("First letter \n");
break;
case 'Z':
printf ("Last letter \n");
Will print this statement
break;
for all letters other than
default : A or Z
printf ("Middle letter \n");
break;
}
22
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Examples
23
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Another way
24
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Rounding a Digit
switch (digit) {
case 0:
case 1:
case 2:
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;
}
25
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example: checking if a character is a lower-case letter
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 lower-case letter\n”, c1);
else
printf (“%c is not a lower-case letter\n”, c1);
return 0;
}
26
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example: converting a character from lowercase to uppercase
int main()
{
char c1;
scanf(“%c”, &c1);
/* convert to upper case if lower-case, else leave as it is */
if (c1 >= ‘a’ && c1<= ‘z’)
/* since ascii codes of upper-case letters are contiguous,
the upper-case 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;
}
27
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Evaluating expressions case ‘-’ :
result = operand1 - operand2;
28
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
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.
29
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR