Nested loops and pattern printing

Put a loop inside another loop and you can work in two dimensions: rows and columns, stores and weeks, seats in a bus. Nested loops are also behind every star-pattern question in campus tests. You'll learn exactly how the two loops take turns, a simple method that cracks any pattern, why nested loops slow down on big data, and then practise with 13 problems.

Module 3 · Control Flow⏱ 22 minBeginner13 practice problems
1 The story

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.

row 1row 2row 3row 4 outer loop:which row? inner loop: tables in this row for (row = 1; row <= 4; row++) { for (t = 1; t <= row; t++) print("T"); println(); } myphatshala.in
Riya

Sir, one loop goes down the rows. But how do I print a different number of tables in each row?

Arjun Sir

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.

Riya

So the inner loop runs completely, from start to finish, every time the outer loop takes one step?

Arjun Sir

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.

2 Definition

What is a nested loop?

Formal definition (write this in exams)

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.

In simple words

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

Outer loopThe loop on the outside; usually controls rows.
Inner loopThe loop inside; usually controls columns or items in a row.
Dependent limitAn inner limit that uses the outer variable, like col <= row.
PatternA shape printed with characters, decided row by row.
O(n²)Work that grows with the square of the input size, typical of two nested loops.
TraversalVisiting every cell of a grid or table.

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 variablesUse different names (row/col or i/j); the inner one is recreated each outer iteration
println placementAfter 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.

3 Types and ways to use 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 printsInner loop(s)
*
**
***
****
r starsc <= r
****
***
**
*
n − r + 1 starsc <= n - r + 1
   *
  ***
 *****
*******
n − r spaces, then 2r − 1 starsTwo inner loops
1
12
123
1234
the numbers 1..rprint c
1
22
333
4444
r, r timesprint 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 × columns

All pairs

Comparing every item with every other: duplicates, matching pairs, distances between delivery points.

i, j > i

Group then item

For each store, each order; for each class, each student; for each month, each day.

Hierarchies

Performance: 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.

4 Step by step

Cracking a pattern: the centred pyramid

  1. Draw it and number the rows

       *
      ***
     *****
    *******
    The outer loop will run once per row: for (int row = 1; row <= n; row++).
  2. 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.
  3. Write one inner loop per column of the table

    for (int s = 1; s <= n - row; s++) System.out.print(" ");
    for (int st = 1; st <= 2 * row - 1; st++) System.out.print("*");
    Both inner loops run, one after the other, inside each outer iteration. Their variables are recreated every row.
  4. End the row

    System.out.println();
    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.
  5. 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.
5 See it happen

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.

Printing a triangle with n = 4 6 steps
What you see for row 1..4 { for col 1..row print("*"); println(); } * ** *** **** row 1 → 1 starrow 2 → 2 starsrow 3 → 3 starsrow 4 → 4 starstotal 10 prints n × n workn = 10 → 100n = 1,000 → 10 lakhn = 1,00,000 →1,000 crore row = 1: inner loop runs once, then println. row = 2: inner loop runs twice. row = 3: three times. row = 4: four times. The outer loop then ends. 1 + 2 + 3 + 4 = 10 = n(n + 1) / 2 Nested loops grow fast on big inputs. myphatshala.in
Behind the screen Every (row, col) the inner body sees (1,1) (2,1)(2,2) (3,1)(3,2)(3,3) (4,1)(4,2)(4,3)(4,4) OUTER: row <= 4 ? else → END col = 1 INNER: col <= row ? else → NL print("*"); col++; goto INNER NL: println(); row++; goto OUTER END: col goes 1 → stops at 2 because 2 > row (1). col restarts at 1 for every new row. The limit col ≤ row makes each row longer. 10 cells: a triangle in the (row, col) table. Two loops = two backward jumps, one inside the other. The inner jump runs far more often than the outer one. myphatshala.in
6 Real-world use

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.

Outer loop: rows. Inner loop: seats. 6 steps
Animated example for (row A..C) for (seat 1..4) print(row+seat) SCREEN A1 A2 A3 A4 A B1 B2 B3 B4 B C1 C2 C3 C4 C empty map: 3 rows × 4 seats row A: inner loop runs 4 times row B: inner loop starts again at 1 B3, B4 → row B done row C: 4 more → 12 prints total = 3 × 4 = 12 iterations myphatshala.in

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.

Rows→for row { for seat }→Seat map on screen

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.

Stores × weeks→nested loops + totals→Summary table

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.

Pixels→for y { for x { adjust } }→Edited photo

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.

Drivers × orders→pairwise distance→Nearest driver
for class:for student:sendReport()

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.

Branches→for branch { for account }→Statements

