Вы находитесь на странице: 1из 16

PROG10082 – Object Oriented Programming 1 - Java

Session 5.2 Topics


The While Loop

Chapter 5.1 explains why loops are important to programming. Make sure you read
this section and understand it, as it is the foundation of what you will be learning
in the next few classes.

Chapter 5.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 at the start of Chapter 5.2. 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 evaluates 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:

public class BasicLoop {

public static void main(String[] args) {

int count = 1;

while (count <= 4) {

System.out.println(count + ": Hello!");


PROG10082 – Object Oriented Programming 1 – Java Winter 2018

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) evaluates to false and the loop terminates. Then the last
print statement executes; it prints the value of count followed by ": Done!".

Notice that the condition is tested at the top of the loop. This implies that a while
loop's code block might never execute, as in this example:

public class NeverExecutes {

public static void main(String[] args) {

int x = 5;

while (x < 5) {

System.out.println(x);

x--;

-2-
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

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. For what values 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 if the user enters the value 4?

import java.util.Scanner;

public class LoopThis {

public static void main(String[] args) {

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

int number = keysIn.nextInt();

int counter = 1;

-3-
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

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

So what happens 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.

-4-
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

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 ofcounter (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.

Statement Value Value counter Output


Executed of of <= 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

-5-
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

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

System.out.println("\nDone!"); 1234
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:

-6-
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

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

-7-
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

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 3:
Example 2:
int count = 3;
int count = 1;
int count = 4; while (count <=
while (count < 5)
while (count > 0) { 1)
{ {
System.out.printl
System.out.printl n(count); System.out.printl
n(count); n(count);
count++;
count--; count++;
}
} }
Example 4: Example 5: Example 6:
int count = 3; int count = 9; int x = 1, y = 3;
while (count >= while (count <= while (x < 5 || y
1) 10 && count > 4) > 0)
{ { {

System.out.printl System.out.printl System.out.printl


n(count); n(count); n(x++ +
count--; count--; ", " + --y);
} } }

-8-
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

System.out.printl System.out.print(
n(count); "x: " + x);
System.out.printl
n(" y:" + y);

Do-While Loops
Do-While loops are covered in chapter 5.6.

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.

You can see the general form of a do-while loop at the top of Chapter 5.6. Note the
syntax carefully - there is a semi-colon after the while condition. This is because the
braces of a do-while loop enclose the loop body, but not the while clause in the
loop. Since the while clause appears after the closing brace, it requires a line-
terminator (semi-colon) so that Java knows where the end of the while statement
is.

See Figure 5.2 in Chapter 5.6 and try the animation (click the (b) button) to see how
the do-while loop works. How is this chart different from the while-loop flowchart
in Figure 5.1/Chapter 5.2?

The key difference is that a while loop, a top-checking or pre-test loop, checks the
condition of the loop before executing the loop body. The do-while loop, a bottom-
checking or post-test loop, checks the condition of the loop after executing the
loop body.

What does this mean? It means that the body of a while loop might never execute,
whereas the body of a do-while loop is always guaranteed to execute at least once.
See the following examples:

Example A: a while loop

What is the output of the following program?

public class LoopProblem {

public static void main(String[] args) {

-9-
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

int counter = 1;

while (counter > 1) {

System.out.println(counter);

counter--;

In the program above, we first initialize counter to 1. Then we begin the loop: check
the condition counter >= 1. The condition is false, because counter is 1, and 1 is not
>= 1, so the loop ends right away and no output is printed.

Example B: a do-while loop

What is the output of the following program?

public class LoopProblem {

public static void main(String[] args) {

int counter = 1;

do {

System.out.println(counter);

counter--;

} while (counter > 1);

- 10 -
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

First, we encounter the do keyword, which indicates we are about to enter a


bottom-checking while loop.

The body of the loop prints the current value of counter (1) and then decrements
counter. The counter variable now has a value of 0. The body of the loop has
finished executing and now we move to the while and check our condition.

counter >= 1 is false, because counter (0) is not >= 1. So the loop now terminates,
and the output of this program was just "1".

We can clearly see that these loops are the same, except that one checks the
condition at the top and one checks the condition at the bottom. In both loops, the
condition counter >= 1 was false the first time it was checked however, because
the while loop checks the condition before the loop body is executed, the body of
the loop never executes. Because the do-while loop checks the same condition
after the loop body is executed, the body of the loop executes once before it is
determined that the condition is false.

This summarizes what we said about the difference between pre-test loops and
post-test loops: The body of a pre-test loop might never execute if the condition is
false right away, whereas the body of a post-test loop is always guaranteed to
execute at least once.

Exercises

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

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

- 11 -
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

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. a. 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. 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 question such as "Would you like to enter another test
result? (Y/N)". The user can answer "Yes" or "No" too this question, or even just "Y"
or "N". To capture this, we would use the Scanner's next() method to grab only the
first word of the user input:

String answer = in.next();

However, we can make this program more efficient if we use a character value
instead of a string, and just compare the first letter of the user's input (Y or N).
There is a method in the String class called charAt(index). You give charAt() a string
index (the position number, where the first character is position 0, the second
position 1, etc) of the character you'd like to have and it will return that character
at the specified index as a char value. For example:

"hello".charAt(0) // returns 'h'


"hello".charAt(1) // returns 'e'
"hello".charAt(2) // returns 'l'
"hello".charAt(4) // returns 'o'
"hello".charAt(5) // would give an error because there
is no index 5

- 12 -
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

So since we only what the first character that the user types, we can use:

char keepGoing = 'Y'; // initialize to yes


... // code code code
keepGoing = in.next().charAt(0);

Next, we want to see if the user says 'Y' to our prompt, meaning they'd like to enter
another test result. So our loop condition could be something like keepGoing == 'y'
|| keepGoing == 'Y' because we don't know if the user will type an upper-case or a
lower-case answer. If you prefer, you can use one of the String class's methods
toUpperCase() or toLowerCase() to convert the user's answer to upper- or lower-
case, and then compare. For example, I will use upper-case comparisons:

keepGoing = in.next().toUpperCase().charAt(0);

Then my loop condition would be keepGoing == 'Y'.

Add this functionality to your program, so your user can enter as many test
results as they'd like.

Counted Loops (For Loop)

A lot of loops, like the ones we've already worked with, are counted loops. This
means that they have a definite number of iterations. In our first example, we
counted until we reached the value specified by the user. We knew there would be
a definite number of iterations. In our second example, our number of iterations
depended on how many times it would take the user to enter a valid number. In
this case, there is an indefinite or undetermined number of iterations because we
don't know how many tries the user would need. The same would apply if you were
using a loop to process a file - you can never know how many records are in a file
at any given time, so you can't determine the number of iterations of a loop that
processes a file.

We often use while-loops or do-loops to perform an indefinite loop, or a loop


where we can't determine the number of iterations. When we do know that there
will always be a definite number of iterations, such as a loop that counts until it
reaches a specific value, we can use a special counted loop. In Java, and a number
of other programming languages, this is called a for-loop. The syntax for a for-loop

- 13 -
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

can be found in chapter 5.7 of your text, and the flowcharts in Figure 5.3 in chapter
5.7 show how a for-loop works.

The for-loop performs some of the tasks that you have to code for yourself in a
while-loop or a do-loop. These include:

1. initialization of the counter variable


2. evaluation of a condition
3. incrementing, or other expression that keeps the loop going

Using our counting example discussed in the beginning of this session, we can
determine that our loop starts at 1, continues until it reaches the user-specified
value, and increments by 1. In a for-loop in Java, this would be written as:

public class ForLoopExample {

public static void main(String[] args) {

Scanner in = new Scanner();

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

int number = in.nextInt();

for (int counter=1; counter <= number; counter++) {

System.out.println(counter);

In this loop, the three tasks are specified inside the brackets and separated by
semicolons:

- 14 -
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

• initialization: int counter = 1;


o counter is initialized or starts at a value of 1
o we are also declaring the counter in this statement: this is allowed, but only if
the counter is no used outside the loop since the counter is local to the loop
block
• condition evaluation: counter <= number;
o this loop will continue as long as this condition is true
o when the condition is false, the loop terminates
• increment: counter++;
o this statement increases the counter by 1
o this increment takes place after the body of the loop executes and before the
condition is evaluated again

If you type this code into a Java program, you'll see that it executes exactly the
same way as the first While example! The difference is that the For-Loop is made
up of fewer statements.

As with other loops, if you have more than one statement inside the body of the
loop, you must have braces surrounding the statements to be repeated.

Exercises

How would you make the for-loop in the previous example count backwards? Do
it!

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

a.

int i;
for (i=0; i<5; i++)
{
System.out.print(i + ", ");
}
System.out.println("\nAfter the loop, i is " + i);

b. >

- 15 -
PROG10082 – Object Oriented Programming 1 – Java Winter 2018

for (int i=0; i<=20; i+=4) {


System.out.print(i + " ");
}

c.

for (int i=1; i<=21; i+=3) {


System.out.print(i + " ");
}

d.

for (int i=20; i>=0; i-=4) {


System.out.print(i + " ");
}

2. Write a program that converts Fahrenheit to Celsius temperatures. The starting


value and ending value of Fahrenheit temperatures to convert are to be retrieved
from the user. Celsius = (5.0 / 9.0) * (Fahrenheit - 32). Use a for-loop.

3. Investment Problem: Have the user input an investment amount and an interest
rate. Have the program use a for-loop to output a list showing the value of the
investment at the end of each year for 5 years. For example:

Enter the investment amount: 1000


Enter the interest rate: 10
After year 1: $1100.00
After year 2: $1210.00
After year 3: $1331.00
After year 4: $1464.10
After year 5: $1610.51

For more practice, try questions 5.2, 5.4, and 5.6 at the end of Chapter 5.

- 16 -

Вам также может понравиться