Switch case in cpp is condition statement in cpp
Switch statement is multiple decision making statement.
It tests variable with the equivalent value which is called as case.This case must be constant integer.
Switch case : this switch statement which contains multiple branch statements.Its checks with each value. each value is called as the case. if this case true then statement in this case is executed.
Syntax for switch case
switch(expression)
{
case value:
// statements.
break;
case value:
// statements.
break;
default:
//statements
break;
}
Switch contains case and it’s statements of any value case is true then statement in case is executed
and (if we not written break )after that all case with their statement are also get executed is called fall through.
we write break after each case because we do not need to execute rest of the cases(to avoid fall through).
default case in switch statement is not compulsory.it is used for case which is not present.
switch case Example
switch (1){
case 1:
cout<<“switch case”;
break;
default:
cout <<“default”;
break;
}
Switch case program in cpp
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
#include <iostream> using namespace std; int main() { int ch; cout<<"Enter number"; cin>>ch; switch(ch) { case 1: cout<<"number is 1"; break; case 2: cout<<"number is 2"; break; case 3: cout<<"number is 3"; break; case 4: cout<<"number is 4"; break; case 5: cout<<"number is 5"; break; default: cout<<"other number"; } cout<<" \nswitch case executed "; return 0; } |
Output :

Program description
1. In above program we written switch statement to check user choice.
2. First we take input from user in ch variable.
=> ch = 2
3. Next switch case executed.
4. First it checks case 1 with ch = 2
=> case 1 => 1 = 2 condition false and switch case 1 not executed
=> case 2 =>2 = 2 condition true
5. and case 2 executed.
cout<<“number is 2″;
=> number is 2
6. At last print message
=> cout<<” \nswitch case executed “;
Leave a Reply