While loops
1public class WhileLoops {
2 public static void main(String[] args) {
3 // A different type of loop
4 int i = 1;
5 while(i < 11) {
6 System.out.println(i);
7 i++;
8 }
9 System.out.println("End: " + i);
10
11 // The condition can be anything
12 i = 1;
13 while(i % 5 != 0) {
14 System.out.println(i);
15 i++;
16 }
17 System.out.println("End: " + i);
18
19 i = 10;
20 while(i > 0) {
21 System.out.println(i);
22 i--;
23 }
24 System.out.println("End: " + i);
25 }
26}
Explanation
In this exercise, we introduce
while
loops, which are another kind of loop. They are likefor
loops, but they only have one condition that has to be met, and no initialisation or increment. That is why variables used in the condition are defined beforehand.Like
for
loops, thewhile
loops continue until the condition specified in parentheses is no longer met.The first
while
loop repeats untili
equals11
, whereas the secondwhile
loop repeats untili
is divisible by 5.In the third
while
loop,i
is decremented. It continues to run untili
becomes0
.While
loops are always in the form:while(CONDITION) { BODY; }
Note: You must remember to change
i
when you code awhile
loop. Imagine line 7 were omitted - the value ofi
would never change and thewhile
loop's condition would always be true. This would create aninfinite while loop
, and for now must be avoided.
Exercises
Note: These are the same exercises as in Part VI, but using while
loops.
Write a program,
Ex7B
, that uses awhile
loop to produce the following sequence:1 -2 4 -8 16 -32
, stopping once it gets to 2000.Write a program,
Ex7C
that uses awhile
loop to produce the following sequence:1 3 6 10 15 21 28 36
. Hint: Use a counter to store the last number you've printed out, and think about what number to start at.Write a program,
Ex7D
, that prints out all the multiples of 9 between 0 and 108.Write a program,
Ex7E
, that prints out the sum of all the multiples of 9 between 0 and 108.