Using different relational and logical operators,
we can perform different actions for different decisions.
C++ has the following conditional statements:
1. Use 'if' to specify a block of code to be executed, if a specified condition is true
2. Use 'else' to specify a block of code to be executed, if the same condition is false
3. Use 'else if' to specify a new condition to test, if the first condition is false
4. Use 'switch' to specify many alternative blocks of code to be executed
Simple 'if':-
Syntax:-
Example:-
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator).
As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".
if...else:-
Syntax:-
Example:-
Example explained
In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good evening".
If the time was less than 18, the program would print "Good day".
else...if:-
Syntax:-
Example:-
Example explained
In the example above, time (22) is greater than 10, so the condition is false.
The next condition, in the else if statement, is also false,
so we move on to the else condition since condition1 and condition2 is both false
and print to the screen "Good evening".
Short Hand if...else (Ternary Operator):-
Syntax:-
Example:-
The if...else example can be simply written as
switch-case:-
Syntax:-
This is how it works:
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
break and default keywords:-
When C++ reaches a break keyword, it breaks out of the switch block.
This will stop the execution (thus saving time) of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
The default keyword specifies some code to run if there is no case match.
The default keyword must be used as the last statement in the switch, and it does not need a break.