C++ Decision making(cont.)

We have seen the use of if,if-else and if-else if-else loops for decision making.If there are too many else if statements the program becomes difficult and cumbersome. For this purpose we use the switch statement to replace multiple else if statements. The basic syntax of a switch statement is as follows:

switch (a)
​{
case constant1:
// code to be executed if a is equal to constant1;
break;

case constant2:
// code to be executed if a is equal to constant2;
break;
.
.
default:
// code to be executed if a doesn’t match any constant
}

Example of a switch statement :

int numberofapples = 2;
switch (x)
{
case 1: printf(“Number of apples is 1”);
break;
case 2: printf(“Number of apples is 2”);
break;
case 3: printf(“Number of apples is 3”);
break;
default: printf(“Number of apples is not 1 or 2 or 3”);
break;

  • The default block,as the comment says, is executed if none of the other cases match.This block is optional.

  • The break keyword at the end of each block causes control to jump to the end of switch statement after that particular block is processed.It is very important to include the break statement after every case or else the condition called “fall through” will occur which basically means even if a particular case is true and that block is executed, if there is no break statement, control will enter all subsequent blocks and execute them all unless a break is encountered.

  • C++ switch statements support int and char data values. 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: