Professional Documents
Culture Documents
The While Loop Do-While Loops: Opics Overed
The While Loop Do-While Loops: Opics Overed
The While Loop Do-While Loops: Opics Overed
T H I N G S T O D O F I R S T
Read over chapters 4.1 to 4.3
Try programming questions 4.3 to 4.5 on page 129.
T H I N G S T O D O L A T E R
Review your notes from today's class:
o What is an "endless loop"?
o How is a while loop different from a do-while loop?
T H E W H I L E L O O P
Chapter 4.2 introduces you to the while loop. This is a pre-test loop, or
top-checking loop. This means that the test to determine whether or not
the loop should continue is at the top of the loop. Alternatively, the test
condition can go at the bottom of the loop, as we'll see later. The general
format of a while loop can be found on page 104. Note that if you have more
than one statement in the body of your loop, you will need to enclose the
statements in braces:
while (loop-continuation-condition)
{
// statement 1
// statement 2
// etc...
}
int count = 1;
while (count <= 4) {
System.out.println(count + ": Hello!");
count++;
}
System.out.println(count + ": Done!")
1: Hello!
2: Hello!
3: Hello!
4: Hello!
5: Done!
Note that the loop iterates 4 times for the values 1, 2, 3, and 4 of the count
variable. Inside the last iteration, the variable gets incremented to 5. At this
point, the loop condition (count <= 4) evalutates to false and the loop
terminates. Then the last print statement executes; it prints the value of
count followed by ": Done!".
See Figure 4.1 on page 104 to see a diagram of how the while loop works.
Notice that the condtion is tested at the top of the loop. This implies that a
while loop's code block might never execute, as in this example:
int x = 5;
while (x < 5)
{
System.out.println(x);
x--;
}
Since x starts with a value of 5, the while loop's condition is false as soon as
the loop begins, so the code block is never entered.
Keep in mind that the condition on a while loop specifies the conditions
under which the loop continues. The loop continues as long as the
condition remains true; in other words, the loop terminates when the
condition is false.
Exercises
In this code, the program first retrieves the number to count up to from the
user. Next, a counter variable is initialized to 1. We need this counter to do
the actual counting. We can't use the number variable, because we need
that to store the number we want to count up to.
Next, the while loop condition states that the loop should continue as long as
the value of the counter remains less than or equal to the value of the
number variable. As long as this condition stays true, the body of the loop
will execute repeatedly.
The body of the loop contains two statements - one that prints the value of
the counter, and one that adds one to the counter. We need to increment
the counter variable, otherwise the counter will always stay at its initial
value and never change! This would result in an endless loop (a loop that
never terminates).
Let's see what happens in our code if the user a value of 4. For the first
iteration of the loop, the counter variable has a value of 1. When the loop
condition is evaluated (is counter <= number?). Since the counter is 1 and
the value of number is 4, this statement is true. The flow of execution moves
inside the loop. The print statement is executed (displaying the value of
counter (1) on the screen followed by a space). Then the counter is
incremented; after this statement is done, the counter has a value of 2.
Once the body of the loop is finished executing, the flow of execution goes
back up to the loop condition. The condition is evaluated again: is counter
<= number? This statement is true, since counter is 2 and number is 4. The
body of the loop is executed again, causing the value of 2 to be printed on
the screen, and the counter to be incremented to a new value of 3.
The trace chart below shows the rest of the variable values and the output of
this code.
The key thing to note as you look at the results is that the counter variable
does actually get incremented one last time before the loop condition is
false. The counter gets incremented to 5 after the value 4 is printed (which
is the highest value the user wanted to count to). The loop condition still has
to be checked, however. Just because the counter has been assigned a value
of 5 doesn't mean the program knows to end the loop! The loop condition
must first be evaluated - this is how the computer knows when to end the
loop. When the condition is determined to be false, then the flow of
execution can move down to the statement after the loop.
2. b. How would you modify this program so that the output appears instead
as:
1
2
3
4
Done!
int counter = 1;
int sum = 0;
while (counter <= 5)
sum += counter++;
System.out.println(sum);
5. a. Write a loop that prints the numbers from 1 to 10 with their squares,
like this:
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
5. b. How would you make the loop do the same output backwards (from 10
to 1)?
2 4 6 8 10 12 14 16 18 20
D O - W H I L E L O O P S
Do-While loops are covered in chapter 4.3.
If we asked the user for a positive number, and they accidentally enter an
invalid value, how could we write a loop to keep asking for the number until
they enter it correctly?
You might first decide to prompt and get the value from the user:
Then we need to perform some kind of validation. What is the action we are
trying to perform? We want to ask the user for a number again, but only as
long as the number is invalid. What condition evaluates whether or not the
number is invalid? We need to put this in a While loop:
It turns out we've repeated the print and get statements! Is there an easier
way we could have done this? One way would be to initialize the number
variable to 0 instead of asking for and getting the number from the user
before the loop:
int number = 0;
while (number <= 0) {
System.out.print("Enter a positive number:");
number = keysIn.nextInt();
}
This works fine, and in some situations it might look a little awkward, but it
works. However, there's another way - use a bottom-checking loop. In Java,
this is generally referred to as a "do-loop". The syntax for a do-loop can be
found on the bottom of page 100. Watch this syntax carefully - note the
semi-colon after the while condition. Our number-validation code, with an
extra statement to display the root of the number, could be written in Java
as:
int number = 0;
do
{
System.out.print("Enter a positive number:");
number = keysIn.nextInt();
}
while (number <= 0);
System.out.println("Root: " + Math.sqrt(number));
A flowchart on page 111 shows how the do-loop works. How is this chart
different from the while-loop chart on page 104?
Exercises
2. b. Modify the above program so that the user can cancel by entering the
value 999.
2. c. Modify the program in 1. a. so that the user has only 5 tries to enter
the grade. After 5 tries, the program terminates.
You don't know how many test results they'll enter, so after each result is
entered, prompt the user with a confirm dialog (e.g. "Would you like to enter
another test result?" Yes/No buttons). Continue recording test results until
the user clicks NO on the confirm dialog.