Part 03 / Topic 5 of 8
for loops
A for loop packs "start, keep going while, and what to do each time" into one line: for (init; condition; update). It fits best when you already know how many times to repeat, or you are counting something.
int loanAmount = 60000;
int months = 6;
int emi = loanAmount / months;
int remaining = loanAmount;
for (int month = 1; month <= months; month++) {
remaining -= emi;
System.out.println("Month " + month + ": paid Rs " + emi + ", remaining Rs " + remaining);
}
Output:
Month 1: paid Rs 10000, remaining Rs 50000
Month 2: paid Rs 10000, remaining Rs 40000
Month 3: paid Rs 10000, remaining Rs 30000
Month 4: paid Rs 10000, remaining Rs 20000
Month 5: paid Rs 10000, remaining Rs 10000
Month 6: paid Rs 10000, remaining Rs 0
Counting down just reverses the condition and the update:
for (int seconds = 5; seconds >= 1; seconds--) {
System.out.println(seconds + "...");
}
System.out.println("Transaction started.");
Output:
5...
4...
3...
2...
1...
Transaction started.
A for loop can sit inside another for loop — a nested loop — for anything grid-shaped (rows and columns, here a cinema seating chart):
int rows = 3;
int seatsPerRow = 4;
for (int row = 1; row <= rows; row++) {
StringBuilder line = new StringBuilder("Row " + row + ": ");
for (int seat = 1; seat <= seatsPerRow; seat++) {
line.append(row).append(seat).append(' ');
}
System.out.println(line.toString().trim());
}
Output:
Row 1: 11 12 13 14
Row 2: 21 22 23 24
Row 3: 31 32 33 34
The inner loop runs completely (all 4 seats) for every pass of the outer loop (each of the 3 rows) — 12 total passes through the inner body.
🔍 Going further: the
forheader can update more than one variable, separated by commas:for (int left = 0, right = 5; left < right; left++, right--). This is legal but rare — reach for it only when two counters genuinely move together.
Full program: examples/04_for_loops.java.
Done here? The practice set for Part 3 — including the solutions — is on the part page.