Java for Beginners · Module 4: Control Flow
🎯 The Loop for Counting
When you know how many times to repeat, the for loop is the neatest choice. It puts the start, the condition and the update on a single line, so you can see the whole loop at a glance.
1️⃣ The for Loop
int i = 1 (once)
i <= 5 ?
runs
i++
for (init; condition; update) { body }: all three control parts sit on one line.Figure 1: The order of events in a for loop.
Program 1: Counting, summing and factorial
public class ForBasic {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 10; i >= 0; i -= 2) {
System.out.print(i + " ");
}
System.out.println();
int sum = 0;
for (int k = 1; k <= 100; k++) {
sum += k;
}
System.out.println("Sum 1..100 = " + sum);
int fact = 1;
for (int k = 1; k <= 5; k++) {
fact *= k;
}
System.out.println("5! = " + fact);
}
}
1 2 3 4 5
10 8 6 4 2 0
Sum 1..100 = 5050
5! = 120
- Use
print(without ln) to keep the numbers on one line, and a bareprintln()to end the line. - A loop can count down (
i--) or step by any amount (i -= 2). - The loop variable
int iis declared inside the for, so it exists only within the loop (Lesson 11). The same name can be reused in the next loop. - Accumulator pattern: start a variable (
sum = 0,fact = 1) before the loop and update it each pass. For a sum the start is 0, and for a product the start is 1.
Program 2: A multiplication table
public class Table {
public static void main(String[] args) {
int n = 7;
for (int i = 1; i <= 10; i++) {
System.out.println(n + " x " + i + " = " + (n * i));
}
}
}
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
2️⃣ Other Shapes of for
public class ForEachAndMulti {
public static void main(String[] args) {
int[] marks = {70, 85, 90};
int total = 0;
for (int m : marks) {
total += m;
}
System.out.println("Total = " + total);
for (int i = 0, j = 10; i < j; i += 3, j -= 3) {
System.out.println("i = " + i + ", j = " + j);
}
int count = 0;
for (int a = 1; a <= 3; a++) {
for (int b = 1; b <= 4; b++) {
count++;
}
}
System.out.println("Inner body ran " + count + " times");
}
}
Total = 245
i = 0, j = 10
i = 3, j = 7
Inner body ran 12 times
- For-each loop:
for (int m : marks)reads “for each m in marks”. It visits every element of an array without an index. Arrays come in Lesson 21. - You can run two variables together by separating them with commas in the init and update parts.
- A loop inside a loop is a nested loop. The inner body runs (outer count × inner count) times: 3 × 4 = 12.
3️⃣ Nested Loops and Patterns
Printing patterns is the standard way to practise nested loops. Think of the output as a table: the outer loop chooses the row, and the inner loop prints along that row.
| Outer row | Inner loop runs | Prints |
| 1 | 1 time | * |
| 2 | 2 times | * * |
| 3 | 3 times | * * * |
| 4 | 4 times | * * * * |
Figure 3: How a nested loop prints a triangle.
| row | spaces before | stars | what is printed |
| 1 | 3 | 1 | * |
| 2 | 2 | 3 | *** |
| 3 | 1 | 5 | ***** |
| 4 | 0 | 7 | ******* |
Figure 2: The formula behind the pyramid pattern.
Program 4: Four classic patterns
public class Patterns {
public static void main(String[] args) {
System.out.println("Right triangle:");
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
System.out.print("* ");
}
System.out.println();
}
System.out.println("Number triangle:");
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
System.out.print(col + " ");
}
System.out.println();
}
System.out.println("Pyramid:");
for (int row = 1; row <= 4; row++) {
for (int s = 1; s <= 4 - row; s++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * row - 1; k++) {
System.out.print("*");
}
System.out.println();
}
System.out.println("Square of letters:");
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) {
System.out.print((char) ('A' + c));
}
System.out.println();
}
}
}
Right triangle:
*
* *
* * *
* * * *
Number triangle:
1
1 2
1 2 3
1 2 3 4
Pyramid:
*
***
*****
*******
Square of letters:
ABCD
ABCD
ABCD
- Right triangle: in row r, the inner loop runs r times, so it prints r stars. After each row,
println()moves to the next line. - Number triangle: the same shape, but it prints the inner counter
colinstead of a star. - Pyramid: each row needs two inner loops, one for spaces (4 − row of them) and one for stars (2 × row − 1 of them).
- Letters:
(char) ('A' + c)turns the column number into a letter, using the char arithmetic from Lesson 8. - To design any pattern, write down for each row how many spaces and how many symbols it needs, then find the formula in terms of the row number.
4️⃣ Errors Beginners Meet
Commas instead of semicolons
public class Bad1 {
public static void main(String[] args) {
for (int i = 0; i < 3, i++) {
System.out.println(i);
}
}
}
Bad1.java:3: error: ‘;’ expected
for (int i = 0; i < 3, i++) {
^
1 error
- The three parts of a for loop are separated by semicolons.
Using the loop variable after the loop
public class Bad2 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
System.out.println("Last i = " + i);
}
}
Bad2.java:6: error: cannot find symbol
System.out.println(“Last i = ” + i);
^
symbol: variable i
location: class Bad2
iwas declared inside the for, so it vanishes after the loop. Declare it before the loop if you need its final value.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
for (int i = 0; i < 3, i++) | Comma instead of semicolon | Use ; |
for (...); with a semicolon at the end | Empty loop body; the block runs once after | Remove the ; |
Off by one: i <= n versus i < n | One extra or one missing pass | Trace the first and last values |
| Starting a product at 0 | Result is always 0 | Start products at 1 |
| Reusing the same variable in nested loops | Inner loop disturbs the outer | Use different names (row, col) |
Forgetting println() after the inner loop | Everything on one line | Add it after the inner loop |
❓ Frequently Asked Questions
Q1. When should I use for instead of while?
Use for when the count is known, and while when the loop depends on something that happens during the run.
Q2. Can any part of the for header be empty?
Yes. for (;;) is an infinite loop. You then need a break (Lesson 20).
Q3. Does a for loop run its update after the last pass?
Yes, the update runs after every body pass, then the condition is checked and fails.
Q4. How many times does a nested loop run?
Outer count × inner count, if the inner count does not change.
✅ Key Takeaways
for (init; condition; update)keeps the whole loop control on one line.- The init runs once. Then: test, body, update, repeat.
- Use sum starting at 0 and product starting at 1 for the accumulator pattern.
- For-each (
for (int m : marks)) visits every element of an array. - Nested loops print patterns: the outer loop is the row, the inner loop is the column.
🎓 Practice questions: (1) Print the first 10 even numbers. (2) Print the Fibonacci series up to 10 terms. (3) Print an inverted triangle of stars with 5 rows. (4) Print the pattern with rows “1”, “2 2”, “3 3 3”, “4 4 4 4”. (5) Write a program that prints all prime numbers between 1 and 50 using a nested loop.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java