Switch Statement in C++

C++ Switch Statement

Switch Statement : When we have most than one valid choice or condition then, most programming languages provide another selection concept known as multiway selection. Multiway selection chooses among several alternatives. C ++ has two different ways to implement multiway selection:

i.Switch Statement
ii. else-if statement

Switch Statement :

This is applicable when we have more than one valid choices to choose from then we can use switch statement instead of if statement.

Syntax :

switch(expression)
{
case value:
statement;
break;
case value2:
statement ;
break;
case 3:
statement;
break;
default :
statement;
}
return 0;
}

Example :

#include<iostream.h>
int main()
{
float a,b;
char opr;
cout<<“Enter number1 operator number2 : “;
cin>>a>>opr>>b;
switch(opr)
 {
case ‘+’:
cout<<“Sum : “<<(a+b)<<endl;
break;
case ‘-‘:
cout<<“Difference : “<<(b-a)<<endl;
break;
case ‘*’:
cout<<“Sum : “<<(a*b)<<endl;
break;
case ‘/’:
cout<<“Difference : “<<(b/a)<<endl;
break;
default :
cout<<”Invalid Input”<<endl;
}
return 0;
}

Output:

Enter number1 operator number2
2
+
3

Sum : 5

Note : Here break is a jump statement and break is used to get out of that condition or that case.
Default is used as else statement if any of the condition doesn’t satisfy then default case will be called. So we have to use default statement in case.


Spread the love

2 thoughts on “Switch Statement in C++”

  1. Pingback: Control Statement In C++ - AskAtul.com

  2. Pingback: For loop in C++ - AskAtul.com

Leave a Comment

Your email address will not be published. Required fields are marked *