Wednesday, January 15, 2014

The if selection structure performs an indicated action only when the condition evaluates
to true; otherwise, the action is skipped. The if/else selection structure allows the pro-
grammer to specify different actions to perform when the condition is true and 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, and 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 If/Else structure may be written in C# as

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

 



        Good Programming Practice 4.1
Indent both body statements of an if/else structure.
      
Note that the body of the else statement also is indented. The indentation convention
you choose should be applied carefully throughout your programs. It is difficult to
read programs that do not use uniform spacing conventions.

The flowchart in Fig. 4.4 illustrates the flow of control in the if/else structure. Note
that (besides small circles and arrows) the only symbols in the flowchart are rectangles (for
actions) and a diamond (for a decision). We continue to emphasize this action/decision
model of computing.

The conditional operator (?:) is related closely to the if/else structure. The ?: is
C#’s only ternary operator—it takes three operands. The operands and the ?: form a conditional expression. The first operand is a condition (i.e., an expression that evaluates to a bool value), the second is the value for the conditional expression if the condition evaluates to true and the third is the value for the conditional expression if the condition evaluates to false. For example, the output statement
          Console.WriteLine( studentGrade >= 60 ? "Passed" : "Failed" );
contains a conditional expression that evaluates to the string "Passed" if the condition
studentGrade>=60 is true and evaluates to the string "Failed" if the condition is
false.

image

The statement with the conditional operator performs in the same manner as the pre-
ceding if/else statement. The precedence of the conditional operator is low, so the entire
conditional  expression  normally  is  placed  in  parentheses.  Conditional  operators  can  be
used in some situations where if/else statements cannot, such as the argument to the
WriteLine method shown earlier.
Nested if/else structures can test for multiple cases by placing if/else struc-
tures inside other if/else structures. For example, the following pseudocode statement
will print A for exam grades greater than or equal to 90, B for grades in the range 80–89,
C for grades in the range 70–79, D for grades in the range 60–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 may be written in C# as
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" );

If studentGrade is greater than or equal to 90, the first four conditions are true, but only
the Console.WriteLine statement after the first test executes. After that particular
Console.WriteLine executes, the program skips the else part of the “outer” if/
else structure.

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

Most C# programmers prefer to write the preceding if structure as
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" );

Both forms are equivalent. The latter form is popular because it avoids the deep indentation
of the code. Such indentation often leaves little room on a line, forcing lines to be split and
decreasing program readability.
The C# compiler always associates an else with the previous if, unless told to do
otherwise by the placement of braces ({}). This 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 if structure in its body determines if 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 structure outputs the string
"xis<=5".

Testing and Debugging Tip 4.1
The reader can use Visual Studio to indent code properly. In order to check indentation, the
reader should highlight the relevant code and press Ctrl-K followed immediately by Ctrl-F.

However,  the  preceding  nested  if  structure  does  not  execute  as  its  indentation
implies. The compiler actually interprets the structure 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 structure is an if/else structure. This structure tests if
x is greater than 5. If so, execution continues by testing if 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
x is greater than 5.

To force the preceding nested if structure to execute as it was originally intended, the
structure must be written 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 structure is in the body of the
first if structure and that the else is matched with the first if structure.
The if selection structure normally expects only one statement in its body. To include
several statements in the body of an if, enclose these statements in braces ({ and }). A set
of statements contained in a pair of braces is called a block.

Software Engineering Observation 4.2
A block can be placed anywhere in a program at which a single statement can be placed.  

The following example includes a block in the else part of an if/else structure:
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.
Notice the braces surrounding the two statements in the else clause. These braces are im-
portant. Without the braces, the statement
Console.WriteLine( "You must take this course again." );
would be outside the body of the else and would execute regardless of whether the grade
is less than 60.

Common Programming Error 4.1
Forgetting one of the braces that delimit a block can lead to syntax errors. Forgetting both of the braces that delimit a block can lead to syntax and/or 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 error caused when both braces in a block are left out of the program, 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 the program produces incorrect results.

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

Common Programming Error 4.2
Placing a semicolon after the condition in an if structure leads to a logic error in single-
selection if structures and a syntax error in double-selection if structures (if the if clause
contains a nonempty body statement).
  

Good Programming Practice 4.3
Some programmers prefer to type the beginning and ending braces of blocks before typing
the individual statements within the braces. This practice helps avoid omitting one or both of
the braces.
   

  

In this section, we introduced the notion of a block. A block may contain declarations.
The declarations in a block commonly are placed first in the block before any action statements, but declarations may be intermixed with action statements.

0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!