206 Control Structures: Part 2 Chapter 5 Common (Free web host)

206 Control Structures: Part 2 Chapter 5 Common Programming Error 5.6 Not using the proper relational operator in the loop-continuation condition of a loop that counts downward (such as using i<=1in a loop counting down to 1) is usually a logic error and will yield incorrect results when the program runs. The next two sample programs demonstrate simple applications of the forrepetition structure. The application in Fig. 5.5 uses the for structure to sum all the even integers from 2to 100. Remember that the javainterpreter is used to execute an application from the command window. Note that the body of the for structure in Fig. 5.5 could actually be merged into the rightmost portion of the forheader by using a comma as follows: for ( int number = 2; number <= 100; sum += number, number += 2 ) ; // empty statement 1 // Fig. 5.5: Sum.java 2 // Counter-controlled repetition with the for structure 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 public class Sum { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 int sum = 0; 13 14 // sum even integers from 2 through 100 15 for ( int number = 2; number <= 100; number += 2 ) 16 sum += number; 17 18 // display results 19 JOptionPane.showMessageDialog( null, “The sum is ” + sum, 20 “Sum Even Integers from 2 to 100″, 21 JOptionPane.INFORMATION_MESSAGE ); 22 23 System.exit( 0 ); // terminate the application 24 25 } // end method main 26 27 } // end class Sum Fig. 5.5Summation with the forstructure. Fig. 5. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Leave a Reply