Switch Statements in C++

Switch Statements in C++

Switch statements in C++ is used to select one of many code blocks to be executed. The switch statement in C++ executes one statement from multiple conditions. It is same as if-else-if ladder statement in C++

How Switch statements work?

Firstly, switch expression is evaluated for one time then the given value of expression is compared with the value of each case. If this value is match then block of code will be executed.And there are break and default keywords they are optional.

 

Syntax of switch statement

switch(expression){      
case value1:      
 //code ;      
 break;    
case value2:      
 //code ;      
 break;    
......      
      
default:       
 //code ;      
 break;    
}    

Program of switch statement in C++

#include <iostream>  
using namespace std;  
int main () {  
       int num;  
       cout<<"Enter a number:";    
       cin>>num;  
           switch (num)    
          {    
              case 10: cout<<"It is 5"; break;    
              case 20: cout<<"It is 10"; break;    
              case 30: cout<<"It is 15"; break;    
              default: cout<<"Not 5, 10 or 15"; break;    
          }    
    }

Output

Enter a number:
5
It is 5

 

Read more, Loops in C++
Share this post

Leave a Reply

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