if
…else
Double-Selection StatementThe 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 student's grade is greater than or equal to 60
Display "Passed"
Else
Display "Failed"
represents an if
…else
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 if…else 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.
Indent both body statements of an if
…else
statement. Visual Studio does this for you.
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. Figure 5.4 illustrates the flow of control in the preceding An app can test multiple cases by placing We use shading to highlight the nesting. This pseudocode may be written in C# as If variable 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. In a nested Throughout the text, we always enclose control statement bodies in braces ( The The following example includes a block of multiple statements in the In this case, if Without the braces surrounding the two statements in the would be outside the body of the 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. 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 ( Placing a semicolon after the parenthesized condition in an C# provides the conditional operator ( The first operand (to the left of the The second operand (between the The third operand (to the right of the 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 displays the value of is Good Programming Practice 5.2
UML Activity Diagram for an
if
…else
Statementif
…else
statement. Once again, the symbols in the UML activity diagram (besides the initial state, transition arrows and final state) represent action states and decisions.5.6.1 Nested
if
…else
Statementsif
…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 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:studentGrade
is greater than or equal to 90, the first four conditions in the nested if
…else
statement 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. Many programmers prefer to write the preceding nested if
…else
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");
}
Error-Prevention Tip 5.1
if
…else
statement, ensure that you test for all possible cases.5.6.2 Dangling-
else
Problem{
and }
). This avoids a logic error called the “dangling-else
” problem. We investigate this problem in Exercises 5.27–5.29.5.6.3 Blocks
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), 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.else
part of an if
…else
statement:
if (studentGrade >= 60)
{
Console.WriteLine("Passed");
}
else
{
Console.WriteLine("Failed");
Console.WriteLine("You must take this course again.");
}
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.
else
clause, the statement
Console.WriteLine("You must take this course again.");
else
part of the if
…else
statement and would execute regardless of whether the grade was less than 60.Syntax and Logic Errors
Empty Statement
;
) where a statement would normally be. Common Programming Error 5.1
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 a body statement).5.6.4 Conditional Operator (
?:
)?:
) that can be used in place of an if
…else
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:
?
) is a bool
expression that evaluates to true
or false
.?
and :
) is the value of the conditional expression if the bool
expression is true
.:
) is the value of the conditional expression if the bool
expression is false
.
Console.WriteLine(studentGrade >= 60 ? "Passed" : "Failed");
WriteLine
’s conditional-expression argument. The conditional expression in the preceding statement evaluates to the string
"Passed"
if the condition
studentGrade >= 60
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 if
…else
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 if
…else
statements cannot.