Chapter 4 Control Structures: (Web hosting providers) Part 1 155 4.6
Chapter 4 Control Structures: Part 1 155 4.6 The if/elseSelection Structure The if selection structure performs an indicated action only when the given condition evaluates to true; otherwise, the action is skipped. The if/else selection structure allows the programmer to specify that a different action is to be performed when the condition is true rather than 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. Note that the body of the else is also indented. Good Programming Practice 4.2 Indent both body statements of an if/else structure. The indentation convention you choose should be carefully applied throughout your programs. It is difficult to read programs that do not use uniform spacing conventions. The preceding pseudocode If/else structure may be written in Java as if ( studentGrade >= 60 ) System.out.println( “Passed” ); else System.out.println( “Failed” ); The flowchart in Fig. 4.4 nicely illustrates the flow of control in an if/elsestructure. Once again, 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. Imagine again a deep bin containing as many empty double-selection structures as might be needed to build a Java algorithm. The programmer s job is to assemble the selection structures (by stacking and nesting) with other control structures required by the algorithm and to fill in the empty rectangles and empty diamonds with actions and decisions appropriate to the algorithm being implemented. grade >= 60 true print Failed false print Passed Fig. 4.4Flowcharting the double-selection if/elsestructure. Fig. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01