Application: Summing the Even Integers from 2 to 20
We now consider two sample applications that demonstrate simple uses of for. The application in Fig. 5.5 uses a for statement to sum the even integers from 2 to 20 and store the result in an int variable called total.
Click here to view code image
1 // Fig. 5.5: Sum.java 2 // Summing integers with the for statement. 3
4 public class Sum
5 {
6 public static void main(String[] args)
7 {
8 int total = 0; 9
10 // total even integers from 2 through 2011 for (int number = 2; number <= 20; number += 2) 12 total += number; 13
14 System.out.printf(
"Sum is %d%n", total);
15 }
16 }
// end class Sum