DEV Community

Cover image for Day 10: Understanding the Nested `for` Loop in Java
Karthick Narayanan
Karthick Narayanan

Posted on

Day 10: Understanding the Nested `for` Loop in Java

What is a Nested for Loop?

A nested for loop means:

  • A for loop inside another for loop
  • 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
    }
}
Enter fullscreen mode Exit fullscreen mode

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

  1. Outer Loop Initialization
    Outer loop variable is initialized once.

  2. Outer Loop Condition Check
    If condition is true, control enters the loop.

  3. Inner Loop Initialization
    Inner loop variable is initialized.

  4. Inner Loop Condition Check
    If condition is true, inner loop body executes.

  5. Inner Loop Execution
    Code inside the inner loop runs.

  6. Inner Loop Increment
    Inner loop variable is updated.

  7. Inner Loop Ends
    When inner condition becomes false, control returns to outer loop.

  8. Outer Loop Increment
    Outer loop variable is updated.

  9. 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 of print() 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)