Java Arena
Step 2 of 7

for loops

Counting loops are so common that Java has a shorter way to write them. The for loop puts all three parts on one line, separated by semicolons:

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}
Output
1
2
3
4
5

for (start; condition; change) does the same as this while loop:

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}
  • The start runs once, before the first round.
  • The condition is checked before every round.
  • The change runs at the end of every round.

A loop variable is often called i. Made in the for line, it only exists inside the loop. Counting down and other steps work too: for (int i = 10; i >= 1; i--) counts from 10 to 1, and i += 2 instead of i++ takes every second number.

Your task

Challenge 1 of 3

Rewrite this while loop as a for loop. The program prints:

Lap 1
Lap 2
Lap 3
Lap 4

Challenge 2

Read a start number and, with a for loop, print every whole number from it up to 10. For the input 7 the program prints:

7
8
9
10

Challenge 3

Read a number and, with a for loop, print its times table from 1 to 10, in the form 1 x 7 = 7. For the input 7 the program prints:

1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
5 x 7 = 35
6 x 7 = 42
7 x 7 = 49
8 x 7 = 56
9 x 7 = 63
10 x 7 = 70