Programming

Switch Statement in C and C++

Sometimes there arrives a situation where you want multiple if-else conditions but writing and maintaining all the sequences and choices can become difficult and even complicated. In simple words, consider this example:

Let say, you have an application which takes an integer input for finding a month in a year. Then, it would be better to go with switch statements without going to 12 times if-else statements for every months. Syntax for switch case:

Switch (choice)

{

   Case 1:   // if choice is equal to 1

   Break;

   Case 2:   // if choice is equal to 2

   Break;

     ……..

  Default :  // this executes if none of the case matches.

}

Flowchart for Switch in C and C++

Switch Case
Flowchart for Switch Case

Some facts about switch conditions

  • The expression inside the switch function should be a constant value or valid expression, else it might through error. For example,

    Switch (2+8/2)     // it is valid

    Switch (10-b+1)    // it is invalid

  • Don’t use duplicate case, it can lead to error.
  • Always use break statement ( though it’s optional ) , else it will match other case and also execute till the last statement in switch condition.
  • The Default statement is optional, but it is advise to use it for good programming practice.
  • You can also perform nesting switch statement, i.e, switch case inside of another switch statement. But try to avoid it, as it might increase difficulty in reading the code.

Example of Switch Condition

#include<iostream>
using namespace std;

int main()
{
   int n;
   cout << "Enter the month in numbers" << endl;
   cin >> n;
   switch (n)
   {
        case 1:
        cout<<"January"<<endl;
        break;
        case 2:
        cout<<"Feburary"<<endl;
        break;
        case 3:
        cout<<"March"<<endl;
        break;
        case 4:
        cout<<"April"<<endl;
        break;
        case 5:
        cout<<"May"<<endl;
        break;
        case 6:
        cout<<"June"<<endl;
        break;
        case 7:
        cout<<"July"<<endl;
        break;
        case 8:
        cout<<"August"<<endl;
        break;
        case 9:
        cout<<"September"<<endl;
        break;
        case 10:
        cout<<"October"<<endl;
        break;
        case 11:
        cout<<"November"<<endl;
        break;
        case 12:
        cout<<"December"<<endl;
        break;
        default :
        cout<<"Invalid month have been entered "<<endl;
   }
   return 0;
}

Output

Enter the month in number

3

March

Facebook Comments

Show More

Leave a Reply

Back to top button