Beginner
Nested Loops and Loop Patterns
📂 Phase 2: Control Flow & Data (Days 6–10) · JavaA nested loop is simply a loop placed inside another loop. The inner loop completes all of its iterations for every single iteration of the outer loop — this is the foundation for working with grids, matrices, and pattern printing.
Basic Nested Loop Structure
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // runs 2 times
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // runs 2 × 3 = 6 times total
}
}
For every single pass of the outer loop, the inner loop runs completely from start to finish before control returns to the outer loop.
Classic Use Case: Multiplication Table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + " ");
}
System.out.println(); // moves to next line after each row
}
// Output:
// 1 2 3
// 2 4 6
// 3 6 9
Pattern Printing — A Common Interview Warm-Up
// Right-angled triangle of stars
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
Time Complexity of Nested Loops
If the outer loop runs n times and the inner loop runs m times for each outer pass, the total number of inner-loop executions is n × m. When both loops run over the same input size n, this gives O(n²) time complexity — a key concept that resurfaces constantly in DSA when analyzing brute-force algorithms.
Interview tip: Pattern-printing questions (triangles, pyramids, diamonds) are common in early technical screening rounds specifically to test comfort with nested loop logic — practice a few different shapes, not just triangles.