Decision Control Statements in C++ – Part 2
Written by
In this chapter, we will learn about If- Else If Statements and the Switch Case Statements.
If – Else If Statements:
When a condition is checked then there are two possible outcomes, either true or false. However, when a new condition needs to be checked depending upon the result of the previous condition, then we use the If- Else If Statements.
For Example: If you want to go out for a movie, then you will first check if the weather permits you to go out or not. If the weather permits, then only you will search for an interesting movie, if you find something worth watching then you will book the tickets.
Now, the above situation can be explained using the if-else if statements as follows:
if(weather is not okay)
{
cout<< “Don’t Go”;
}
else if(weather is okay)// if-else if statements
{
if(good movie available) // nested if else statements
{
cout<< “Book Tickets”;
}
else
{
cout<< “Don’t Book Tickets”;
}
}
The if-else statements can also be nested.
Switch Case Statements:
switch case statement is a multi-directional conditional control statement.
It helps the user to evaluate a particular condition and on the basis of the result produced execute the statements. It can be used to execute statements based on different values.
Syntax:
switch(condition)
{
case 1:
statement(s);
case 2:
statement(s);
.
.
.
.
.
.
case n:
statement(s);
default:
statement(s);
}
The cases include the possible values the condition can return and with the case, the value returned matches the statements included in that particular case are executed along with all the statements below it. This is called a fall-through case. To prevent it we use a jumping statement called break. We will learn more about jumping statements later on.
The default case is executed if the value returned does not match with any case.
Example:
#include <iostream.h>
void main()
{
int num;
cout<< “Enter any number between 1 to 4”;
cin>>num;
switch(num)
{
case 1:
cout<< “You have entered ONE”;
break;
case 2:
cout<< “You have entered TWO”;
break;
case 3:
cout<< “You have entered THREE”;
break;
case 4:
cout<< “You have entered FOUR”;
break;
default:
cout<< “You have not entered any number between 1 to 4” ;
break;
}
}
In the above example, the number entered by the user is checked against four cases.
If the user enters 1 then case1 is executed, if 2 is entered then case2 is executed and so on. However, if none of the cases matches that is if the user has not entered any number between 1 to 4 then the default case is executed.