4.6 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 if else double-selection statement allows you to specify an action to perform when the condition is true and another action 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”

represents an ifelse statement that prints “Passed” if the student’s grade is greater than or equal to 60, but prints “Failed” if it’s less than 60. In either case, after printing occurs, the next pseudocode statement in sequence is “performed.”

The preceding IfElse pseudocode statement can be written in C++ as


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

The body of the else is also indented. Whatever indentation convention you choose should be applied consistently throughout your programs.

Good Programming Practice 4.1

Indent both body statements (or groups of statements) of an ifelse statement. Many IDEs do this for you.

 

Good Programming Practice 4.2

If there are several levels of indentation, each level should be indented the same additional amount of space. We prefer three-space indents.

UML Activity Diagram for an ifelse Statement

Figure 4.5 illustrates the flow of control in the preceding ifelse statement. Once again, the symbols in the UML activity diagram (besides the initial state, transition arrows and final state) represent action states and decisions.

Fig. 4.5 ifelse double-selection statement UML activity diagram.

4.6.1 Nested ifelse Statements

A program can test multiple cases by placing ifelse statements inside other ifelse statements to create nested if else statements. For example, the following pseudocode represents a nested ifelse that prints A for exam grades greater than or equal to 90, B for grades 80 to 89, C for grades 70 to 79, D for grades 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”

We use shading to highlight the nesting. This pseudocode may be written in C++ as


if (studentGrade >= 90) {
   cout << "A";
}
else {
   if (studentGrade >= 80) {
      cout << "B";
   }
   else {
      if (studentGrade >= 70) {
         cout << "C";
      }
      else {
         if (studentGrade >= 60) {
            cout << "D";
         }
         else {
            cout << "F";
         }
      }
   }
}

If variable studentGrade is greater than or equal to 90, the first four conditions in the nested ifelse statement will be true, but only the statement in the if part of the first ifelse statement will execute. After that statement executes, the else part of the “outermost” ifelse statement is skipped. Many programmers prefer to write the preceding nested ifelse statement in the following form, which is identical except for the spacing and intentation that the compiler ignores:


if (studentGrade >= 90) {
   cout << "A";
}
else if (studentGrade >= 80) {
   cout << "B";
}
else if (studentGrade >= 70) {
   cout << "C";
}
else if (studentGrade >= 60) {
   cout << "D";
}
else {
   cout << "F";
}

The latter form avoids deep indentation of the code to the right. Such indentation often leaves little room on a line of code, forcing lines to wrap.

Error-Prevention Tip 4.1

In a nested ifelse statement, ensure that you test for all possible cases.

4.6.2 Dangling-else Problem

Throughout the text, we always enclose control statement bodies in braces ({ and }). This avoids a logic error called the “dangling-else” problem. We investigate this problem in Exercises 4.234.25.

4.6.3 Blocks

The if statement normally expects only one statement in its body. To include several statements in the body of an if (or the body of an else for an ifelse statement), enclose the statements in braces. As we’ve done throughout the text, it’s good practice to always use the braces. Statements contained in a pair of braces (such as the body of a control statement or function) form a block. A block can be placed anywhere in a function that a single statement can be placed.

The following example includes a block of multiple statements in the else part of an ifelse statement:


if (grade >= 60) {
   cout << "Passed";
}
else
{
   cout << "Failed
";
   cout << "You must take this course again.";
}

In this case, if grade is less than 60, the program executes both statements in the body of the else and prints


Failed
You must take this course again.

Without the braces surrounding the two statements in the else clause, the statement


cout << "You must take this course again.";

would be outside the body of the else part of the ifelse statement and would execute regardless of whether the grade was less than 60.

Syntax and Logic Errors

Syntax errors (such as when one brace in a block is left out of the program) are caught by the compiler. A logic error (such as an incorrect calculation) has its effect at execution time. A fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error allows a program to continue executing but causes it to produce incorrect results.

Empty Statement

Just as a block can be placed anywhere a single statement can be placed, it’s also possible to have an empty statement, which is represented by placing a semicolon (;) where a statement would normally be.

Common Programming Error 4.1

Placing a semicolon after the parenthesized condition in an if or ifelse statement leads to a logic error in single-selection if statements and a syntax error in double-selection ifelse statements (when the if-part contains a body statement).

4.6.4 Conditional Operator (?:)

C++ provides the conditional operator (?:) that can be used in place of an ifelse statement. This can make your code shorter and clearer. The conditional operator is C++’s only ternary operator (i.e., an operator that takes three operands). Together, the operands and the ?: symbol form a conditional expression. For example, the statement


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

prints the value of the conditional expression. The first operand (to the left of the ?) is a condition, the second operand (between the ? and :) is the value of the conditional expression if the condition is true and the third operand (to the right of the :) is the value of the conditional expression if the condition is false. The conditional expression in this statement evaluates to the string "Passed" if the condition


studentGrade >= 60

is true and to the string "Failed" if it’s false. Thus, this statement with the conditional operator performs essentially the same function as the first ifelse statement in Section 4.6. The precedence of the conditional operator is low, so the entire conditional expression is normally placed in parentheses. We’ll see that conditional expressions can be used in some situations where ifelse statements cannot.

The values in a conditional expression also can be actions to execute. For example, the following conditional expression also prints "Passed" or "Failed":


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

The preceding is read, “If grade is greater than or equal to 60, then cout << "Passed"; otherwise, cout << "Failed".” This is comparable to an ifelse statement. Conditional expressions can appear in some program locations where ifelse statements cannot.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset