Repeating with for Loops
A for loop repeats code a set number of times — perfect for counting.
What you will learn
- Write a for loop with start, condition and step
- Use the loop counter inside the loop
- Count up and count down
Why loops?
Imagine printing the numbers 1 to 5. You could write five println lines — but what about 1 to 1000? A loop repeats a block of code so you do not have to.
A for loop is ideal when you know how many times to repeat. It has three parts inside the brackets:
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}Note: Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
The three parts are: start (int i = 1), keep going while (i <= 5), and step (i++ adds 1 each time). The loop stops when i becomes 6 because the condition is no longer true.
Reading the three parts
| Part | Example | Meaning |
|---|---|---|
| Start | int i = 1 | Runs once, before the loop begins |
| Condition | i <= 5 | Checked before each round; loop runs while true |
| Step | i++ | Runs after each round (here, add 1) |
The i++ is shorthand for i = i + 1. The counter i is a normal variable you can use inside the loop — that is how we printed it.
Counting down
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
System.out.println("Lift off!");Note: Output:
5
4
3
2
1
Lift off!
This time we start at 5, keep going while i >= 1, and i-- subtracts 1 each round. After the loop finishes, the last line runs once.
Watch out: Beware the infinite loop. If the step never makes the condition false (for example, counting up but using i--), the loop runs forever. Always check that the loop will eventually stop.
Tip: Programmers usually start counting from 0, not 1, because arrays (next-but-one lesson) are numbered from 0. So for (int i = 0; i < 5; i++) is extremely common.
Q. In for (int i = 1; i <= 3; i++), how many times does the loop body run?
i <= 3 is false, so the loop stops.✍️ Practice
- Print the even numbers from 2 to 10 using a for loop (hint: step by 2 with
i += 2). - Use a loop to add up 1 + 2 + ... + 10 and print the total.
🏠 Homework
- Write a program that prints the times table of a number the user enters (for example, 7 x 1 up to 7 x 10).