To use a
while loop, we first need to determine a way to control how many times the
loop executes (the number of iterations).
For that we will condition the execution of the loop on the value of a
variable. The number of loop
iterations is controlled by the initial value of the variable, its final
value, and how its value changes at every iteration. As an example, suppose we’d like to have a println statement execute 5 times.
We will declare a variable, say i, before the loop and give it an initial value of 0. The next thing we have to decide is how i’s value is updated. The
simplest thing is to increment it by 1.
This means that in order to have the loop execute 5 times, the logical
condition must be that variable i is less than 5 (or less than or equal to 4). In code, this is what we would have: int i
= 0; while (i < 5) //
iterate as long as i is less than 5 { System.out.println(“This will be printed 5 times.”); i = i + 1; // add 1 to i } The code’s
output would be: This will be printed 5
times. This will be printed 5
times. This will be printed 5
times. This will be printed 5 times.
This will be printed 5
times. We quickly
come to the realization that we could have accomplished the same thing by
initializing i to a value
other than 0. This is as long as the
number of updates we make to i before the condition becomes false corresponds to the number
of times we’d like to repeat the execution of the body of the loop. Take a look at this code segment: int i
= 10; while (i < 20) { System.out.println(“This will be printed 5 times.”); i = i + 2; } Here, the
values that i take on
before the loop ends are: 10, 12, 14, 16, and 18. For each of these values the println statement executes.
Essentially, the output will be identical to the first code
segment. It may be
useful to print out the value of i inside the body
of the loop to be convinced: int i
= 10; while (i < 20) { System.out.println(“i is ” + i); i = i + 2; } Increment
and decrement operators On a side
note, since adding or subtracting 1 from the value of a variable are such
common operations, Java provides two shorthand operators to accomplish this –
postincrement and postdecrement. The operators are represented by ++ (two
pluses) and -- (two minuses) and are placed after the variable. So instead of i = i
+ 1; we can write i++; and instead of i = i
– 1; we can write i--; Common
pitfall Beware!
Placing a semicolon after the parentheses of a while loop may cause it to
execute forever (what we call an infinite loop). Java interprets such code as: so long as
the condition is true do nothing. The compiler will not produce an
error. Here’s an example (of what NOT
to do): int i
= 0; while (i < 5); // the semicolon causes an infinite loop { System.out.println(“This will never be printed.”); i = i + 1; } |