What is a Nested for Loop?
A nested for loop means:
- A
forloop inside anotherforloop - The outer loop controls rows
- The inner loop controls columns
- Used when a task requires multiple levels of repetition
Syntax of Nested for Loop
for (initialization; condition; increment/decrement) {
for (initialization; condition; increment/decrement) {
// code to be executed
}
}
How a Nested for Loop Works
- Outer loop runs first
-
For each outer loop iteration:
- Inner loop runs completely
-
After inner loop finishes:
- Control goes back to outer loop
Process continues until outer loop ends
Order of Execution in a Nested for Loop
Outer Loop Initialization
Outer loop variable is initialized once.Outer Loop Condition Check
If condition is true, control enters the loop.Inner Loop Initialization
Inner loop variable is initialized.Inner Loop Condition Check
If condition is true, inner loop body executes.Inner Loop Execution
Code inside the inner loop runs.Inner Loop Increment
Inner loop variable is updated.Inner Loop Ends
When inner condition becomes false, control returns to outer loop.Outer Loop Increment
Outer loop variable is updated.Repeat
Steps repeat until outer loop condition becomes false.
Important Point to Note
- Inner loop runs completely for each iteration of the outer loop
- Total executions =
outer loop count × inner loop count - Nested loops increase time complexity
Key Points
- Used for patterns, tables, and matrix problems
- Outer loop controls rows
- Inner loop controls columns
- Most common in star patterns
* Needs careful control to avoid performance issues
Common Mistakes to Avoid
- Forgetting to reset inner loop variable
- Using wrong loop conditions
- Printing
println()instead ofprint()inside inner loop - Creating infinite loops accidentally
- Too many nested loops causing slow performance
When to Use Nested for Loops?
Use nested for loops when:
- Working with rows and columns
- Printing patterns
- Handling tables or matrices
- Performing repeated combinations
Top comments (0)