Prelab Exercises
Section 3.6
In a while loop, execution of a set of statements (the body of
the loop) continues until the boolean expression controlling the loop
(the condition)
becomes false. As for an if statement, the condition must be
enclosed in parentheses. For example, the loop below prints the
numbers from 1 to to 100:
Loop A
final int LIMIT = 100; // setup
int count = 1;
while (count <= LIMIT) // condition
{ // body
System.out.println(count); // -- perform task
count = count + 1; // -- update condition
}
// Program continues here after loop terminates
There are three parts to a loop:
- The setup, or initialization. This comes before the
actual loop, and is where variables are initialized in preparation for
the first time through the loop.
- The condition, which is the boolean expression that
controls the loop. This expression is evaluated each time through the
loop. If it evaluates to true, the body of the loop is executed, and then
the condition is evaluated again; as soon as the condition evaluates to false (even if at the first evaluation),
the loop terminates (Java jumps to the line commented "Program continues here after loop terminates".)
- The body of the loop. The body typically needs to do two things:
- Do some work toward the task that the
loop is trying to accomplish. This
might involve printing, calculation, input and output, method calls -- this
code can be arbitrarily complex.
- Update the condition. Something has to happen inside the loop so
that the condition will eventually be false -- otherwise the loop will
go on forever (an infinite loop). This code can also
be complex, but often it simply involves
incrementing a counter or reading in a new
value.
Sometimes doing the work and updating the condition are related. For example,
in the loop above, the print statement is doing work, while the
statement that increments count is both doing work (since the loop's task
is to print the values of count) and updating the
condition (since the loop stops when count hits a certain value).
The loop above is an example of a count-controlled loop, that is, a
loop that contains a counter (a variable that increases or decreases by a fixed
value -- usually 1 -- each time through the loop) and that stops when the counter
reaches a certain value. Not all loops with counters are count-controlled; consider
the example below, which determines how many even numbers must be added together,
starting at 2, to reach or exceed a given limit.
Loop B
final int LIMIT = 16;
int count = 1;
int sum = 0;
int nextVal = 2;
while (sum < LIMIT)
{
sum = sum + nextVal;
nextVal = nextVal + 2;
count = count + 1;
}
System.out.println("Had to add together " + (count-1) + " even numbers " +
"to reach value " + LIMIT + ". Sum is " + sum);
Note that although this loop counts how many times the body is executed, the
condition does not depend on the value of count. By the way, the result of executing the above code is:
Had to add together 4 even numbers to reach 16. Sum is 20
Not all loops have counters. For example, if the task in the loop above
were simply to add together even numbers until the sum reached a certain
limit and then print the sum (as opposed to printing the number of things added
together), there would be no need for the counter.
Similarly, the loop below sums integers input by the user and prints the sum;
it contains no counter.
Loop C
int sum = 0; //setup
char keepGoing = 'y';
int nextVal;
while (keepGoing == 'y' || keepGoing == 'Y') // (Do you recall the '||' operator?)
{
System.out.print("Enter the next integer: "); //do work
nextVal = kbd.nextInt();
sum = sum + nextVal;
System.out.println("Type y or Y to keep going"); //update condition
keepGoing = kbd.nextChar();
}
System.out.println("The sum of your integers is " + sum);
Exercises
-
First, go to this web page to find out
how to handle error-laden loops in BlueJ.
- In Loop A above, the println statement comes before the value of
count is incremented. What would happen if you reversed the order of these
statements so that count was incremented before its value was printed? Would
the loop still print the same values? Explain.
- Consider the second loop, Loop B, above.
- Trace this loop; that is, in a table show values
for variables nextVal, sum and count at each iteration. As you work through the iterations by hand, update the values in the table everytime a variable's value changes. Whenever there is output, copy it into the next row in the OUTPUT column in the table.
When evaluating a line of code (such as "sum=sum+nextVal"), use the table to determine what the current value of each of the variables is to determine the effect of the code.
- Note that when the loop terminates, the number of even numbers added
together before reaching the limit is count-1, not count. How could you
modify the code so that when the loop terminates, the number of things
added together is simply count?
- Write a while loop that will print "I love computer science!!" 100 times.
Is this loop count-controlled?
- Add a counter to the third example loop, Loop C, above (the one that reads and sums
integers input by the user). After the loop, print the number of integers
read as well as the sum. Just note your changes on the example code. Is your
loop now count-controlled?
- The code below is supposed to print the integers from 10 to 1 backwards.
What is wrong with it? (Hint: there are two problems!) Correct the code so
it does the right thing.
count = 10;
while (count >= 0)
{
System.out.println(count);
count = count + 1;
}