In this tutorial you will learn about the C++ Switch Case Statement and its application with practical example.
C++ Switch Case Statement
In C++, switch case statement is simplified form of the C++ Nested if else statement , it helps to avoid long chain of if..else if..else statements. A switch case statement evaluates an expression against multiple cases in order to identify the block of code to be executed.
C++ Switch Case Flow Diagram
Syntax:-
1 2 3 4 5 6 7 8 9 10 11 |
switch(expression){ case value1: // statements break; case value2: // statements break; default: // statements break; } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <iostream> using namespace std; int main() { const int dayOfWeek = 5; cout<<"W3Adda - C++ Switch Case statement."; switch(dayOfWeek){ case 1: cout<<"\nToday is Monday."; break; case 2: cout<<"\nToday is Tuesday."; break; case 3: cout<<"\nToday is Wednesday."; break; case 4: cout<<"\nToday is Thursday."; break; case 5: cout<<"\nToday is Friday."; break; case 6: cout<<"\nToday is Saturday."; break; case 7: cout<<"\nToday is Sunday."; break; default: cout<<"\nInvalid Weekday."; break; } return 0; } |
In the above program we have an integer constant dayOfWeek with initial value of 5, and we pass this variable as expression to following switch statement, value of dayOfWeek is tested with multiple cases to identify the block of code to be executed.
When we run the above c++ program, will see the following output –
Output:-