A loop runs the same block of code again and again. Printing the numbers 1 to 100 takes three lines with a loop instead of a hundred without one.
while
A while loop checks its condition, runs the block if it's true, then goes back and checks again. It stops the first time the condition is false. Something inside the loop must change, or the condition stays true forever and the program never stops (an infinite loop).
Java
int count = 3;
while (count > 0) {
System.out.println(count);
count--;
}
System.out.println("Lift off!");
Prints
3
2
1
Lift off!
for
When you know how many times to go round, the for loop puts the three parts of counting on one line: where to start, when to keep going, and what to do after each turn. for (int i = 1; i <= 5; i++) reads "start i at 1; while i is at most 5; add 1 each time". Programmers often call the counter i.
Java
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 10; i > 0; i -= 3) {
System.out.print(i + " ");
}
System.out.println();
Prints
1 2 3 4 5
10 7 4 1
i < 5 and i <= 5 differ by one turn, so check the end carefully. Starting at 0 with i < 5 also goes round five times (0 to 4), and that's the usual shape once you work with lists, which count from 0.
Adding things up
A very common pattern is a running total: make a variable before the loop, then add to it each time round.
Java
int total = 0;
for (int i = 1; i <= 4; i++) {
total += i;
}
System.out.println(total);
Prints
10
Turn by turn: total is 0, then 0+1 = 1, 1+2 = 3, 3+3 = 6, 6+4 = 10. Tracing a loop by hand like this, writing down each variable at each turn, is the best way to understand one.
break and continue
break leaves the loop straight away. continue skips the rest of this turn and moves on to the next one.
Java
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
if (i > 7) break;
System.out.print(i + " ");
}
System.out.println();
Prints
1 3 5 7
Loops inside loops
A loop can sit inside another one. The inner loop runs all the way through for each turn of the outer one, which is how you'd draw a grid or a times table:
Java
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print(row * col + "\t");
}
System.out.println();
}
Prints
1 2 3
2 4 6
3 6 9
\t is a tab, which lines columns up. If a loop seems stuck, press Ctrl+C in the terminal to stop the program, then check what's supposed to change inside it.
Practice
What does this print?
for (int i = 0; i < 3; i++) {
System.out.print(i);
}
More info
Quick reference
while (cond) { }
Repeat while cond is true; checked before each turn.
for (int i = 0; i < n; i++) { }
Count from 0 to n - 1: n turns.
i <= n vs i < n
Includes n / stops before n.
total += x
A running total: start at 0 before the loop.
break
Leave the loop now.
continue
Skip to the next turn.
infinite loop
A loop whose condition never becomes false; Ctrl+C stops it.