C++ Selection Statements
Selection statements are used to decide the course of a program. Selection statements basically execute some lines of code if one condition is met and a different set of lines if the condition is not met.
To understand selection statements better consider a problem statement
Write code for a gaming competition where if you score 900 to 1000 points (1000 being the maximum) you win Rs.5000 and anything lesser than 900 points earns you nothing.
The condition to earn Rs.5000 in this example is points greater than 900.
Lets see how we can write this in C++ using selection statements.
C++ provides us with 2 ways in which we can select which lines of code are to be executed based on the condition.
if, else if and else statements
In the above example, we have the condition:-points greater than 900 if this is true then earn 5000 else you earn nothing.
Syntax of if/else statements:
Syntax of if/else statements:
But only having one Rs.5000 prize is not interesting, let's add some more conditions if your score is less than 900 but greater than 800 you win a prize of Rs.2000 and scoring less than 800 but greater than 700 will earn you Rs.1000. Any score lesser than 700 does not win anything.
Syntax
Now, write a program for the same.
Let us try to write a code for the above conditions.
Nested if/else
Consider example problem
Airplane tickets If you have a membership then, adult ticket is Rs.70,000, children under 14 years ticket are Rs.40,000 if you do not possess the membership then the cost for 1 adult ticket is Rs.85000 and for children, it is Rs.60,000
Write a program to ask the user if he has the membership or not and based on the ticket type display the bill.
Using if-else statements, again and again, is annoying so C++ offers another alternative Switch statements.
Switch
The s***witch*** is used when we have more than 2 paths in which the program can be executed. It usually contains multiple switch cases and a default case which is executed only if neither of the above case condition is met. The variable in the bracket is compared with the test conditions and if the condition is met then the statement is executed. Each switch statement ends with a |break|. This is done to prevent statements following from being executed.
Syntax
Lets create a simple shooting game using switch statements.