Programming Concepts and Constructs
(C Language)
Unit 4.4 - Selection Statements
Presentation 3
Switch Statements
• Is used when you choose from a number of
choices.
Switch Statements - Syntax
switch (<expression>)
{
case <constant1>:
<Statements1>;
break;
case <constant2>:
<Statements2>;
break;
...
...
...
default:
<Statementsn>;
}
Switch Statements - Execution
• The expression following the keyword switch
can either be an integer expression or a
character expression.
• An integer or a character constant follows the
keyword case.
• Based on the value returned by the
expression, the respective case is executed
Flowchart
Start
Accept x
Display
False False False
Case Case Case "Wrong
1? 2? 3? Entry"
True True True
Display Display Display
"You have "You have "You have
entered entered entered
One" Two" Three"
Stop
Activity 4.4.4 (a)
What will be the output of the following code:
int a = 1;
switch(a)
{
case 1:
printf("\n Case 1 ");
break;
case 2:
printf("\n Case 2 ");
break;
case 3:
printf("\n Case 3 ");
break;
default:
printf("\n No match found");
}
Activity 4.4.4 (b)
What will be the output of the following code:
int a = 1;
switch(a)
{
case 1:
printf("\n Case 1 ");
case 2:
printf("\n Case 2 ");
case 3:
printf("\n Case 3 ");
default:
printf("\n No match found");
}
Lab Exercise
1. Write a program to accept a character from
the user.
If the input is V or v, display the text Violet.
If the input is B or b, display the text Blue.
If the input is R or r, display the text Red.
For any other value, display the text Invalid
input.
Lab Exercise
2. Write a program to accept a number that
represents the day of the week and display the
corresponding day.
For example:
1 – Sunday
2 – Monday
3 – Tuesday
4 – Wednesday
5 – Thursday
6 – Friday
7 – Saturday