Homework: Iteration


  1. (This is from Review Exercise R4.1 at the end of Chapter 4 of Java for Everyone.) Assume variables SimpleWriter out and int n are already declared in each case. Write a separate while loop for each of the following tasks:
    1. Print all squares less than n. For example, if n is 100, print 0 1 4 9 16 25 36 49 64 81.
    2. Print all positive numbers that are divisible by 10 and less than n. For example, if n is 100, print 10 20 30 40 50 60 70 80 90.
    3. Print all powers of two less than n. For example, if n is 100, print 1 2 4 8 16 32 64.
  2. (The first four of these are from Review Exercise R4.3 at the end of Chapter 4 of Java for Everyone). Using the kind of tracing tables discussed in Writing and Tracing Loops, provide tracing tables for these loops:
  3. (This is from Review Exercise R4.15 at the end of Chapter 4 of Java for Everyone.) Rewrite the following for loop into a while loop.
  4. Given variables int n and double pi, write a snippet of code that assigns to pi the approximation of π resulting from adding the first n terms in the Gregory-Leibniz series:
    `pi=4sum_(i=0)^infty (-1)^i/(2i+1)=4(1/1-1/3+1/5-1/7+...)`
  5. Given variables int areaBound and int sum, write a snippet of code that assigns to sum the result of adding up all integers of the form n2 + m2 where:

Additional Questions

  1. Modify the loop to approximate pi with the Gregory-Leibniz series so that, instead of adding a given number of terms, it keeps adding terms until the difference between two consecutive estimates is less than some predefined tolerance, say double epsilon = 0.0001.