Switch Statement in C++ | Topic 7 | VU Insider



What if you are asked about coding a program which gets marks percentage from user and prints out your grade.

In this case, you are required to build multiple code blocks that will be executed to check which code block will satisfy. If your program contains hundreds of code blocks and the 2nd code block satisfies the statement then compiler will not stop at 2nd code block. Compiler will execute all of them.

Hence the program may become time & memory consumer.

To overcome this issue C++ provides switch statement to select one of several code blocks to be executed.

Syntax for Switch Statement:
switch (expression) {
case x:
// code block1
break;
case y:
// code block2
break;
....
case z:
// code block999
break;
} code-box


Example for Switch Statement:
int day = 5;
switch (day) {
case 1:
cout<< "Monday";
break;
case 2:
cout<< "Tuesday";
break;
case 3:
cout<< "Wednesday";
break;
case 4:
cout<< "Thursday";
break;
case 5:
cout<< "Friday";
break;
case 6:
cout<< "Saturday";
break;
case 7:
cout<< "Sunday";
break;
} code-box


The output will be "Friday" as (day 5).

Note: Here break keyword is very important as it will stop compiler for further execution.

Post a Comment

Previous Post Next Post