CBCP2202 E-Tutorial 2 Selection Control Structure
CBCP2202 E-Tutorial 2 Selection Control Structure
Selection Control
Structure
E-TUTORIAL 2
Learning Outcomes
1. Write C syntax for if selection, if/else selection, multiple if/else selection
and nested if selection structures;
2. Compare between the if and switch statements based on the problem given;
and
3. Differentiate between the if and switch statements.
switch and break statements
The if-else statement is used to select one of the many choices depending on the
value of the expression tested.
The switch and break statements are used to select only one choice from many
choices that exist.
The statement is very useful when the choice is dependent on the value for one
variable or simple expression.
The value for the expression can only be of type int and char, but not of float
type.
Syntax for the switch and break:
switch (expression) {
case expression1:
statement1;
break;
case expression2:
statement2;
break;
...
case expression1:
statementm;
break;
default
statement n;
break;
}
Flow diagram for switch-case statement
Syntax explanation
The expression at the switch statement will be evaluated and matched to
expression1 until expression-m at the case.
If it matches, the case statement will be executed and will be followed by the break
statement.
The break statement will bring the program control out of the switch statement
without executing the next case statement. If the break statement is not given, then
the next statement will be executed, regardless the case value matches or not.
If the expression cannot be matched, and the default statement is available, then
statement-n will be executed. If the default statement does not exist, control will exit
the switch statement.
Code Example 1
// Display text for digits 1 to 3 case 2: printf(“Two”);
#include <stdio.h> break;
int main() case 3: printf(“Three”);
{ break;
int digit; default:
printf(“Input a digit: “); printf(“Not a digit”);
scanf(%d”, &digit); }
switch( digit) }
{
case 1: printf(“One”); Output:
break; Input a digit: 2
Two
Code Example 2
#include <stdio.h> case 'D' :
int main () { printf("You passed\n" );
/* local variable definition */ break;
char grade = 'B'; case 'F' :
switch(grade) { printf("Better try again\n" );
case 'A' : break;
printf("Excellent!\n" ); default :
break; printf("Invalid grade\n" );
case 'B' : }
case 'C' : printf("Your grade is %c\n", grade );
printf("Well done\n" ); return 0;
break; }
Well done
Your grade is B
Differences between if and switch statements
The switch statement can be said to be an alternative to the nested if-else
statement, where the if-else expression are then tested at each of the case’s
variable value.
Differences between if and switch statements
The End
Q&A
Thank you.