if...else 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 a different action when the condition is false. For example, the pseudocode statement

if grade is greater than or equal to 60

       print "Passed"

else

       print "Failed"

prints "Passed" if the grade is greater than or equal to 60, but prints "Failed" if it is less than 60. In either case, after printing occurs, the next pseudocode statement in sequence is "performed."

The preceding if...else pseudocode statement can be written in C# as

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

Note that the body of the else part is also indented. Whatever indentation convention you choose should be applied consistently throughout your applications. It is difficult to read applications that do not obey uniform spacing conventions.

Good Programming Practice 5 1

Indent both body statements of an if...else statement.

Good Programming Practice 5 2

If there are several levels of indentation, each level should be indented the same additional amount of space.

Figure 5.3 illustrates the flow of control in the if...else statement. Once again, the symbols in the UML activity diagram (besides the initial state, transition arrows and final state) represent action states and a decision. We continue to emphasize this action/decision model of computing. Imagine again a deep bin containing as many empty if...else statements as might be needed to build any C# application. Your job is to assemble these if...else statements (by stacking and nesting) with any other control statements required by the algorithm. You fill in the action states and decision symbols with action expressions and guard conditions appropriate to the algorithm you are developing.

Figure 5.3. if...else double-selection statement UML activity diagram.

 

Conditional Operator (?:)

C# provides the conditional operator (?:), which can be used in place of an if...else statement. This is C#'s only ternary operatorthis means that it takes three operands. Together, the operands and the ?: symbols form a conditional expression. The first operand (to the left of the ?) is a boolean expression (i.e., an expression that evaluates to a bool-type valuetrue or false), the second operand (between the ? and :) is the value of the conditional expression if the boolean expression is true and the third operand (to the right of the :) is the value of the conditional expression if the boolean expression is false. For example, the statement

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

prints the value of WriteLine's conditional-expression argument. The conditional expression in this statement evaluates to the string "Passed" if the boolean expression grade >= 60 is TRue and evaluates to the string "Failed" if the boolean expression is false. Thus, this statement with the conditional operator performs essentially the same function as the if...else statement shown earlier in this section. You will see that conditional expressions can be used in some situations where if...else statements cannot.

Good Programming Practice 5 3

Conditional expressions are more difficult to read than if...else statements and should be used to replace only simple if...else statements that choose between two values.

Good Programming Practice 5 4

When a conditional expression is inside a larger expression, it's good practice to parenthesize the conditional expression for clarity. Adding parentheses may also prevent operator precedence problems that could cause syntax errors.

 

Nested if...else Statements

An application can test multiple cases by placing if...else statements inside other if...else statements to create nested if...else statements. For example, the following pseudocode represents a nested if...else statement that 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 grade is greater than or equal to 90

      print "A"

else

      if grade is greater than or equal to 80

            print "B"

      else

            if grade is greater than or equal to 70

                  print "C"

            else

                  if grade is greater than or equal to 60

                        print "D"

                  else

                        print "F"

This pseudocode may be written in C# as

if ( grade >= 90 ) Console.WriteLine( "A" ); else if ( grade >= 80 ) Console.WriteLine( "B" ); else if ( grade >= 70 ) Console.WriteLine( "C" ); else if ( grade >= 60 ) Console.WriteLine( "D" ); else Console.WriteLine( "F" );

If grade is greater than or equal to 90, the first four conditions will be true, but only the statement in the if-part of the first if...else statement will execute. After that statement executes, the else-part of the "outermost" if...else statement is skipped. Most C# programmers prefer to write the preceding if...else statement as

 

if ( grade >= 90 ) Console.WriteLine( "A" ); else if ( grade >= 80 ) Console.WriteLine( "B" ); else if ( grade >= 70 ) Console.WriteLine( "C" ); else if ( grade >= 60 ) Console.WriteLine( "D" ); else Console.WriteLine( "F" );

The two forms are identical except for the spacing and indentation, which the compiler ignores. The latter form is popular because it avoids deep indentation of the code to the rightsuch indentation often leaves little room on a line of code, forcing lines to be split and decreasing the readability of your code.

Dangling-else Problem

The C# compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }). This behavior can lead to what is referred to as the dangling-else problem. For example,

if ( x > 5 ) if ( y > 5 ) Console.WriteLine( "x and y are > 5" ); else Console.WriteLine( "x is <= 5" );

appears to indicate that if x is greater than 5, the nested if statement determines whether y is also greater than 5. If so, the string "x and y are > 5" is output. Otherwise, it appears that if x is not greater than 5, the else part of the if...else outputs the string "x is <= 5".

Beware! This nested if...else statement does not execute as it appears. The compiler actually interprets the statement as

if ( x > 5 ) if ( y > 5 ) Console.WriteLine( "x and y are > 5" ); else Console.WriteLine( "x is <= 5" );

in which the body of the first if is a nested if...else. The outer if statement tests whether x is greater than 5. If so, execution continues by testing whether y is also greater than 5. If the second condition is true, the proper string"x and y are > 5"is displayed. However, if the second condition is false, the string "x is <= 5" is displayed, even though we know that x is greater than 5.

To force the nested if...else statement to execute as it was originally intended, we must write it as follows:

if ( x > 5 ) { if ( y > 5) Console.WriteLine( "x and y are > 5" ); } else Console.WriteLine( "x is <= 5" );

The braces ({}) indicate to the compiler that the second if statement is in the body of the first if and that the else is associated with the first if. Exercises 5.275.28 investigate the dangling-else problem further.

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 if...else statement), enclose the statements in braces ({ and }). A set of statements contained within a pair of braces is called a block. A block can be placed anywhere in an application that a single statement can be placed.

The following example includes a block in the else-part of an if...else statement:

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

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

Failed. You must take this course again.

Note the braces surrounding the two statements in the else clause. These braces are important. Without the braces, the statement

Console.WriteLine( "You must take this course again." );

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

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

Common Programming Error 5 1

Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic errors in an application.

Good Programming Practice 5 5

Always using braces in an if...else (or other) statement helps prevent their accidental omission, especially when adding statements to the if-part or the else-part at a later time. To avoid omitting one or both of the braces, some programmers type the beginning and ending braces of blocks before typing the individual statements within the braces.

Just as a block can be placed anywhere a single statement can be placed, it is also possible to have an empty statement. Recall from Section 3.9 that the empty statement is represented by placing a semicolon (;) where a statement would normally be.

Common Programming Error 5 2

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

while Repetition Statement

Категории