/* T01n10.java -- This program computes the sum 1 + 0.5 + 0.25 + 0.125 + ... * Notice that, after 25 terms are summed, the sum is * reported to be exactly 2. This is nonsense, mathematically speaking. * The sum is merely very close to 2, and the precision of the float * is too limited to show how close. * * The real point of this example is to demonstrate the FOR loop. This is * a counter-controlled loop situation (the value of termNum, which is * counting the number of iterations, is being used to determine when * we have completed enough work), and FOR loops are typically used for * such tasks. We could have used a WHILE without any trouble, though; * if you have some time, you might try rewriting the FOR loop as a WHILE * loop, to help you understand their relationship. */ public class T01n10 { public static void main (String [] args) { final int NUM_TERMS = 25; // Quantity of fractions to sum int termNum = 1; // identifier of the term currently considered float sum = 0, // the running total of the fractions divisor = 1; // denominator of current term; a power of 2 /* Note that in the following for loop, the initialization * is empty. We could have put the preceding initializations * in there if we wished; in fact, that would be more * in keeping with standard coding style. But, it would * have made the for line really, really long; and it gives * me the opportunity to show that the first component can * be empty. */ for ( ; termNum <= NUM_TERMS; termNum++, divisor *= 2) { sum += 1.0 / divisor; System.out.println("After adding term " + termNum + ", the sum is " + sum + "."); } } }