4.5 Comparing Loop Structures
With three loop structures available in Java, how do we decide which to
use in a given situation? To some extent, this is a matter of personal taste,
but usually one of the statements is more appropriate than either of the
others.
The for statement should usually be used if we know, before we start
the loop, how many repetitions we want. Problems that call for the reading
of a given number of data items or the production of a table of a given size
are examples of situations where we would normally use a for statement.
The while and do statements should normally be used when the number
of repetitions is not known before we start execution of the loop. If it
is convenient to test the condition that controls the loop before entry to
the loop body, then a while is the usual choice. If the condition is only
established within the body, then a do should be used. If it is possible that
the loop body may never be entered, a while statement should be used; if
it is certain that the loop body will be executed at least once, then a do
might be the better choice.
Example 1
All three program fragments shown here have the same effect. They all
find the sum of the series
In each part, the variable sum is of type double while i is of type int.
- sum = 0;
i = 1;
while (i <= 5)
{
sum += 1.0/i;
i++;
}
- sum = i = 0;
do
{
i++;
sum += 1.0/i;
}
while (i < 5);
- for (sum = 0, i = 1; i <= 5; i++)
sum += 1.0/i;
The solution using a for statement is the shortest and clearest. |
|
We have suggested that counted loops use for statements while conditional
loops use while or do statements. Sometimes, however, loops have
both of these elements. For these situations, the choice of structure is very
often a matter of personal preference.
Example 2
As part of a program to generate report cards, one segment is required
to read and total the marks. Most students take MAX_SUBJECTS subjects
and input for them consists of that many marks. Some students take fewer
subjects. Input for them consists of their marks followed by a sentinel value
of -l.
In this problem, the number of repetitions of the loop is sometimes
simply counted (for students taking the maximum number of subjects) but
sometimes conditional (for students with fewer subjects). The segment
shown below will give the correct values for totalMarks and numberOfMarks for input of either form. We have solved the problem with a do but
other solutions are possible.
totalMarks = numberOfMarks = 0;
do
{
System.out.println("Next mark please");
mark = In.getInt();
if (mark != -1)
{
totalMarks += mark;
numberOfMarks++;
}
}
while (mark != -1 && numberOfMarks < MAX_SUBJECTS);
|
|
Exercise 4.5
- Describe what the fragment does and then rewrite it using a for
statement.
- count = 1;
while (count < 10)
{
System.out.println(count+" "+Math.sqrt(count));
count++;
}
- i = 5;
do
{
i--;
System.out.println(Math.pow(i,3));
}
while (i > 0);
- Describe what the fragment does and then rewrite it using a while
statement.
- for (i = 0; i < 10; i++)
{
x = 2 * i - 10;
y = Math.abs(x / 5 - 2);
System.out.println (x + " " + y);
}
- product = 1;
do
{
System.out.println("Next value please");
next = In.getInt();
if (next != TERMINATOR)
product *= next;
}
while (next != TERMINATOR);
- Describe what the fragment does and then rewrite it using a do statement.
- System.out.println("Enter a value - zero to stop");
value = Math.abs(In.getInt());
biggest = value;
while (value != 0)
{
if (value > biggest)
biggest = value;
System.out.println("Enter a value (0 to stop)");
value = Math.abs(In.getInt());
}
- for (i = 0; i == 0; )
{
System.out.println("Continue? (Y/N)");
response = In.getChar();
if (response == 'Y' || response == 'N')
i = 1;
}
- State, with reasons, which loop structure you think would be most
appropriate for solving each problem. Do not actually solve the problem.
- Find the sum of the cubes of the numbers from 1 to 100.
- Repeatedly prompt a user for a password, rejecting any submissions
until the correct password has been provided.
- Read and sum positive integers until a sentinel value of -1 is
read.
- Determine the number of times that a positive integer can be
divided by two.
- Find the amount to which $1 will grow in ten years at a rate of
8%.
| |