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.

 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 += 212            total += number;                             13 14         System.out.printf("Sum is %d%n", total);15      }16   } // end class Sum

Sum is ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.