Java Nested Loops & Star/Number Pattern Masterclass
Nested Loop Mechanics ยท Rows vs Columns Coordinate Logic ยท Right Triangle ยท Inverted Triangle ยท Pyramid ยท Diamond ยท Floyd's Triangle ยท Number Pyramids
Mastering multi-dimensional coordinate logic and pattern programming in Java: understanding outer loop (rows) and inner loop (columns) mechanics, building right-angled triangles, inverted pyramids, diamonds, Floyd's numerical triangles, and complex symmetric matrices.
1. Mental Model of Nested Loops (Rows & Columns Matrix)
A Nested Loop is a loop inside another loop.
Whenever the outer loop executes once, the inner loop executes its entire cycle from start to finish:
$$\text{Total Iterations} = \text{Outer Loop Iterations} \times \text{Inner Loop Iterations}$$
+-----------------------------------------------------------------------------------+
| NESTED LOOP COORDINATE MATRIX |
+-----------------------------------------------------------------------------------+
| Outer Loop: Controls the ROWS (Vertical dimension - i = 1 to 5) |
Inner Loop: Controls the COLUMNS / SPACES / STARS (Horizontal dimension - j) Row 1 (i=1): * (Inner loop runs 1 time) Row 2 (i=2): * * (Inner loop runs 2 times) Row 3 (i=3): * * * (Inner loop runs 3 times) Row 4 (i=4): * * * * (Inner loop runs 4 times) Row 5 (i=5): * * * * * (Inner loop runs 5 times)
+-----------------------------------------------------------------------------------+2. The 3-Step Systematic Formula for Any Pattern
To solve any pattern problem in technical interviews, apply this 3-step formula:
1. Step 1 (Outer Loop): Count the total number of horizontal lines/rows ($N$). Set outer loop: for (int row = 1; row <= N; row++).
2. Step 2 (Inner Loops): For each row, identify:
- How many leading spaces are needed? (for (int s = 1; s <= N - row; s++))
- How many characters/stars/numbers are needed? (for (int col = 1; col <= row; col++))
3. Step 3 (Newline): After inner loops finish printing the row elements with System.out.print(), insert a System.out.println() to drop down to the next row.
3. Overview of Iconic Pattern Categories
| Pattern Name | Visual Structure | Core Inner Loop Logic |
|---|---|---|
| Right-Angled Triangle | * |
for (int col = 1; col <= row; col++) print("* ") |
| Inverted Triangle | * * * * |
for (int col = 1; col <= (N - row + 1); col++) print("* ") |
| Symmetrical Pyramid | * |
Spaces: N - row, Stars: 2 * row - 1 |
| Floyd's Triangle | 1 |
Increment running counter count++ inside inner loop |
| Binary (0-1) Triangle | 1 |
Check (row + col) % 2 == 0 ? "1 " : "0 " |
Beginner Example & Code Anatomy
public class Main {
public static void main(String[] args) {
int rows = 5;
// 1. Right-Angled Triangle Pattern
System.out.println("=== 1. Right-Angled Star Triangle ===");
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println(); // Next row
}
// 2. Inverted Right-Angled Triangle
System.out.println("
=== 2. Inverted Star Triangle ===");
for (int i = rows; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// 3. Centered Star Pyramid
System.out.println("
=== 3. Symmetrical Star Pyramid ===");
for (int i = 1; i <= rows; i++) {
// Print leading spaces
for (int space = 1; space <= rows - i; space++) {
System.out.print(" ");
}
// Print odd number of stars (2*i - 1)
for (int k = 1; k <= (2 * i - 1); k++) {
System.out.print("* ");
}
System.out.println();
}
// 4. Floyd's Consecutive Number Triangle
System.out.println("
=== 4. Floyd's Number Triangle ===");
int counter = 1;
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%2d ", counter++);
}
System.out.println();
}
}
}
๐ Line-by-Line Code Explanation
for (int i = 1; i <= rows; i++)
Outer loop controlling vertical row progression from 1 to rows.
for (int j = 1; j <= i; j++) System.out.print("* ");
Inner loop printing stars corresponding to current row index without newline.
System.out.println();
Advances cursor to the beginning of the next line after inner loop completes.
System.out.printf("%2d ", counter++);
Floyd's triangle prints the current counter value and post-increments by 1.
Practical Real-World Example
public class DiamondPatternGenerator {
public static void main(String[] args) {
int n = 4; // Top half height
System.out.println("=== Symmetrical Diamond Pattern (2 * N) ===");
// Part 1: Top Half Pyramid
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++) System.out.print(" ");
for (int j = 1; j <= (2 * i - 1); j++) System.out.print("*");
System.out.println();
}
// Part 2: Bottom Half Inverted Pyramid
for (int i = n - 1; i >= 1; i--) {
for (int s = 1; s <= n - i; s++) System.out.print(" ");
for (int j = 1; j <= (2 * i - 1); j++) System.out.print("*");
System.out.println();
}
}
}
- Using System.out.println() instead of print() inside the inner loop: Prints each star on its own separate line instead of building a horizontal row.
- Forgetting the newline statement System.out.println() after the inner loop: Causes all stars for all rows to blur together onto one single long line.
- Reusing the same variable name in outer and inner loops: "for (int i=0; ...) { for (int i=0; ...) }" causes variable collision compile errors.
Test your understanding by writing the code directly in your editor or running in our online Java compiler:
// Coding Challenge:
// Print a Binary Triangle of 5 rows:
// 1
// 0 1
// 1 0 1
// 0 1 0 1
// 1 0 1 0 1
// Hint: Check if (row + col) is even or odd!
public class Main {
public static void main(String[] args) {
int rows = 5;
// TODO: Print the binary 1/0 pattern
}
}
๐ก Frequently Asked Questions & Interview Insights
โ What is the time complexity of a nested loop of size N x N?
Quadratic time complexity O(N^2). If N = 100, the inner loop executes 10,000 times total.
โ How do you print a hollow square pattern?
Inside inner loop, print star only if (row == 1 || row == N || col == 1 || col == N), otherwise print a blank space.
โ Why are pattern problems asked in Java technical coding interviews?
Pattern problems test your mental models of coordinate mathematics, nested boundary conditions, matrix indexes, and logical loop manipulation without external library crutches.
๐ Quick Chapter Recap
- Nested loops execute outer loop rows and inner loop columns.
- Total iterations = (Outer count * Inner count).
- Use System.out.print() for row elements and System.out.println() for row breaks.
- Symmetric patterns like pyramids and diamonds require calculating leading spaces.