Tutorial#21 - Switch Statement

Switch Statement


Switch statement:

Switch case statement is used when we have multiple conditions and we need to perform different action based on the condition. When we have multiple conditions and we need to execute a block of statements when a particular condition is satisfied. In such case either we can use lengthy if..else-if statement or switch case. The problem with lengthy if..else-if is that it becomes complex when we have several conditions. The switch case is a clean and efficient method of handling such scenarios.

The syntax of Switch case statement:
switch (variable or an integer expression)
{
     case constant:
     //C++ code
     ;
     case constant:
     //C++ code
     ;
     default:
     //C++ code
     ;
}
Switch Case statement is mostly used with break statement even though the break statement is optional. We will first see an example without break statement and then we will discuss switch case with break.

Flow chart of switch statement is show in figure:


Example of switch statement is:

#include <iostream>
using namespace std;
int main(){
   int num=5;
   switch(num+2) {
      case 1: 
        cout<<"Case1: Value is: "<<num<<endl;
      case 2: 
        cout<<"Case2: Value is: "<<num<<endl;
      case 3: 
        cout<<"Case3: Value is: "<<num<<endl;
      default: 
        cout<<"Default: Value is: "<<num<<endl;
   }
   return 0;

Comments