BITS Pilani
K K Birla Goa Campus
CSF111
Computer Programming
Control Flow
(Supplementary)
Conditional: Variants of If else
• If statement
• If else statement
• Nested If else statements
• If - else if - else statements
2
Dangling else problem
An “else” clause is associated with the closest
preceding unmatched “if”.
Print “ABC” if a number is between 0 and 100, or “XYZ”
if it is –ve. Do not print anything in other cases.
3
Dangling else problem
Print “ABC” if a number is between 0 and 100, or “XYZ”
if it is –ve. Do not print anything in other cases.
Wrong Program
4
Dangling else problem
Print “ABC” if a number is between 0 and 100, or “XYZ”
if it is –ve. Do not print anything in other cases.
Correct Program
5
Conditional (Ternary) 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
6
Conditional (Ternary) Operator ? :
Example
if ((a > 10) && (b < 5))
x = a + b;
else
x = 0;
x = ((a > 10) && (b < 5)) ? a + b : 0
if (marks >= 60) printf(“Passed \n”); else printf(“Failed \n”);
(marks >= 60) ? printf(“Passed \n”) : printf(“Failed \n”);
7
Switch Statement
This causes a particular group of statements to be chosen from several
available groups.
• Uses “switch” statement and “case” labels.
switch (expression) {
case const-expr-1: S-1
case const-expr-2: S-2
:
case const-expr-m: S-m
default: S
}
8
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-
case const-expr-m: S-m valued expressions
default: S • Values must be distinct
} • S-1, S-2, …,S-m, S are statements /
compound statements
• Default is optional, and can
come anywhere (not necessarily
9
at the end as shown)
Switch Statement switch (expression) {
case const-expr-1: S-1
case const-expr-2: S-2
:
case const-expr-m: S-m
default: S
}
• 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 10
Switch Statement
Example
switch ( letter ) {
case 'A':
printf ("First letter \n");
break;
Will print this statement
case 'Z':
for all letters other than
printf ("Last letter \n"); A or Z
break;
default :
printf ("Middle letter \n");
break;
}
11
Switch Statement
Example
12
Switch Statement
Example
Previous Example (another way)
13
Practice Problem
Checking if a character is a lower-case letter
14
Practice Problem
Checking if a character is a lower-case letter
15