Chapter 7a - Nested Loops
Why Nest a Loop?β
A single loop repeats one line of work. A nested loop β a loop inside another loop β repeats a whole block of work, once for every pass of the outer loop. That is exactly what you need for anything shaped like a grid: rows and columns, a multiplication table, a pattern of stars.
Rule of thumb: the outer loop picks the row, the inner loop draws everything in that row.
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print("* ");
}
System.out.println(); // move to the next line after each row
}
}
}
π§ͺ Try the code out!
For every one pass of the outer loop, the inner loop runs completely β start to finish. With row going 1β3 and col going 1β3, the inner print runs 3 Γ 3 = 9 times total, but println() (the newline) only runs 3 times, once per row.
Mini quiz β tracing nested loopsβ
Tracing nested loops
1 / 2How many times does the inner System.out.print run in total?
for (int row = 1; row <= 4; row++) {for (int col = 1; col <= 2; col++) {System.out.print("*");}}
Pick an answer to see if you are right.
A Row That Grows: Trianglesβ
Patterns get more interesting once the inner loop's limit depends on the outer loop's current value.
public class Main {
public static void main(String[] args) {
int n = 4;
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= row; col++) { // notice: col <= row, not col <= n
System.out.print("*");
}
System.out.println();
}
}
}
Output for n = 4:
*
**
***
****
π§ͺ Try the code out!
Mini quiz β growing patternsβ
Growing patterns
1 / 2To print a triangle where row 1 has 1 star and row 5 has 5 stars, the inner loop condition should be
Pick an answer to see if you are right.
Challenge: star triangleβ
Read one integer n. Print a triangle of * with n rows: row i has i stars, no spaces between stars, one row per line.
Piston runs the file as Main.java, so the public class the tests call into must be named Main. If you want a separate class to hold your own main, name it something else (like Runner above) β Java allows more than one class per file as long as only one is public.
Challenge: multiplication rowβ
Read two integers on one line: row and limit. Print the multiplication table row for row, from row * 1 up to row * limit, space-separated.
Chapter summaryβ
- A nested loop is a loop inside another loop: the outer loop picks the row, the inner loop does the work for that row.
- The inner loop runs completely for every single pass of the outer loop β multiply the two trip counts to know the total number of inner-loop runs.
- When a pattern grows or shrinks by row, the inner loop's limit depends on the outer loop's current variable (
col <= row), not a fixed number. println()(notprint()) is what moves you to a new row between passes of the outer loop.
Exercisesβ
Read one integer n. Print a single row of n characters alternating # and ., starting with # (e.g. for n = 5: #.#.#). You do not need a second nested loop for this one β think about how the column index (col % 2) decides which character to print.