Activity 5.1.1.
Here is a while loop that counts from 1 to 5 that demonstrates the 3 steps of writing a loop. Can you change it to count from 2 to 10?
while
and for
. Of the two the while
loop is simpler, with fewer moving parts so weβll talk about it first. The for
loop, which weβll discuss in the next section is actually the one youβll use most of the time as it has some amenities to make it easier to express common looping patterns.
while
statement looks a lot like an if
statement, as you can see in the two listings below:
if
statement, when the flow of control reaches a while
loop, the first thing that happens is the condition, which must be a boolean
expression, is evaluated. If it true, then the body of the loop runs. However, when control reaches the end of the body, it loops back around to the top of the loop and evaluates the condition again, and runs the body again if the condition is true, and so on. When the condition is false, the body is skipped, just like in an if
statement when its condition is false.
if
statement and a while
loop is that the body of the if
statement runs either zero or one times, whereas the body of the while
loop runs zero or many times.
while
loop. Follow the arrows in this diagram to see when the condition is checked versus when the body is executed.
while
Loopwhile
loops: it loops until the condition is true where a while
loop loops until its condition is false.
x
is 100 would need to be written in Java with a while
loop that runs as long as x
is not yet 100, which can be written as x < 100
.
repeat until
loop to Java while
loopwhile
loop. They are labeled in FigureΒ 5.1.5.
while
loop)int count = 0;
/* missing loop header */ {
System.out.print(count + " ");
count += 2;
}
int count = 1;
while (count <= 10) {
count *= 2;
}
count = count - 10;
int x = -5;
while (x < 0) {
x++;
System.out.print(x + " ");
}
while
is to accidentally create an infinite loop. An infinite loop runs forever because condition never becomes false. If we create an infinite loop by accident, our program may seem to get stuck. For an example, look at the following loop. It looks a lot like the loops earlier in this chapter but it is actually an infinite loop. Can you see why?
int i = 0;
while (i < 10) {
System.out.println(i);
}
while
loopβis that although it includes steps 1 and 2 (initializing the loop variable and testing it) it forgot step 3 and never changes the loop variable. The loop variable, i
, starts at 0
and the loop loops as long as i < 10
which will always be true because thereβs no code in the loop that changes i
. The simple fix is to add a line that increments i
:
int i = 0;
while (i < 10) {
System.out.println(i);
i++; // This fixes it!
}
while (true)
is a clear sign that this was intended to be an infinite loop.
while (true) {
if (tooHot()) {
turnOnFurnace();
} else {
turnOffFurnace();
}
}
int i = 10;
while (i < 10){ // This loop will never run!
System.out.println(i);
i++;
}
<=
when it should have been <
or vice versa.
while
loop should print out the numbers from 1 to 8, but it has two bugs. One causes an infinite loop. And the other an off-by-one error. Can you fix the bugs? Try to fix the infinite loop bug first since otherwise youβll just get an error abut the code taking too long to run.
while
loop as a counting loop to repeat the body of the loop a certain number of times, weβll see in the next section that thatβs more easily done with a for
loop. A while
loop is more typically used when we donβt know how many times the loop will need to executeβwhen the condition will eventually become false but it might be after a few iterations or a lot and the only way to find out is to execute the loop.
while
loop stops when the user types βByeβ.
Scanner in = new Scanner(System.in);
String statement = in.nextLine();
while (!statement.equals("Bye")) {
System.out.println(getResponse(statement));
statement = in.nextLine();
}
String
not a number. And the condition, statement.equals("Bye")
is how we test whether that String
is a particular value, "Bye"
. (More on this in the ChapterΒ 9Β Objects). A special value, like "Bye
, that is the sign to stop the loop is called a sentinel value for the loop.
"Bye"
as the very first thing.
// The statements in a while loop run zero or more times,
// determined by how many times the condition is true
int count = 0; // initialize the loop variable
while (count < 10) // test the loop variable
{
// repeat this code
// update the loop variable
count++;
}
int n = 35;
int result = 1;
while (n > 0)
{
int d = n % 10;
result *= d;
n /= 10;
}
System.out.println(result);
int count = 0;
/* missing loop header */
{
if (count % 2 == 0)
{
System.out.println(count);
}
count++;
}