The canteen's seating chart
For the annual fest, the canteen sets up 4 rows of tables. The first row has 1 table, the second 2, the third 3, the fourth 4: a triangle, so everyone can see the stage. Riya wants to print the layout. One loop can print rows, but each row needs its own count of tables.
Sir, one loop goes down the rows. But how do I print a different number of tables in each row?
Put a second loop inside the first. The outer loop picks the row; for that row, the inner loop places the tables. The trick is the inner loop's limit: t <= row. Row 3 gets 3 tables.
So the inner loop runs completely, from start to finish, every time the outer loop takes one step?
Exactly, like a clock: the minute hand goes all the way round for each step of the hour hand. Once you see that, every pattern question becomes easy.
What is a nested loop?
A nested loop is a loop placed inside the body of another loop. For each iteration of the outer loop, the inner loop executes all of its iterations. If the outer loop runs m times and the inner loop runs n times per outer iteration, the inner body executes m × n times. Any loop type (for, while, do-while) can be nested inside any other.
Outer loop = rows, inner loop = columns. The inner loop finishes a whole row before the outer loop moves to the next row, just like reading a page: left to right along a line, then down to the next line.
Words you'll meet in this lesson
col <= row.Counting iterations
| Rectangle (rows × cols) | for r 1..m { for c 1..n } → inner body runs m × n times |
|---|---|
| Triangle (col ≤ row) | 1 + 2 + … + n = n(n + 1) / 2 times |
| All pairs (j starts at i + 1) | n(n − 1) / 2 pairs, each checked once |
| Loop variables | Use different names (row/col or i/j); the inner one is recreated each outer iteration |
| println placement | After the inner loop, inside the outer loop: one line break per row |
Exam tip: for for (i = 1; i <= 3; i++) for (j = 1; j <= 4; j++), the inner statement runs 12 times. A common question asks how many times a statement runs, or the output of a pattern program: draw a small table of i and j values to answer it.
The row-and-column method for any pattern
Every pattern question can be solved the same way. Write a table: for each row, what is printed, and how many of each?
| Pattern (n = 4) | Row r prints | Inner loop(s) |
|---|---|---|
* | r stars | c <= r |
**** | n − r + 1 stars | c <= n - r + 1 |
* | n − r spaces, then 2r − 1 stars | Two inner loops |
1 | the numbers 1..r | print c |
1 | r, r times | print r |
Beyond patterns: where nested loops are used
Grids and tables
Seat maps, chessboards, spreadsheets, images (pixels in rows and columns), 2D arrays (Lesson 4.2).
Rows × columnsAll pairs
Comparing every item with every other: duplicates, matching pairs, distances between delivery points.
i, j > iGroup then item
For each store, each order; for each class, each student; for each month, each day.
HierarchiesPerformance: two nested loops over n items do about n² steps. For 100 items that's 10,000 (instant). For 1,00,000 items it's 10,000,000,000 (minutes or hours). In real systems, large “compare everything with everything” jobs use smarter structures such as hash maps or sorting instead.
Cracking a pattern: the centred pyramid
Draw it and number the rows
The outer loop will run once per row:* *** ***** *******for (int row = 1; row <= n; row++).Make a table of what each row contains
Row 1: 3 spaces, 1 star. Row 2: 2 spaces, 3 stars. Row 3: 1 space, 5 stars. Row 4: 0 spaces, 7 stars.
Look for the formula in each column: spaces go 3, 2, 1, 0 →n - row. Stars go 1, 3, 5, 7 →2 * row - 1.Write one inner loop per column of the table
Both inner loops run, one after the other, inside each outer iteration. Their variables are recreated every row.for (int s = 1; s <= n - row; s++) System.out.print(" "); for (int st = 1; st <= 2 * row - 1; st++) System.out.print("*");End the row
This sits after the inner loops but inside the outer loop. Put it inside an inner loop and every star lands on its own line.System.out.println();Check with n = 1 and n = 2
Small cases expose off-by-one mistakes quickly: n = 1 should print a single star with no spaces.
Total characters printed grow with n²; that's fine for patterns, but remember the warning about big data.
The inner loop runs fully for each row: both views
Left: the triangle being printed. Right: the values of row and col, and how the work adds up.
- Row 1: the inner loop prints one star, then
println()ends the line. - Row 2: the inner loop starts again from col = 1 and runs twice.
- Row 3: three stars. The inner loop restarts for every row.
- Row 4: four stars. Now
rowbecomes 5, and the outer loop ends. - The inner body ran 1 + 2 + 3 + 4 = 10 times, which is n(n + 1)/2.
- For a full n × n grid the work is n². Fine for patterns; far too slow for comparing lakhs of records.
- For row 1, the inner body runs once, with (row, col) = (1, 1).
- For row 2,
colis recreated at 1 and goes up to 2. - The inner limit depends on the outer variable, so the cells form a triangle.
- Ten (row, col) pairs in total: exactly the stars printed.
- In bytecode, the inner loop is a smaller cycle of jumps inside the outer cycle.
- The inner cycle's jump is taken many more times than the outer one: that's where the time goes.
Nested loops in real systems
Whenever data has two levels (rows and columns, groups and items), nested loops appear.
Watch it with an example: printing a cinema seat map
Rows A to C, seats 1 to 4. The outer loop picks a row; the inner loop runs completely for every row. Watch the order in which the 12 seats are printed.
- The plan: 3 rows and 4 seats per row. Two loops, one inside the other.
- Row A: the outer loop sets row = A. The inner loop then runs fully: A1, A2, A3, A4.
- Row B: the outer loop moves on. The inner loop starts again from seat 1: B1, B2…
- … B3, B4. Only when the inner loop finishes does the outer loop move to the next row.
- Row C: C1 to C4. That's 3 rounds of the outer loop.
- Total work: 3 × 4 = 12 inner iterations. Booking apps draw seat maps exactly like this; with 20 rows × 30 seats it's 600 iterations.
1. Seat maps in booking apps
Bus, train and cinema apps draw the seat map with an outer loop over rows and an inner loop over seats, colouring each by its status.
2. Reports with rows and columns
A store × week sales table, a student × subject marks sheet, or a month × category expense report: loop over rows, then columns, adding row and column totals.
3. Image processing
A photo is a grid of pixels. Filters (brightness, blur, grayscale) loop over every row and every column of pixels. A 12-megapixel photo means 1.2 crore inner iterations.
4. Distances between all locations
Delivery and ride-hailing systems may need distances between every pickup and every driver. For small numbers a nested loop works; at city scale, they use spatial indexes to compare only nearby pairs.
5. Group-then-item processing
Schools send report cards class by class, student by student; banks run month-end jobs branch by branch, account by account. The outer loop also gives a natural point to log progress or commit work.
Examples are simplified to show where nested loops fit. Large systems use indexes and databases to avoid comparing everything with everything.
The seating triangle
public class Main {
public static void main(String[] args) {
int n = 4;
for (int row = 1; row <= n; row++) { // outer: rows
for (int col = 1; col <= row; col++) { // inner: items in this row
System.out.print("*");
}
System.out.println(); // end of the row
}
}
}for (int row = 1; row <= n; row++)The outer loop runs once per line of output.col <= rowThe dependent limit: row r prints r stars.System.out.print("*")print, not println, so the stars stay on the same line.System.out.println()After the inner loop, inside the outer loop: one line break per row.
Watch col restart for every row
A triangle with n = 3. Notice col disappearing and being recreated at 1 each time row moves on.
Worked examples: real problems, solved and traced in memory
A loop inside a loop handles anything with rows and columns: seating charts, tables, calendars and printed patterns. In the traces, notice that the inner loop runs completely for every single pass of the outer loop.
Print a seating chart
Problem statement
A seminar hall has 3 rows (A–C) of 4 seats. Print the chart with seat labels like A1 A2 …, one row per line.
3 rows, 4 seats
A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4
Approach
- Outer loop over rows, inner loop over seats.
- Row letter:
(char) ('A' + r). printinside,printlnafter each row.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Weekly sales per store
Problem statement
Two stores record sales for 3 days in a 2D array. Print each store's total and the overall total.
Pune {1200, 950, 1800}; Nashik {700, 1100, 640}Pune: Rs 3950 Nashik: Rs 2440 All stores: Rs 6390
Approach
- Outer loop over stores, inner loop over days.
- Reset
storeTotalfor each store. - Add each store's total into the grand total.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
A right-angled number triangle
Problem statement
A token display board shows a staircase of numbers. Print 4 rows where row i has the numbers 1 to i. The inner loop's limit depends on the outer loop variable.
4 rows
1 1 2 1 2 3 1 2 3 4
Approach
- Outer loop
ifrom 1 to 4. - Inner loop
jfrom 1 toi. - So row 1 prints once, row 4 prints four times.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Check yourself
Quick revision
Lesson 3.6 in one screen
- The inner loop runs completely for each outer iteration.
- Iterations: rectangle m × n; triangle n(n + 1)/2; all pairs n(n − 1)/2.
- Patterns: outer = rows; make a table of what each row prints; turn each column of the table into an inner loop.
- Common formulas: r items; n − r + 1 items; n − r spaces + 2r − 1 stars.
println()after the inner loop(s), inside the outer loop.- Different variable names for each loop; the inner one is recreated every row.
- Nested loops grow as n²: fine for small grids, too slow for comparing huge datasets.
Interview and viva questions
What is the time complexity of two nested loops?
If each loop runs up to n times, the inner body runs about n × n times: O(n²). If the inner loop's limit depends on the outer variable (a triangle), it's about n²/2, which is still O(n²).
How do you approach any pattern question?
Number the rows, write down for each row how many spaces and how many symbols (or which numbers) it has, find formulas in terms of the row number, then write one inner loop per part of the row, followed by println.
How do you break out of both loops at once?
Use a labelled break (outer: for … break outer;), set a flag checked by the outer loop, or put the loops in a method and return (Lesson 3.5).
Can different loop types be nested?
Yes. A while inside a for, a for-each inside a while, and so on. The rule is the same: the inner loop completes for each outer iteration.
How can nested-loop algorithms be made faster?
Avoid repeated work: use a HashSet or HashMap for lookups instead of an inner search loop, sort data first so a single pass is enough, or stop early with break when the answer is known.
Practice problems
Pattern problems are a favourite in campus tests because they train you to connect the row number to what gets printed. Work out the rule for each row on paper first, then code it. The last three are real business tasks that use nested loops.
Square of stars
Print an n × n square of stars.
n = 4
**** **** **** ****
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 4;
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= n; col++) {
System.out.print("*");
}
System.out.println();
}
}
}How it works: the outer loop chooses the row; the inner loop prints every column of that row; println() after the inner loop moves to the next line. Every row has the same length, so the inner limit is n, not related to row.
Number triangle
Print rows where row r contains the numbers 1 to r.
n = 5
1 12 123 1234 12345
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 5;
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= row; col++) {
System.out.print(col);
}
System.out.println();
}
}
}How it works: the rule is “row r has r items”, so the inner loop runs col <= row. Printing col gives 1…r; printing row instead would give 1, 22, 333… Try it.
Inverted triangle
Print a triangle of stars that gets shorter on each row.
n = 4
**** *** ** *
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 4;
for (int row = n; row >= 1; row--) {
for (int col = 1; col <= row; col++) {
System.out.print("*");
}
System.out.println();
}
}
}How it works: the outer loop counts down, so the first row has n stars. Equivalent rule with an upward loop: row r prints n - r + 1 stars.
Multiplication grid
Print a 5 × 5 multiplication grid with neatly aligned columns.
size = 5
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
Show solution and explanation
public class Main {
public static void main(String[] args) {
int size = 5;
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
}
}How it works: each cell is row × column. %4d prints each number right-aligned in 4 characters, so 5 and 25 line up in columns. The inner loop runs 5 times for each of the 5 outer iterations: 25 cells in total.
Centred pyramid
Print a pyramid of stars centred on the last row: row r has (n − r) leading spaces and (2r − 1) stars.
n = 4
* *** ***** *******
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 4;
for (int row = 1; row <= n; row++) {
for (int s = 1; s <= n - row; s++) {
System.out.print(" ");
}
for (int st = 1; st <= 2 * row - 1; st++) {
System.out.print("*");
}
System.out.println();
}
}
}How it works: each row has two inner loops: one for spaces, one for stars. Write a small table first: row 1 → 3 spaces, 1 star; row 2 → 2 spaces, 3 stars… The formulas n - row and 2 * row - 1 come straight from that table.
Floyd's triangle
Print consecutive numbers in a triangle: 1 on row 1, 2 3 on row 2, 4 5 6 on row 3, and so on.
n = 4
1 2 3 4 5 6 7 8 9 10
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 4;
int next = 1;
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= row; col++) {
System.out.print(next + (col < row ? " " : ""));
next++;
}
System.out.println();
}
}
}How it works: the shape is the usual triangle, but the number printed comes from a counter next declared outside both loops, so it keeps growing across rows instead of restarting.
Diamond
Print a diamond of stars with n rows in the top half (the middle row is the widest).
n = 3
* *** ***** *** *
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 3;
for (int row = 1; row <= 2 * n - 1; row++) {
int k = row <= n ? row : 2 * n - row; // grows to n, then shrinks
System.out.println(" ".repeat(n - k) + "*".repeat(2 * k - 1));
}
}
}How it works: a diamond is a pyramid followed by an upside-down pyramid. Instead of writing two loops, we compute k, the “size” of each row: 1, 2, 3, 2, 1. String.repeat (Java 11+) replaces the inner loops; it does the same repetition for us.
Pascal's triangle
Print the first n rows of Pascal's triangle, where each number is the sum of the two above it.
n = 5
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 5;
for (int row = 0; row < n; row++) {
int value = 1;
StringBuilder line = new StringBuilder();
for (int k = 0; k <= row; k++) {
if (k > 0) line.append(' ');
line.append(value);
value = value * (row - k) / (k + 1); // next binomial coefficient
}
System.out.println(line);
}
}
}How it works: row r, position k holds C(r, k). Instead of computing factorials, each value is derived from the previous one: C(r, k+1) = C(r, k) × (r − k) ÷ (k + 1). Multiplying before dividing keeps it an exact integer.
Hollow square
Print an n × n square where only the border is made of stars.
n = 5
***** * * * * * * *****
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 5;
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= n; col++) {
boolean border = row == 1 || row == n || col == 1 || col == n;
System.out.print(border ? "*" : " ");
}
System.out.println();
}
}
}How it works: visit every cell, and decide what to print with a condition on both row and column. A cell is on the border if it's in the first or last row, or the first or last column.
All primes up to 50
Print every prime number from 2 to 50 using nested loops.
limit = 50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Show solution and explanation
public class Main {
public static void main(String[] args) {
int limit = 50;
StringBuilder primes = new StringBuilder();
for (int n = 2; n <= limit; n++) {
boolean prime = true;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
prime = false;
break;
}
}
if (prime) primes.append(n).append(' ');
}
System.out.println(primes.toString().trim());
}
}How it works: the outer loop picks each candidate; the inner loop tests divisors up to √n and stops at the first one found. The prime flag is reset for every candidate, which is why it's declared inside the outer loop.
Store × week sales table
A chain has 3 stores. Weekly sales (in ₹ thousands) for 4 weeks are in a 2D array. Print a table with each store's total on the right, each week's total at the bottom, and the grand total.
Kharghar: 42 38 51 47 Vashi: 55 60 49 58 Panvel: 31 29 35 40
Store W1 W2 W3 W4 Total Kharghar 42 38 51 47 178 Vashi 55 60 49 58 222 Panvel 31 29 35 40 135 Total 128 127 135 145 535
Show solution and explanation
public class Main {
public static void main(String[] args) {
String[] stores = {"Kharghar", "Vashi", "Panvel"};
int[][] sales = {
{42, 38, 51, 47},
{55, 60, 49, 58},
{31, 29, 35, 40}
};
int weeks = sales[0].length;
int[] weekTotals = new int[weeks];
int grand = 0;
System.out.printf("%-9s %4s %4s %4s %4s %6s%n", "Store", "W1", "W2", "W3", "W4", "Total");
for (int s = 0; s < stores.length; s++) {
int storeTotal = 0;
System.out.printf("%-9s", stores[s]);
for (int w = 0; w < weeks; w++) {
System.out.printf(" %4d", sales[s][w]);
storeTotal += sales[s][w];
weekTotals[w] += sales[s][w];
}
grand += storeTotal;
System.out.printf(" %6d%n", storeTotal);
}
System.out.printf("%-9s", "Total");
for (int w = 0; w < weeks; w++) {
System.out.printf(" %4d", weekTotals[w]);
}
System.out.printf(" %6d%n", grand);
}
}How it works:
- The outer loop walks stores (rows), the inner loop walks weeks (columns): a classic grid traversal. 2D arrays are covered in Lesson 4.2.
- Row totals are reset for each store (declared inside the outer loop); column totals live in an array that keeps adding across all stores.
%-9sleft-aligns names in 9 characters and%4dright-aligns numbers, so the table lines up like a spreadsheet.- The grand total equals both the sum of row totals and the sum of column totals, a handy self-check in real reports.
Gift card combos
A customer has a ₹500 gift card and wants exactly two different products whose prices add up to ₹500. List every such pair from the price list.
prices: Mug 199, Diary 301, Pen set 250, Bottle 280, Planner 220, Lamp 250
Mug + Diary = Rs 500 Pen set + Lamp = Rs 500 Bottle + Planner = Rs 500 3 combination(s) found
Show solution and explanation
public class Main {
public static void main(String[] args) {
String[] names = {"Mug", "Diary", "Pen set", "Bottle", "Planner", "Lamp"};
int[] prices = {199, 301, 250, 280, 220, 250};
int card = 500;
int pairs = 0;
for (int i = 0; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
if (prices[i] + prices[j] == card) {
System.out.println(names[i] + " + " + names[j] + " = Rs " + card);
pairs++;
}
}
}
System.out.println(pairs + " combination(s) found");
}
}How it works:
- Starting the inner loop at
i + 1checks every pair exactly once and never pairs a product with itself. - For n products this is n(n − 1)/2 checks: fine for 6 products, slow for 1 lakh. With a HashMap of prices (Module 11) the same task takes one pass.
- Two products with the same price (Pen set and Lamp) are still different items, so both appear as a valid pair.
Bus seat map
A bus has 6 rows with seats A, B | aisle | C, D. Print the seat map, marking booked seats with X and free ones with their seat number, then count the free seats.
booked = 1A, 1B, 2C, 3D, 4A, 4B, 4C, 4D, 6B
X X | 1C 1D 2A 2B | X 2D 3A 3B | 3C X X X | X X 5A 5B | 5C 5D 6A X | 6C 6D Free seats: 15 of 24
Show solution and explanation
public class Main {
public static void main(String[] args) {
String booked = " 1A 1B 2C 3D 4A 4B 4C 4D 6B ";
char[] letters = {'A', 'B', 'C', 'D'};
int free = 0;
for (int row = 1; row <= 6; row++) {
StringBuilder line = new StringBuilder();
for (int s = 0; s < letters.length; s++) {
String seat = "" + row + letters[s];
if (booked.contains(" " + seat + " ")) {
line.append(" X ");
} else {
line.append(seat).append(' ');
free++;
}
if (s == 1) line.append(" | "); // the aisle after seat B
}
System.out.println(line.toString().stripTrailing());
}
System.out.println("Free seats: " + free + " of 24");
}
}How it works:
- Outer loop = rows of the bus; inner loop = the 4 seats in each row. That's the same shape as every seat map you've seen in booking apps.
- The seat label is built from the row number and letter, then checked against the booked list. Spaces around each code stop “1A” from matching inside “11A” in bigger buses.
- The aisle is drawn by a condition on the column index, not by a separate loop.
- Real booking systems store seats in a database and lock them during payment, but the map is drawn exactly like this.
Real-world scenario questions (asked in company interviews)
Nested loops work on small data and hurt on big data. Decide your answer first, then open the model answer.
Duplicate check that takes all night
A job finds duplicate customers by comparing every customer's phone number with every other using two nested loops. With 5,000 customers it took seconds. Now there are 8 lakh, and the job runs for hours. Why, and what would you do?
The interviewer is checking: do you understand O(n²) growth and know the standard fix?
Show a strong answer
Comparing all pairs is about n²/2 comparisons. 5,000 customers → about 1.25 crore comparisons; 8 lakh → about 32,000 crore. The data grew 160 times, but the work grew about 25,600 times.
- Use a single pass with a HashMap from phone number to customer: each lookup is almost constant time, so the job becomes roughly linear.
- Or let the database do it:
GROUP BY phone HAVING COUNT(*) > 1, backed by an index. - Normalise phone numbers first (remove spaces, +91) so real duplicates actually match.
Avoid saying: “Run it on a bigger server.” The algorithm is the problem.
Explaining your pattern solution to the interviewer
In a technical interview you're asked to print a centred pyramid, then the interviewer asks: “Don't just code it, explain how you found the loop limits.” What do you say?
The interviewer is checking: can you show a systematic method rather than trial and error?
Show a strong answer
- “I numbered the rows 1 to n and wrote a table: for each row, the number of spaces and stars.”
- “For n = 4, spaces were 3, 2, 1, 0, so
n - row; stars were 1, 3, 5, 7, so2 * row - 1.” - “The outer loop goes over rows; inside it, one loop prints spaces, a second prints stars, then println.”
- “I checked n = 1 and n = 2 to make sure the edges work.”
Avoid: changing numbers until the output looks right. Interviewers want to see the reasoning.
A database query inside an inner loop
To build a “frequently bought together” report, code loops over 2,000 products, and for each product loops over its orders, calling the database for every order's line items. The report takes 40 minutes. What's wrong?
The interviewer is checking: do you spot expensive operations multiplied by nested loops?
Show a strong answer
The slow part isn't the loops themselves but the database call in the innermost loop: it runs once for every product × order combination, each with network round-trip time.
- Load the needed data in bulk (one query for all order lines, or a join), then loop in memory.
- Better, let the database aggregate: count co-occurring products with a SQL query, or precompute the report in a nightly batch.
- Measure: time spent waiting on I/O usually dwarfs CPU time in loops.
Avoid: micro-optimising the loop code while the database calls stay inside it.
Matching bank entries with our records
Every night, 2 lakh entries from the bank statement must be matched with 2 lakh payments in our database by transaction ID. A teammate writes two nested loops. Estimate the work and propose a better approach.
The interviewer is checking: can you estimate cost and choose a better data structure?
Show a strong answer
Nested loops mean up to 2 lakh × 2 lakh = 4 × 1010 comparisons: far too slow for a nightly window.
- Put our payments in a HashMap keyed by transaction ID (one pass), then loop over the bank entries once, looking each up: about 4 lakh steps in total.
- Alternatively, sort both lists by ID and walk them together (a merge), which also finds missing entries on either side.
- Report unmatched entries on both sides for the finance team to investigate.
Avoid: starting to code before estimating how much work the approach will do.