Java Reference
In-Depth Information
the sum of the integers 1..n (for some integer n )”.
In the table below, we give examples of ranges, giving the integers in the
range and a formula ( last-value +1- first-value ) for calculating the number of
integers in the range. The last line gives a general range with two variables: h..k .
integers in range
number of integers
5, 6, 7
7+1-5 = 3
5, 6
6+1-5 = 2
5+1-5 = 1
4+1-5 = 0
h , h+1 , …, k
Take special note of the range 5..4 , which denotes the range beginning at 5
but containing no integers. It may seem weird, but it follows the progression
given by the preceding three, and it is quite useful, mathematically speaking.
Whenever we write a range like h..k , we assume, usually without explicit-
ly saying so, that h≤k+1 , and if h=k+1 , then the range is empty. For exam-
ple, we would never write a range 5..3 or 5..2 because they do not make sense.
But 5..4 is ok: it denotes the set of no integers.
Four loopy questions
This sequence of statements prints the squares of integers in the range 2..4 :
Activity 7-1.2
covers the
same material
but with a dif-
ferent loop.
System.out.println(2 * 2);
System.out.println(3 * 3);
System.out.println(4 * 4);
Below, we write a loop that does the same thing. We think of the loop shown
below as simulating this sequence of three statements:
int i= 2;
while (i != 5) {
System.out.println(i * i);
i= i + 1;
We look for a way of commenting the loop —this particular loop is, perhaps,
simple enough that it does not require comments, but most loops do. In order to
figure out what kind of comments will help, we annotate the sequence of three
statements, showing what is true before and after each one:
Search WWH ::

Custom Search