Professional Documents
Culture Documents
and
Programming
MODULE 6
SELECTION STRUCTURES
• Identify the selection structures in C.
• Discuss if, if-else, if-else-if statements.
• Use if, if-else, if-else-if statements in decision
making.
• Discuss the nested if statements.
• Discuss switch statement.
• Explain the syntax of switch statement.
• Differentiate switch and if-else statement.
• Discuss the use of default and break keywords in
switch statement.
MODULE 6 – SUBTOPIC 1
CONDITIONAL STATEMENTS
PART 1
• Selection structures are used to perform ‘decision making‘
and then branch the program flow based on the outcome of
decision making.
Key-in 2 numbers: 20
_ 15
_Smallest: 15
_
Example:
int grd;
92 > 80?
printf(“Grade: “); grd ?
92
scanf(“%d”, &grd);
if (grd > 80) {
printf(“Category: Excellent\n”);
printf(“Congratulations!”);
}
Grade:92
Mark: _92
_
Category: Excellent
Congratulations!
Example: What will the output be if the mark is
void main() { 65?
int mark;
printf(“Mark: “);
scanf(“%d”, &mark);
if (mark >= 50)
printf(“Pass\n”);
printf(“Your mark is %d”, mark);
}
Example: What will the output be if the mark is
void main() { 35?
int mark;
printf(“Mark: “);
scanf(“%d”, &mark);
if (mark >= 50)
printf(“Pass\n”);
printf(“Your mark is %d”, mark);
}
The structure is similar to double selection (flowchart)
Syntax:
if (expression)
statement;
else
statement;
or
if (expression) {
statement1;
statement2;
} else
statement3;
or
if (expression) {
statement1;
statement2;
} else {
statement3;
statement4;
}
The similarity between double selection structure
and if - else statement:
Double Selection: if Statement:
if <condition is true> start if <condition> {
step 1 statement 1
… …
step k statement k
end_if }
else start else {
step 1 statement 1
… …
step n statement n
end_else }
Example:
if (num1 < num2)
10 < 15?
num1 10
min = num1;
else num2 15
min = num2;
min 10
?
printf(“Smallest: %d\n”, min);
_Smallest: 10
_
Example:
if (num1 < num2)
20 < 15?
num1 20
min = num1;
else num2 15
min = num2;
min 15
?
printf(“Smallest: %d\n”, min);
_Smallest: 15
_
Example: num1 700
if (num1 < num2) { 700 < 125?
min = num1; num2 125
max = num2;
}
else { min 125
??
min = num2;
max = num1; max 700
??
}
printf(“Min = %d, Max = %d\n”, min, max);