Why loops?
14 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A loop repeats lines of code for you. You write the lines once, and Java runs them again and again until a condition says stop.
Repeating without copy-paste
Your teacher asks for the 7 times table. With one println per row, a table up to 7 x 100 needs a hundred almost identical lines.
A loop runs the same lines again and again, so three lines can print any number of rows.
Example 1 · Without a loop
public class NoLoop { public static void main(String[] args) { System.out.println("7 x 1 = 7"); System.out.println("7 x 2 = 14"); System.out.println("7 x 3 = 21"); System.out.println("7 x 4 = 28"); System.out.println("7 x 5 = 35"); }}7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
What this code does
- Five almost identical lines print five rows.
- Only the number after
7 xand the answer change from line to line. That is the sign that a loop can do the job.
Example 2 · With a loop
public class WithLoop { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println("7 x " + i + " = " + (7 * i)); } }}7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
What this code does
- The line inside
{ }is written once but runs five times, once for each value ofi: 1, 2, 3, 4, 5. (7 * i)works out the answer for the current row, so no answer is typed by hand.- Change
5to10and the same three lines print the full table.
for line yet. The next lesson, The for loop (opens in a new tab), takes it apart piece by piece.What every loop needs
You tell a friend to do 3 push-ups and count them. Without noticing, you give three rules: start at 1, stop after 3, add one each time. Every loop needs the same three things, held in a counter, a variable that remembers the round, like rep:
- Start: the counter's first value,
rep = 1. - Condition: checked before each round,
rep <= 3. While it istrue, the loop goes on. - Update: moves the counter on after each round,
rep++.
One run of the loop's lines is called an iteration, or simply a round. When the condition becomes false, the loop ends and Java goes to the line after it. Step through the program below and watch rep change.
Trace the code
Watch the push-up counter
Variables
- rep
- 1
Output
(nothing printed yet)Line 3Start: the counter rep is made and set to 1. The start runs only once.
true and the loop never stops. This is called an infinite loop.Two kinds of repeating
Sometimes you know the number of rounds before you start: 10 rows of a table, 5 subjects. Sometimes you do not: an ATM asks for the PIN until it is right, and nobody knows how many tries that will take.
A for loop (opens in a new tab) fits a known number of rounds. A while or do-while loop (opens in a new tab) fits "repeat until something happens". Sort the tasks below to feel the difference.
Classify
Known count or until something happens?
Tap a task, then tap the kind of repeating it needs.
Next step
Check your understanding
7 quick questions