The While Loop Do-While Loops: Opics Overed

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

T O P I C S C O V E R E D :

 The While Loop


 Do-While Loops

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...
}

In a while-loop, the loop-continuation-condition is a valid condition that


evaluates to true or false. As long as this condition evaulates to true, the
loop's body will execute. When the loop condition becomes false, the loop
will terminate, and program flow to move to any statements that appear
after the loop. For example, the loop below iterates 4 times:

int count = 1;
while (count <= 4) {
System.out.println(count + ": Hello!");
count++;
}
System.out.println(count + ": Done!")

The output of this loop would be:

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

1. When do each of these loops terminate?

a. while (recCount != 10)


b. while (userInput.equals(""))
c. while (x >= 5)
d. while (x < 5)
e. while ( (x < 5) && (y > 10) )

2. a. What do you think is the output of this loop?

System.out.print("Enter a value to count to:");


int number = keysIn.nextInt();
int counter = 1;
while (counter <= number) {
System.out.print(counter + " ");
counter++;
}
System.out.println("\nDone!");

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.

Eventually at some point, when the incrementing statement executes, the


counter will be incremented to the value of 4. When control moves back up
to the while-loop condition, the condition will evaluate to true (counter <= 4
is still true when counter has a value of 4). The body of the loop will
execute one more time: The value of counter (4) will be printed and the
counter will then be incremented to 5.

After the counter is incremented to 5, control moves back up to the while-


loop condition. At this point, the condition counter <= 4 is false, since
counter is 5, and the value 5 is not less than or equal to 4. The loop
terminates and control moves to the print statement that appears after the
loop. This statement prints the value "Done!" on the screen and the program
is finished.

The trace chart below shows the rest of the variable values and the output of
this code.

Value Value counter


Statement Output
of of <=
Executed Shown
counter number number?
System.out.print("Enter a value
       
to count to:");
int number = keysIn.nextInt();   4    
int counter = 1; 1      
while (counter <= number) {     true  
System.out.print(counter + " ");       1
counter++; 2      
while (counter <= number) {     true  
System.out.print(counter + " ");       12
counter++; 3      
while (counter <= number) {     true  
System.out.print(counter + " ");       123
counter++; 4      
while (counter <= number) {     true  
System.out.print(counter + " ");       1234
counter++; 5      
while (counter <= number) {     false  
1234
System.out.println("\nDone!");      
Done!

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!

3. What is the output of the following code segment?

int counter = 1;
int sum = 0;
while (counter <= 5)
sum += counter++;
System.out.println(sum);

4. What's wrong with the following program?

public class LoopProblem


{
public static void main(String[] args)
{
// print from 1 to 10 by 2's
int counter = 1;
while (counter != 10)
{
System.out.println(counter);
counter += 2;
}
}
}

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)?

6. Write a while loop that counts from 1 to 20 by 2's on one line:

2 4 6 8 10 12 14 16 18 20

7. What is the output of each of the following loops?

Example 1: Example 2: Example 3:


int count = 4; int count = 1; int count = 3;
while (count > while (count < while (count <=
0) 5) 1)
{ { {

System.out.print System.out.print System.out.print


ln(count); ln(count); ln(count);
count--; count++; count++;
} } }
Example 6:
int x = 1, y =
Example 4: 3;
int count = 3; Example 5: while (x < 5 ||
while (count >= int count = 9; y > 0)
1) while (count <= {
{ 10 && count > 4)
{ System.out.print
System.out.print ln(x++ +
ln(count); System.out.print ", " +
count--; ln(count); --y);
} count--; }
System.out.print } System.out.print
ln(count); ("x: " + x);
System.out.print
ln(" y:" + y);

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:

System.out.print("Enter a positive number:");


int number = keysIn.nextInt();

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:

System.out.print("Enter a positive number:");


int number = keysIn.nextInt();
while (number <= 0) {
System.out.print("Enter a positive number:");
number = keysIn.nextInt();
}

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?

A do-loop is often referred to as a post-test loop or bottom-checking


loopbecause the condition that checks for loop continuation is at the bottom
of the loop, instead of the top.

Exercises

1. What's the output of each of the following code segments:


Example 3:
Example 2: int count = 9;
Example 1:
int count = 9; do
int count = 4;
do {
do
{
{ System.out.print
System.out.print ln(count);
System.out.print
ln(count); count--;
ln(count);
count--; } while (count
count--;
} while (count <= 10 && count >
} while (count >
<= 10 && count > 4);
0);
4); System.out.print
ln(count);

2. a. Write a program that requests a final grade. Use a do-loop to request


the grade continuously as long as the grade entered is invalid. A grade is
invalid if it is less than 0 or greater than 100. After a valid grade is entered,
display it on the screen.

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.

3. For this program, use either a while-loop or a do-loop, whichever you


think is most efficient. Write a program that records scientific test results
(they'll have decimal values) from the user via a dialog box. As each test
result is entered, add it to a total. After all the test results have been
entered, display the total.

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.

You might also like