Written by Lisa Yan
These are practice programs to help you get familiar with loops in Java. They are ordered from easiest to hardest.
Recall the general structure of a for loop:
for(int i = 0; i < 15; i++) { // some code... }
The loop above runs for 15 iterations. You can parse the meaning of a for loop from the first line:
i
that starts at 0.i < 15
.i < 15
, run the code inside the loop. While running the loop code, you can use the value of i
. So for example, the first time the loop runs, the value of i
is zero.
i++
.!(i < 15)
, exit the loop. So the last time the loop code runs, the value of i
is 14, and i
is incremented to 15. Then it fails the check for i < 15
and the loop code doesn't run.Caution! It is very difficult to catch programming bugs in the loop condition! So we always suggest that you design the most basic loop, and increment the loop counter by one (that is, i++
). And then don't change the value of the loop counter within the loop itself!
// Don't do this! This is hard to debug! for(int i = 0; i < 10; i ++) { i += 2; // bad!!! println(i); }
// Uses another variable to keep the loop counter safe for(int i = 0; i < 10; i ++) { int j = i + 2; // does not change the value of i println(j); }
The following exercises are all about using the for-loop counter i
.
BonusConsole: LoopingFun1.java
Try to produce the following output with a loop. Print the first ten odd numbers, starting from 1.
Extension: Now try to print the first ten even numbers, starting from 0.
BonusConsole: LoopingFun2.java
Try to produce the following output with a loop. Print the first ten even numbers in decreasing order.
Can you solve this problem without changing the loop condition from the previous problem? That is, start from the following for loop code:
for(int i = 0; i < 10; i++) { // some code... }
How would you solve the problem by using the following loop condition?
for(int i = 0; i < 20; i++) { // some code... }
BonusConsole: LoopingFun3.java
Use a loop, but print out everything on a single line. Recall that println()
adds a line break/new line, whereas print()
does not.
Print out the squares, starting from 1.
Try avoiding a comma at the end of the last square!
BonusConsole: LoopingFun4.java
Time for nested for loops! Print out the coordinates of a 5x5 grid.
Hint: try the following code structure:
for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++) { // some code... } }
Want more practice with while loops? Do all the above exercises with a while loop instead of a for loop. Good luck!