Switch Statement in C++

Switch statement is a substitute for long if statements that compare a variable to several integral values (integral values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.

Switch Statement Syntax

switch (value) {

case this-value:

Code to execute if value == this-value
break;

case that-value:

Code to execute if value == that-value
break;

default:

Code to execute if value does not equal any of the cases
break;

}

Switch Statement Example

int age;
cout << “What is your age: “; cin >> age;

switch (age)
{

case 1:

cout << “You are 1 year old”;
break;

case 2:

cout << “You are 2 years old”;
break;

case 3:

cout << “You are 3 years old”;
break;

default:

cout << “You are older than 3 years”;

}

Break Statement

The break command can be used to exit a loop at any time. Here is an example that will print “Hello” 5 times and then break out of the loop.

int x;
for (x = 1; x <= 10; x++)
{

cout << “Hello\n”;
if(x == 5)
break;

}

Continue Statement

The continue command lets you start the next iteration of the loop. The following example will not print “Hello” on 5th iteration because the continue command goes back to the beginning of the loop.

int x;
for (x = 1; x <= 10; x++)
{

if(x == 5)
continue;
cout << “Hello\n”;

}

Leave a Reply

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