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 :
- There is another variation to if statement : if-else
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 :
- Consider following program code :
- 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.
Post a Comment