Examples are simplified to show where nested loops fit. Large systems use indexes and databases to avoid comparing everything with everything.

7 Run the code

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.
8 Line by line

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.

Example 1Events · seating

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.

Input
3 rows, 4 seats
Expected output
A1 A2 A3 A4 
B1 B2 B3 B4 
C1 C2 C3 C4

Approach

  1. Outer loop over rows, inner loop over seats.
  2. Row letter: (char) ('A' + r).
  3. print inside, println after 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.

Example 2Retail · weekly report

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.

Input
Pune {1200, 950, 1800}; Nashik {700, 1100, 640}
Expected output
Pune: Rs 3950
Nashik: Rs 2440
All stores: Rs 6390

Approach

  1. Outer loop over stores, inner loop over days.
  2. Reset storeTotal for each store.
  3. 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.

Example 3Printing · patterns

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.

Input
4 rows
Expected output
1 
1 2 
1 2 3 
1 2 3 4

Approach

  1. Outer loop i from 1 to 4.
  2. Inner loop j from 1 to i.
  3. 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.

9 Quiz and revision

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.

P1Easy

Square of stars

Print an n × n square of stars.

Input
n = 4
Expected output
****
****
****
****
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.

P2Easy

Number triangle

Print rows where row r contains the numbers 1 to r.

Input
n = 5
Expected output
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();
        }
    }
}
1 12 123 1234 12345

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.

P3Easy

Inverted triangle

Print a triangle of stars that gets shorter on each row.

Input
n = 4
Expected output
****
***
**
*
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.

P4Easy

Multiplication grid

Print a 5 × 5 multiplication grid with neatly aligned columns.

Input
size = 5
Expected output
   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();
        }
    }
}
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

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.

P5Medium

Centred pyramid

Print a pyramid of stars centred on the last row: row r has (n − r) leading spaces and (2r − 1) stars.

Input
n = 4
Expected output
   *
  ***
 *****
*******
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.

P6Medium

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.

Input
n = 4
Expected output
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();
        }
    }
}
1 2 3 4 5 6 7 8 9 10

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.

P7Medium

Diamond

Print a diamond of stars with n rows in the top half (the middle row is the widest).

Input
n = 3
Expected output
  *
 ***
*****
 ***
  *
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.

P8Medium

Pascal's triangle

Print the first n rows of Pascal's triangle, where each number is the sum of the two above it.

Input
n = 5
Expected output
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);
        }
    }
}
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

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.

P9Medium

Hollow square

Print an n × n square where only the border is made of stars.

Input
n = 5
Expected output
*****
*   *
*   *
*   *
*****
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.

P10Medium

All primes up to 50

Print every prime number from 2 to 50 using nested loops.

Input
limit = 50
Expected output
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());
    }
}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

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.

P11Business problem

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.

Input
Kharghar: 42 38 51 47
Vashi:    55 60 49 58
Panvel:   31 29 35 40
Expected output
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);
    }
}
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

How it works:

  1. The outer loop walks stores (rows), the inner loop walks weeks (columns): a classic grid traversal. 2D arrays are covered in Lesson 4.2.
  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.
  3. %-9s left-aligns names in 9 characters and %4d right-aligns numbers, so the table lines up like a spreadsheet.
  4. The grand total equals both the sum of row totals and the sum of column totals, a handy self-check in real reports.
P12Business problem

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.

Input
prices: Mug 199, Diary 301, Pen set 250,
Bottle 280, Planner 220, Lamp 250
Expected output
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");
    }
}
Mug + Diary = Rs 500 Pen set + Lamp = Rs 500 Bottle + Planner = Rs 500 3 combination(s) found

How it works:

  1. Starting the inner loop at i + 1 checks every pair exactly once and never pairs a product with itself.
  2. 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.
  3. Two products with the same price (Pen set and Lamp) are still different items, so both appear as a valid pair.
P13Business problem

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.

Input
booked = 1A, 1B, 2C, 3D, 4A, 4B, 4C, 4D, 6B
Expected output
 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");
    }
}
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

How it works:

  1. 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.
  2. 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.
  3. The aisle is drawn by a condition on the column index, not by a separate loop.
  4. 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.

CRM · data cleaning1–3 years

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.

Campus test · patternsFresher

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
  1. “I numbered the rows 1 to n and wrote a table: for each row, the number of spaces and stars.”
  2. “For n = 4, spaces were 3, 2, 1, 0, so n - row; stars were 1, 3, 5, 7, so 2 * row - 1.”
  3. “The outer loop goes over rows; inside it, one loop prints spaces, a second prints stars, then println.”
  4. “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.

E-commerce · recommendations1–3 years

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.

Fintech · reconciliation1–3 years

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.