Nested Loops
Nested loops in Java are loops inside another loop. They are used when a task requires repeated execution within repeated execution, such as matrix processing, pattern printing, and multi-dimensional data handling. This concept is essential for logic building and interviews.
What Are Nested Loops?
- A loop placed inside another loop
- Inner loop executes completely for each outer loop iteration
- Can be any combination of for, while, or do-while
Basic Structure
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println(i + "," + j);
}
}
Execution Flow (Important)
- Outer loop runs first
- For each iteration of outer loop, inner loop runs fully
- Total iterations = (outer loop count × inner loop count)
Example with Execution Count
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
* *
* *
* *
Total executions: Outer = 3, Inner = 2 → 6 executions
Nested for Loop (Most Common)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i + j + " ");
}
System.out.println();
}
Nested while Loop
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 2) {
System.out.println(i + "," + j);
j++;
}
i++;
}
Mixed Nested Loops
for (int i = 1; i <= 2; i++) {
int j = 1;
while (j <= 3) {
System.out.println(i + "," + j);
j++;
}
}
Nested Loops with break
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break;
}
System.out.println(i + "," + j);
}
}
Nested Loops with Labeled break
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer;
}
System.out.println(i + "," + j);
}
}
Nested Loops with continue
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue;
}
System.out.println(i + "," + j);
}
}
Common Use Cases
- Pattern printing
- Matrix operations
- Tables and grids
- Searching in 2D data
- Combinational logic
Performance Consideration (Important)
- Time complexity increases with nesting
- Example: O(n²) for two nested loops
Best Practice: Avoid unnecessary nesting in large datasets.
Common Beginner Mistakes
- Infinite loops due to incorrect inner loop update
- Confusing loop variables
- Excessive nesting reducing readability
- Forgetting braces {}
Interview-Ready Answers
Short Answer
Nested loops are loops placed inside another loop, where the inner loop executes fully for each iteration of the outer loop.
Detailed Answer
In Java, nested loops allow repetitive processing within repeated execution. They are commonly used for matrix handling, pattern generation, and multi-dimensional data processing. However, excessive nesting can impact performance.
Key Takeaway
Nested loops are powerful for multi-level iteration, but should be used carefully to maintain readability and performance.
More Nested Loop Examples (1 to 20)
1. Basic Nested for Loop
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i=" + i + ", j=" + j);
}
}
Explanation
- Outer loop runs 3 times.
- Inner loop runs fully for each outer iteration.
- Total executions: 3 × 3 = 9.
2. Nested Loop Printing a Square Pattern
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print("* ");
}
System.out.println();
}
Explanation
- Inner loop prints stars in one row.
- Outer loop moves to the next row.
- Output:
* * *
* * *
* * *
3. Nested Loop Printing a Right Triangle
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Explanation
- Inner loop runs up to i.
- Forms a right-angled triangle.
- Output:
*
* *
* * *
* * * *
4. Nested Loop Printing Numbers Pattern
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Explanation
- Inner loop prints numbers 1 to 3.
- Repeats for each outer iteration.
5. Nested Loop Multiplication Table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println(i + " * " + j + " = " + (i * j));
}
}
Explanation
- Common real-world example.
- Used in table and matrix logic.
6. Nested Loop with break (Inner Loop Only)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break;
}
System.out.println("i=" + i + ", j=" + j);
}
}
Explanation
breakexits only the inner loop.- Outer loop continues normally.
7. Nested Loop with continue (Inner Loop)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue;
}
System.out.println("i=" + i + ", j=" + j);
}
}
Explanation
- Skips j == 2 only.
- Remaining inner iterations execute.
8. Labeled break in Nested Loop
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break outer;
}
System.out.println("i=" + i + ", j=" + j);
}
}
Explanation
break outerexits both loops.- Useful in deeply nested logic.
9. Labeled continue in Nested Loop
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue outer;
}
System.out.println("i=" + i + ", j=" + j);
}
}
Explanation
- Skips remaining inner loop.
- Continues with next outer iteration.
10. Nested while Loops
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 3) {
System.out.println("i=" + i + ", j=" + j);
j++;
}
i++;
}
Explanation
- Same behavior as nested for.
- Initialization handled manually.
11. Nested do-while Loops
int i = 1;
do {
int j = 1;
do {
System.out.println("i=" + i + ", j=" + j);
j++;
} while (j <= 2);
i++;
} while (i <= 2);
Explanation
- Both loops execute at least once.
- Rare but valid interview case.
12. Nested Loop for 2D Array Traversal
int[][] arr = {
{1, 2},
{3, 4}
};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.println(arr[i][j]);
}
}
Explanation
- Outer loop → rows.
- Inner loop → columns.
13. Nested Loop for Matrix Addition
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] sum = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
Explanation
- Common real-world matrix operation.
- Uses nested loops for row-column access.
14. Nested Loop with Condition on Both Indices
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == j) {
System.out.println("Diagonal: " + i);
}
}
}
Explanation
- Executes logic when i == j.
- Used in diagonal matrix logic.
15. Nested Loop Skipping One Combination
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
continue;
}
System.out.println("(" + i + "," + j + ")");
}
}
Explanation
- Skips only (2,2).
- All other pairs print.
16. Nested Loop for Counting Combinations
int count = 0;
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
count++;
}
}
System.out.println(count);
Explanation
- Total combinations = 3 × 3 = 9.
- Used in complexity analysis.
17. Nested Loop for String Comparison
String[] a = {"A", "B"};
String[] b = {"1", "2"};
for (String x : a) {
for (String y : b) {
System.out.println(x + y);
}
}
Explanation
- Produces all string combinations.
- Output: A1 A2 B1 B2
18. Nested Loop with Flag
boolean found = false;
for (int i = 1; i <= 3 && !found; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 3) {
found = true;
break;
}
}
}
System.out.println(found);
Explanation
- Flag helps control outer loop exit.
- Common interview pattern.
19. Nested Loop for Pyramid Pattern
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Explanation
- Builds increasing numeric pyramid.
- Output:
1
1 2
1 2 3
1 2 3 4
20. Interview Summary Example (Nested Loops)
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println(i + "," + j);
}
}
Explanation
- Output:
1,1
1,2
2,1
2,2
- Demonstrates:
- Outer loop
- Inner loop
- Cartesian combinations
- Very common interview question.