• Have Any Question?
  • contact@eitworld.com

cpp switch statement





C++ switch statement

    • switch-case statement is a multi-way branch statement.
    • case statement enables the user to choose a option from a number of options.
    • The switch statement requires only one argument/expression of any data type which is checked with the case constants. If the value of expression is matches with any case constant then that particular case statement is executed, If the value of expression does not match with any case constant then default block is executed.
    • The break statement is used to exit from the current case block.
    • switch statement is alternate of if else ladder statements.
    • In switch case, default is the optional part if we don’t want to use then program will run smoothly without any error.
    • Here is the syntax of switch-case statement:

Syntax

switch(expression)

{

case constant A:

statements;

break;

case constant B:

statements;

break;

default:

statements;

}

    • According to the above syntax if the expression matches with the case constant A then the statements present inside case constant A block will be executed, if the expression matches with the case constant B then the statements present inside case constant B block will be executed and if expression does not match with any of the case constants then the statement present inside the default block will be executed. Here is the diagram that shows the concept of switch-case statement:

decision-making

  • Here is an example of switch-case statement as follows:

Example

#include<iostream.h>

#include<conio.h>

int main()

{

int choice;

cout<<“n Enter your choice:”;

cin>>choice;

switch(choice)

{

case 1:

cout<<“nYour choice is 1”;

break;

case 2:

cout<<“nYour choice is 2”;

break;

case 3:

cout<<“nYour choice is 3”;

break;

default:

cout<<“nNo match found”;

break;

}

getch();

return 0;

}

Output

The output of the above program is as follows:

Enter your choice: 3

Your choice is 3



Real Time Web Analytics