Describe Selection – if and switch using C++.
-
if is decision making control and its general for is :
if (this condition is true)
execute this statement;
- The keyword if tells the compiler that what follows, is a decision control instruction. The condition following if is always enclosed in parenthesis. The statement(s) are executed if the condition is true.
-
Example :cout << “\n Enter number:”;
cin >> no;
if (no < 10)
cout<< “Entered number is less than 10”;
- There is another variation to if statement : if-else
if (no < 10)
cout << “No is less than 10”;
else if (no == 10)
cout << “No is equal to 10”;
else
cout << “No greater than 10”;
Switch : - It is used to make choice between multiple options. When a decision is to be made depending upon value of an expression and the programmer knows the possible values it is going to take.
-
The syntax is :switch (integer expression)
{
case constant1:
do this;
case constant2:
do this;
case constant3:
do this;
default:
do this;
}
- Consider following program code :
cout << “\n Enter number:”;
cin >> no;
switch (no)
{
case 1:
cout << “I am in case 1”;
break;
case 2:
cout << “I am in case 2”;
break;
case 3:
cout << “I am in case 3”;
break;
default:
cout << “I am lost!”;
}
- If user enters no 1, 2 or 3, this code will print the appropriate message. For any other no, it will go to the default case and print “I am lost!”
- The advantage of switch is that it leads to more structured program and the level of indentation is manageable, more so if there are multiple statements within each case of a switch. Thus switch statements are very useful in menu driven programs.