ifelse Double-Selection Statement

The if single-selection statement performs an indicated action only when the condition
is
true; otherwise the action is skipped. The ifelse double-selection statement allows
you to specify an action to perform when the condition is true and a different action to
perform when the condition is
false. For example, the pseudocode statement

If student’s grade is greater than or equal to 60
Print “Passed”
Else
Print “Failed”

prints “Passed” if the student’s grade is greater than or equal to 60, but prints “Failed” if
the student’s grade is less than 60. In either case, after printing occurs, the next pseudocode
statement in sequence is “performed.”
The preceding pseudocode
IfElse statement can be written in C++ as

if ( grade >= 60 )
cout <<
"Passed";
else
cout << "Failed";

Conditional Operator (?:)
C++ provides the conditional operator (?:), which is closely related to the ifelse statement. The conditional operator is C++’s only ternary operator—it takes three operands.
The operands, together with the conditional operator, form a
conditional expression. The
first operand is a condition, the second operand is the value for the entire conditional expression if the condition is
true and the third operand is the value for the entire conditional expression if the condition is false. For example, the output statement

cout << ( grade >= 60 ? "Passed" : "Failed" );

contains a conditional expression, grade >= 60 ? "Passed" : "Failed", that evaluates to
the string
"Passed" if the condition grade >= 60 is true, but evaluates to "Failed" if the
condition is
false. Thus, the statement with the conditional operator performs essentially
the same as the preceding
ifelse statement. As we’ll see, the precedence of the conditional operator is low, so the parentheses in the preceding expression are required.


Nested ifelse Statements
Nested ifelse statements test for multiple cases by placing ifelse selection statements inside other ifelse selection statements. For example, the following pseudocode
ifelse statement prints A for exam grades greater than or equal to 90, B for grades in
the range 80 to 89,
C for grades in the range 70 to 79, D for grades in the range 60 to 69
and
F for all other grades:

If student’s grade is greater than or equal to 90
Print “A”
Else
If student’s grade is greater than or equal to 80
Print “B”
Else
If student’s grade is greater than or equal to 70
Print “C”
Else
If student’s grade is greater than or equal to 60
Print “D”
Else
Print “F”

This pseudocode can be written in C++ as

if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else
if
( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else
if
( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else
if
( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";