Homework: Iteration
-
(This is from Review Exercise R4.1 at the end of Chapter 4 of Java for Everyone.) Assume variables
SimpleWriter outandint nare already declared in each case. Write a separatewhileloop for each of the following tasks:- Print all squares less than
n. For example, ifnis 100, print 0 1 4 9 16 25 36 49 64 81. - Print all positive numbers that are divisible by 10 and less
than
n. For example, ifnis 100, print 10 20 30 40 50 60 70 80 90. - Print all powers of two less than
n. For example, ifnis 100, print 1 2 4 8 16 32 64.
- Print all squares less than
-
(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:
-
int i = 0, j = 10, n = 0; while (i < j) { i++; j--; n++; } -
int i = 0, j = 0, n = 0; while (i < 10) { i++; n = n + i + j; j++; } -
int i = 10, j = 0, n = 0; while (i > 0) { i--; j++; n = n + i - j; } -
int i = 0, j = 10, n = 0; while (i != j) { i = i + 2; j = j - 2; n++; } -
int i = 3, j = 4, n = 0; while (i != 0) { n += j; i--; }
-
-
(This is from Review Exercise R4.15 at the end of Chapter 4 of Java for Everyone.) Rewrite the following
forloop into awhileloop.int s = 0; for (int i = 1; i <= 10; i++) { s = s + i; } -
Given variables
int nanddouble pi, write a snippet of code that assigns topithe approximation of π resulting from adding the firstnterms in the Gregory-Leibniz series:`pi=4sum_(i=0)^infty (-1)^i/(2i+1)=4(1/1-1/3+1/5-1/7+...)`
-
Given variables
int areaBoundandint sum, write a snippet of code that assigns tosumthe result of adding up all integers of the form `n^2 + m^2` where:- both `n` and `m` are at least 1, and
- `n^2 < areaBound`, and
- `m^2 < areaBound`.
Additional Questions
- Modify the loop to approximate
piwith 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, saydouble epsilon = 0.0001.