
Lab 08. CS1110 Spring 2009. Practice with assertions and loops
Goal of this lab
Practice with assertions and with loops that process a range of integers. Part of this lab is to be done on paper.
1. Question on ranges:
How many values are in the following ranges? The last one requires a formula in terms of h and k. Remember: in the
notation h..k, we require k ≥ h–1. For example, 5..4 is OK but 5..3 is not allowed.
(a) 5..6 (d) h..h
(b) 5..5 (e) h..h–1
(c) 5..4 (f) h..k
2. Each line below asks you to write an assignment statement. We did the first one for you.
Range Want Assignment statement
(a) h..k Assign to k so that the range has 1 element: k= h;
(b) h..k Assign to h so that the range has 1 element:
(c) h..k Assign to k so that the range has 0 elements:
(d) h..k Assign to h so that the range has 0 elements:
(e) 0..n–1 Assign to n so that the range has 1 element:
(f) 0..n–1 Assign to n so that the range has 0 elements:
(g) h–1..10 Assign to h so that the range has 1 element:
(h) h+1..10 Assign to h to that the range has 0 elements:
3. Each line below contains an assertion P that is guaranteed to be true. Each line also contains an assertion R, which
we would like to be true. In the righthand column, put a Boolean expression that, when true, allows us to conclude
that R is true. We have filled in the first one for you.
KNOW P: WANT R: Additional info needed
(a) x is the sum of 1..n x is the sum of 1..100 n == 100
(b) x is the sum of 1..(n–1) x is the sum of 1..100
(c) x is the smallest char in s[0..k–1] x is the smallest char in s[0..s.length()–1]
(d) x is the no. of blanks in s[0..k–1] x is the no. of blanks in s[0..]
(e) x is the smallest char in s[h..] x is the smallest char in s[0..]
(f) x is the product of k..n x is the product of 1..n
(g) b = “no element of h..k divides x” b = “no element of m..k divides x”
4. Below is a precondition P, an assignment to a variable, and the same assertion P as a postcondition. At the place
indicated, place a statement so that if P is true initially, it will be true afterward (as indicated). The statement can be
in English, if you are not sure how to write it in Java, but make it a command to do something. In the exercises
below, v is a Vector, and you can assume that its elements are of class Integer.
(a) // {P: x is the sum of 1..n} (b) // { P: x is the sum of h..100 }
// Put a statement here: // Put a statement here:
n= n+1; h= h – 1;
// { P: x is the sum of 1..n } // { P: x is the sum of h..100 }
1