Java Reference

In-Depth Information

/*
Set
x
to the sum of the first even integers
2
,
4
,
6,
… such the sum

> 500
but the sum of one less even integer is
≤ 500
.
*/

x= 0;

for
(
int
k= 2; x <= 500; k= k + 2) {

x= x + k;

}

Here is another example. Assume
n
is at least
2
. We write a loop segment

that sets
m
to the largest divisor of
n
that is smaller than
n
. We do not declare
n

and
m
because we assume they are declared elsewhere. This loop is strange

because its repetend does nothing. Everything is done in the test of the condition

and the decrementing of
m
. Execute this loop by hand, using for
n
the value
5
, so

that you see how it works.

/*
Precondition:
n>=2
. Store in
m
the largest integer that is

less than
n
and that divides
n
.
*/

for
(m= n - 1; n % m != 0; m= m - 1} {

}

2.3.9

Self-review exercises for for-loops

After writing an exercise, test it on the computer. That is the best way to deter-

mine that your answer is correct. This usually requires you to calculate some of

the answers by hand for small values of the variables in question. Most, but not

all, of these loops require a statement that initializes a variable or two.

SR1
. Write a for-loop to print the values in the range
4..24
on the Java console

(use statement
System.out.println(…);
).

SR2
. Assume
n≥2
. Write a loop to store this value in
x
:

1*(n - 1) +2*(n-2)+3*(n-3)+ ... + (n - 1) * (n - (n - 1))

SR3
.

Given
n≥1
, write a loop that stores in
double
variable
v
the sum:

1/1+1/2+1/3+ …+1/n

What happens to the sum as
n
gets large? What would happen if
n<1
? (Try it!)

SR4
. Given
n≥1
, write a loop that stores in
double
variable
v
the sum:

1/(1*1)+1/(2*2)+1/(3*3)+ … +1/
(
n*n)

Once you have tested your loop to make sure it is right, try it for increasingly

large values of
n
. What value does the sum “converge” to as
n
gets larger?

SR5
. Given
n≥2
, write a loop to find the smallest integer that is greater than
1

and that divides
n
.

Search WWH ::

Custom Search