Java Reference
In-Depth Information
the four loopy questions. This allows you to separate your concerns . For exam-
ple, when writing the initialization, you do not worry about the loop condition or
repetend, you just ask yourself what needs to be done to truthify the invariant.
When you are finished writing the loop, test it in your IDE! That is the only way
to be sure you did it properly.
E1. Write four loops (with initialization) to store in x the product of the integers
in the range 2..10 . The postcondition R is: x is the product of 2..10 .
(a) Use this invariant P1. It was created by replacing constant 10 in R by k:
P1: 2 ≤ k ≤ 10 and x is the product of 2..k
(b) Use this invariant P2 . It was created by replacing constant 10 in R by k-1:
P2: 2 ≤ k ≤ 11 and x is the product of 2..k-1
(c) Use this invariant P3 . It was created by replacing constant 2 in R by k:
P3: 2 ≤ k ≤ 10 and x is the product of k..10
(d) Use this invariant P4 . It was created by replacing constant 2 in R by k+1:
P4: 1 ≤ k ≤ 10 and x is the product of k+1..10
E2. Write four loops (with initialization) to determine whether an integer n is
divisible by an integer in the range first..last , where first ≤ last . The
answer is stored in a boolean variable b : the postcondition R is:
R: b = " n is divisible by an integer in first..last"
(a) Use this invariant P1 , which was created by replacing last in R by k:
P1: b = first - 1 ≤ k ≤ last and
" n is divisible by an integer in first..k"
(b) Use this invariant P2 . It was created by replacing constant last in R by k-1:
P2: first ≤ k ≤ last + 1 and
b = "n is divisible by an integer in first..k-1"
(c) Use this invariant P3 . It was created by replacing constant first in R by k:
P3: first ≤ k ≤ last+1 and b = " n is divisible by an integer in k..last"
(d) Use this invariant P4 . It was created by replacing constant first in R by k+1:
P4: first-1 ≤ k ≤ last and
b = " n is divisible by an integer in k+1..last"
E3. Given is n>0 . Write a loop (with initialization) to store in k the largest
power of 2 that is at most n . Note that 2 0 =1 . The obvious way to calculate k is
to successively set k to 1 , 2 , 4 , 8 , ... until the right power of 2 is reached. Use the

Search WWH ::

Custom Search