Java Notes
Complete guide to nested loops in Java covering nested for, while, do-while loops, pattern printing, matrix operations, multiplication tables, time complexity analysis, and optimization techniques.
What are Nested Loops?
A nested loop is a loop placed inside another loop. The inner loop executes completely for each single iteration of the outer loop. This creates a multiplication effect — if the outer loop runs m times and the inner loop runs n times, the inner body executes m × n times total.
Analogy
Think of a clock:
- Hour hand (outer loop): moves through 12 positions
- Minute hand (inner loop): completes 60 positions for EACH hour position
- Total minute ticks: 12 × 60 = 720
Execution Flow
Outer loop iteration 1
Inner loop iteration 1, 2, 3, ..., n (complete inner loop)
Outer loop iteration 2
Inner loop iteration 1, 2, 3, ..., n (complete inner loop again)
Outer loop iteration 3
Inner loop iteration 1, 2, 3, ..., n (complete inner loop again)
...
Outer loop iteration m
Inner loop iteration 1, 2, 3, ..., n (complete inner loop last time)
Total inner body executions = m × n
Basic Nested for Loop
(1,1) (1,2) (1,3) (1,4) (2,1) (2,2) (2,3) (2,4) (3,1) (3,2) (3,3) (3,4)
Dry Run:
- i=1: j goes 1→4 (4 prints), then newline
- i=2: j goes 1→4 (4 prints), then newline
- i=3: j goes 1→4 (4 prints), then newline
- Total prints: 3 × 4 = 12
Nested while Loop
1 2 3 2 4 6 3 6 9
Multiplication Table (1 to 10)
MULTIPLICATION TABLE (1-10)
=====================================================================================
| 1 2 3 4 5 6 7 8 9 10
-------------------------------------------------------------------------------------
1 | 1 2 3 4 5 6 7 8 9 10
2 | 2 4 6 8 10 12 14 16 18 20
3 | 3 6 9 12 15 18 21 24 27 30
4 | 4 8 12 16 20 24 28 32 36 40
5 | 5 10 15 20 25 30 35 40 45 50
6 | 6 12 18 24 30 36 42 48 54 60
7 | 7 14 21 28 35 42 49 56 63 70
8 | 8 16 24 32 40 48 56 64 72 80
9 | 9 18 27 36 45 54 63 72 81 90
10 | 10 20 30 40 50 60 70 80 90 100Pattern Programs
Pattern 1: Right Triangle Star Pattern
* * * * * * * * * * * * * * *
Logic: Row i has exactly i stars.
Pattern 2: Inverted Right Triangle
* * * * * * * * * * * * * * *
Pattern 3: Pyramid Pattern
* *** ***** ******* *********
Logic: Row i has (n-i) spaces and (2i-1) stars.
Pattern 4: Diamond Pattern
*
***
*****
*******
*********
*******
*****
***
*Pattern 5: Number Triangle
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Pattern 6: Floyd's Triangle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Pattern 7: Pascal's Triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1Pattern 8: Butterfly Pattern
* * ** ** *** *** ******** ******** *** *** ** ** * *
Pattern 9: Hollow Rectangle
* * * * * * * * * * * * * * * * * * * * * *
Pattern 10: Alphabet Pattern
A A B A B C A B C D A B C D E
Time Complexity of Nested Loops
Understanding how nested loops affect time complexity is crucial for writing efficient programs.
O(n²) — Two Nested Loops
O(n²/2) = O(n²) — Triangular Iteration
O(n³) — Three Nested Loops
O(n × m) — Different Bounds
Counting Iterations
Standard (n×n): 25 Triangular: 15 Inner halving (n×logn): 15
Nested Loop with break and continue
Finding first pair where i + j = 7: Found: (2, 5)
Practical Applications
Application 1: Bubble Sort (Adjacent Swap)
Sorted: [11, 12, 22, 25, 34, 64, 90]
Application 2: Finding Duplicate Pairs
Duplicate values: 3 at indices 0 and 9 1 at indices 1 and 3 5 at indices 4 and 8
Common Mistakes
1. Using Same Variable in Both Loops
2. Wrong Loop Bounds Causing Extra/Missing Iterations
3. Modifying Outer Loop Variable Inside Inner Loop
4. Forgetting Newline After Inner Loop
5. O(n²) When O(n) Is Possible
Best Practices
- Minimize the work inside the innermost loop — every operation is multiplied
- Use break early to avoid unnecessary iterations when possible
- Consider time complexity — nested loops often give O(n²) or worse
- Use meaningful variable names —
row/colinstead ofi/jfor matrices - Trace through small inputs before coding — draw the pattern on paper
- Look for patterns — inner loop bound often depends on outer variable
- Separate concerns — use helper methods for complex inner logic
- Avoid deep nesting (>3 levels) — refactor into methods
- Initialize inner variables inside the outer loop if they need resetting
- Test with edge cases — n=0, n=1, and large n for performance
Interview Questions
Q1: How many times does the inner statement execute in nested loops of n and m? n × m times. If both are n, it's n².
Q2: What is the time complexity of three nested loops each running n times? O(n³). Each additional nested loop multiplies by n.
Q3: Can you nest different types of loops? Yes. You can nest for inside while, do-while inside for, etc. Any combination is valid.
Q4: How do you break out of multiple nested loops? Use a labeled break (break label;), a boolean flag checked in outer loop condition, or extract into a method and use return.
Q5: What is the output of this nested loop?
Answer: Prints decreasing rows: "1 2 3 4 5", "1 2 3 4", "1 2 3", "1 2", "1"
Q6: Why are nested loops inefficient for large inputs? Because time grows quadratically (or worse). For n=1000, O(n²) = 1 million operations. For n=1 million, O(n²) = 1 trillion — impossibly slow.
Q7: How do you optimize nested loops? Reduce iterations with break, precompute values outside inner loop, use better algorithms (sorting, hashing), or restructure to avoid nested loops entirely.
Q8: What is the difference between O(n²) and O(n log n)? For n=1000: n²=1,000,000 vs n·log(n)≈10,000. For n=1,000,000: n²=10¹² vs n·log(n)≈20,000,000. The difference grows enormously.
Q9: Can nested loops be replaced with recursion? Sometimes yes, but recursion has stack overhead. Pattern problems often use recursion as an alternative. Neither is universally better.
Q10: How do you print a right-aligned triangle? Use spaces before stars: inner loop 1 prints (n-i) spaces, inner loop 2 prints i stars.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Nested Loops in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, control, statements
Related Java Master Course Topics