Learn/Java/5. Loops
Lesson 5 of 15
Sign in

Java, lesson 5

Loops

Computers are good at doing the same thing many times without getting bored. A loop runs a block of code again and again while some condition holds.

The for loop

Use for when you know how many times to repeat, or you are counting through a range:

The header has three parts separated by semicolons:

  1. Start: int i = 1 runs once, before the loop.
  2. Condition: i <= 5 is checked before every pass; when it is false, the loop ends.
  3. Update: i++ runs after every pass.

The variable i only exists inside the loop. You can count down (i--) or in steps () just as easily.

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Step counter

Press Ctrl Enter or Check to test your code.

i += 2

The while loop

Use while when you do not know in advance how many passes you need, only when to stop:

If the condition is false from the start, the body never runs. A do { ... } while (condition); loop is the variant that always runs the body at least once, because it checks at the end.

Reading until the input runs out

A very common pattern is to read lines until readLine() returns null, meaning no more input:

The assignment line = in.readLine() happens inside the parentheses, and its value is then compared with null. It looks unusual at first, but you will see it in a lot of Java code.

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of the current pass and jumps to the next one.

Use them to keep loops flat and readable instead of nesting many if blocks.

Infinite loops and accumulators

If the condition never becomes false, the loop runs forever and the program is stopped for taking too long. Check that something inside the loop moves you toward the exit.

Most loops build up a result in an accumulator, a variable declared before the loop and updated inside it, like a running total, a counter, or the best value seen so far.

Further reading

  • Control flow statements (dev.java)
  • BufferedReader.readLine

Read one whole number n and print its times table from 1 to 10, one line each, in the form n x i = result.

Sample input:

Sample output:

A fitness tracker sends one whole number per line: the steps walked each day. A line containing 0 means "tracking stopped", and the input may also simply end. Stop at whichever comes first; the 0 itself is not a day.

Print three lines: the number of days, the total steps, and the best day. If there are no days, all three are 0.

Sample input:

Sample output:

for (int i = 1; i <= 5; i++) {
    System.out.println("Lap " + i);
}
int balance = 100;
int months = 0;
while (balance < 200) {
    balance += balance / 10;   // 10% growth
    months++;
}
System.out.println(months + " months");
String line;
while ((line = in.readLine()) != null) {
    if (line.isBlank()) continue;      // skip empty lines
    System.out.println("Got: " + line);
}
for (int n = 1; n <= 100; n++) {
    if (n % 7 != 0) continue;   // not a multiple of 7: skip
    if (n > 30) break;          // far enough: stop
    System.out.println(n);      // 7 14 21 28
}
7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
8000
12000
5000
0
9999
Days: 3
Total: 25000
Best: 12000