5.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 ifelse double-selection statement allows you to specify an action to perform when the condition is true and a different action when the condition is false. For example, the pseudocode statement


If student's grade is greater than or equal to 60
      Display "Passed"
Else
      Display "Failed"

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

The preceding ifelse pseudocode statement can be written in C# as


if (grade >= 60)
{
   Console.WriteLine("Passed");
}
else
{
   Console.WriteLine("Failed");
}

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

Good Programming Practice 5.1

Indent both body statements of an ifelse statement. Visual Studio does this for you.

Good Programming Practice 5.2

If there are several levels of indentation, each level should be indented the same additional amount of space. Again, we use three-space indents for book-publication purposes, but Microsoft recommends four-space indents—the default in Visual Studio.

UML Activity Diagram for an ifelse Statement

Figure 5.4 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. 5.4 ifelse double-selection statement UML activity diagram.

5.6.1 Nested ifelse Statements

An app can test multiple cases by placing ifelse statements inside other ifelse statements to create nested ifelse statements. For example, the following pseudocode represents a nested ifelse statement that displays A for exam grades greater than or equal to 90, B for 80 to 89, C for 70 to 79, D for 60 to 69 and F for all other grades:

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

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 indentation that the compiler ignores:


if (studentGrade >= 90)
{
   Console.WriteLine("A");
}
else if (studentGrade >= 80)
{
   Console.WriteLine("B");
}
else if (studentGrade >= 70)
{
   Console.WriteLine("C");
}
else if (studentGrade >= 60)
{
   Console.WriteLine("D");
}
else
{
   Console.WriteLine("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 5.1

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

5.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 5.275.29.

5.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), you must 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, property or method) form a block. A block can be placed anywhere in a control statement, property or method 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 (studentGrade >= 60)
{
   Console.WriteLine("Passed");
}
else
{
   Console.WriteLine("Failed");
   Console.WriteLine("You must take this course again.");
}

In this case, if studentGrade 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


Console.WriteLine("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 the problem above or 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 5.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).

5.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—it takes three operands. Together, the operands and the ?: symbols form a conditional expression:

  • The first operand (to the left of the ?) is a bool expression that evaluates to true or false.

  • The second operand (between the ? and :) is the value of the conditional expression if the bool expression is true.

  • The third operand (to the right of the :) is the value of the conditional expression if the bool expression is false.

For now, the second and third operands should have the same type. In Section 7.6, we’ll discuss implicit conversions that may occur if these operands do not have the same type.

For example, the statement


Console.WriteLine(studentGrade >= 60 ? "Passed" : "Failed");

displays the value of WriteLine’s conditional-expression argument. The conditional expression in the preceding 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 task as the first ifelse statement shown in Section 5.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.

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

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