Skip to main content

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!

Trace it before you run it

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​

Quiz

Tracing nested loops

1 / 2

How 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​

Quiz

Growing patterns

1 / 2

To 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.

About the class name

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​

Key takeaways
  1. A nested loop is a loop inside another loop: the outer loop picks the row, the inner loop does the work for that row.
  2. 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.
  3. 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.
  4. println() (not print()) is what moves you to a new row between passes of the outer loop.

Exercises​

Activity: Checkerboard row

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.