Lecture 2 Week 5
Lecture 2 Week 5
FUNDAMENTALS
LAB
Umer Ahmad
Lecture 2 week 5
Switch statement
•Aswitch statement allows a variable to be tested for equality
against a list of values. Each value is called a case, and the
variable being switched on is checked for each case.
switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
Syntax break; //optional
// you can have any number of case
statements.
default :
//Optional
statement(s);
}
FLOW
DIAGRA
M
Without break statement
case 3:
#include <iostream>
using namespace std;
cout<<"Case3 "<<endl;
int main() case 4: Output:
{ Case2
cout<<"Case4 "<<endl;
Case3
int i=2;
default: Case4
switch(i) Default
{
cout<<"Default "<<endl;
case 1: }
cout<<"Case1 "<<endl; return 0;
case 2:
}
cout<<"Case2 "<<endl;
Example • Inthe above program, we have the
variable i inside switch braces, which
Explained means whatever the value of variable i
is, the corresponding case block gets
executed. We have passed integer
value 2 to the switch, so the control
switched to the case 2, however we
don’t have break statement after the
case 2 that caused the flow to continue
to the subsequent cases till the end.
However this is not what we wanted,
we wanted to execute the right case
block and ignore rest blocks. The
solution to this issue is to use the break
statement in after every case block.
Break Statement Used
Break statements are used when you want your program-flow to
come out of the switch body. Whenever a break statement is
encountered in the switch body, the execution flow would directly
come out of the switch, ignoring rest of the cases. Therefore, you
must end each case block with the break statement.
Tell me the output??
Continue..
• case 'C’ :
• break;
• case 'D’ :
• break;
• case 'F’ :
• break;
• default :
• }
• return 0;
• }
PRACTICE
PROGRAM 1
Checking the number whether number is even or odd
PRACTICE PROGRAM 2
Print weekday using switch statement
LAB TASK
Calculator using switch statement