Switch Statement In C++


When we want to test multiple condition same time then we can use a switch statement.


Syntax of switch statement


switch(value)

{

case 1:

Statement;

case 2:

Statement;

. . . .

Default: ///optional here

Statement;

}


Simple Example Of Switch Statement In C++

Create a program in c to print day of week using switch case

#include<iostream>

using namespace std;

int main(){

int choice;

clrscr();

cout<<“Enter a week Number 1 To 7”<

cin>>choice

switch(choice)

{

case 1:

cout<<“Monday”;

Break;

case 2:

cout<<“Tuesday”;

break;

case 3:

cout<<“Wednesday”;

break;

case 4:

cout<<“Thursday”;

break;

case 5:

cout<<“Friday”

break;

case 6:

cout<<“Saturday”;

break;

case 7:

cout<<“Sunday”;

break;

default:

cout<<“Invalid Input Number”;

}

return 0;

}


Output:
Enter a week Number   1   To   7
2
Tuesday

We can also use switch statement with Nested switch.

Simple Example Of Nested Switch Statement In C++


#include <iostream>

using namespace std;

int main(){

int choice;

cout<<“Press 1 for Sum of two Number\n”;

cout<<“Press 2 for Muliplication of two Number\n”;

cout<<“Press 3 for Substraction of two Number\n”;

cout<<“Press 4 for Division of two Number\n”;

cin>>“%d”,&choice

cout<<“Enter two Number”;

cin>>“%d%d”,&a,&b;

switch(choice)

{

case 1:

cout<<“The sum of two Numebr :%d”,a+b;

Break;

case 2:

cout<<“The Multiplication of two Numebr :%d”,a*b;

break;

case 1:

cout<<“The Substraction of two Numebr :%d”,a-b;

break;

case 4:

{

cout<<“Press 1 for quotient of two Number”;

cout<<“Press 2 for Remainder of two Number”;

scanf(“%d”,&choice);

switch(choice)

{

case 1:

cout<<“The quotient of two Number (a/b) is :%d”,a/b;

break;

case 2:

cout<<“The Remainder of two Number is (a%b) :%d”,a%b;

break;

}

break;

}

default:

cout<<“Invalid Input!”;

}

return0;

}


Output:
Press 1 for Sum of two Number
Press 2 for Sum of two Number
Press 3 for Sum of two Number
Press 4 for Sum of two Number
2

Enter two Number
12
2
The Multiplication of two Numebr :24