Programming Concepts and Constructs (C Language) : Unit 4.4 - Selection Statements
Programming Concepts and Constructs (C Language) : Unit 4.4 - Selection Statements
(C Language)
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
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