Switch Case

0 jennypratten96 November 13, 2020

When there are a number of else alternatives, a switchstatement is another way of representing this multi-way selection. A switchstatement allows the user to choose a statement among several alternatives.  The switchstatement is used to be compared with different constants, and in case it equal to a constant, a set of statements are to be executed. The constants in the case statement may be either charor inttype only.

The syntax of the switch statement is:

switch(variabe name)
{
    case case_constant_1:
         statements;
         break;

    case case_constant_1:
         statements;
         break;

    default:
         statements;
}
Switch Statement
Switch Statement

Let’s look at one example to make clear concepts on switch case.

#include <iostream>
using namespace std;

int main(){

    int choice;

    cout << "Select 1 for File, 2 for Edit, 3 for save" << endl;
    cin >> choice;

    switch(choice)
    {
        case 1:
            cout << "You have chosen File menu item" << endl;
            break;

        case 2:
            cout << "You have chosen Edit menu item" << endl;
            break;

        case 3:
            cout << "You have chosen Save menu item" << endl;
            break;

        default:
            cout << "Invalid Options" << endl;
    }

    return 0;
}

The output of the above program is:

Select 1 for File, 2 for Edit, 3 for save
2
You have chosen Edit menu item