Home >>C++ Tutorial >C++ Switch

C++ Switch

C++ Switch

Just like other statements, this switch statement in C++ programming is generally used to execute only one condition from the multiple conditions. If compared then it is very similar to the if-else-if ladder statement in the C++ programming.

Here is the syntax for the same:

switch(expression)
{      
case 1:      
 //code that is to be executed;      
 break;    
case 2:      
 //code that is to be executed;      
 break;

case 3:      
 //code that is to be executed;      
 break; 
......      
      
default:       
 //code that is to be executed if all cases are not matched;      
}

Here is an example of the switch statement in C++ for you to understand it better:

#include <iostream>  
using namespace std;  
int main () 
{  
   int num = 3;    
	switch(num)
	{
	case 1:
	cout<<"Today is Monday";
	break;
	
	case 2:
	cout<<"Today is Tuesday";
	break;
	
	case 3:
	cout<<"Today is Wednesday";
	break;
	
	case 4:
	cout<<"Today is Thursday";
	break;
	
	case 5:
	cout<<"Today is Friday";
	break;
	
	case 6:
	cout<<"Today is Saturday";
	break;
	
	case 7:
	cout<<"Today is Sunday";
	break;
	
	default:
	cout<<"Wrong choice";
	}
   return 0;  
}  
Output : Today is Wednesday

Here is another example of the switch statement(To check given char is vowel or consonant)

#include <iostream>
using namespace std;
int main()
{
     char c;
     cout<<"Enter any character: ";
    cin>>c;
  
     switch(c)
    {
        case 'a': 
		cout<<"a is vowel";
        break;
        
		case 'e':
		cout<<"e is vowel";
        break;
        
		case 'i':
		cout<<"i is vowel";
        break;
        
		case 'o':
		cout<<"o is vowel";
        break;
        
		case 'u':
		cout<<"u is vowel";
        break;
       default:
	   cout<<"Given alphabet is consonant";
    }
    return 0;
}
Output :
Enter any character: e
e is vowel
Output :
Enter any character: b
Given alphabet is consonant