How to Use Switch Statements in C++

When dealing with conditions in C/C++, to make comparisons and to change the flow of programs, if conditions are used but if you have to code a longer comparison or cases, too many if statements are not a good idea to use. To cope with this C and C++ provides us an alternative method to code the conditions and the comparisons, this method is called switch statement method and you can make a switch on any type of variable and then you have to write cases for that switch. I will explain the syntax and correct use of Switch statements step by step.

Instructions

  • 1

    Syntax:
    The general layout of syntax of using switch statements is described below followed by an example.
    [php]
    switch (vari){
    case condition1:
    //set of statements to execute;
    break;
    case condition2:
    //set of statements to execute;
    break;
    default:
    //set of statements to execute if none of the conditions mentioned above is satisfied.
    break;
    }
    [/php]

  • 2

    The switch checks the value of variable which is given as in input to the switch. Then it checks the conditions and conditions are placed on the value of variable. If a certain condition is true then the statements below that condition will execute. If none of the conditions is met then the statements below the default case will execute.


    The use of switch statements is very easy. I will write a sample code in next step, which will help you to get started with switch statements.

  • 3

    Below is the sample code to elaborate the use of switch statements. The code will check the value of an integer and then it will print the value depending on the value entered.


    #include


    using namespace std;


    int main (){


    int user_input;


    cout<<”please enter a number between 1 to 3 inclusive: ”;


    cin>>user_input;


    switch(user_input){


    case 1:


    cout<<”you have entered 1”<


    break;


    case 2:


    cout<<”you have entered 2”<


    break;


    case 3:


    cout<<”you have entered 3”<


    break;


    default:


    cout<<”you have entered an invalid number”<


    break;


    }


    return 0;


    }



    I hope that this guide helps you to get going with switch statements.


    Note: the syntax of switch statements is almost same in C language.

Leave a Reply

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


5 + three =