Nested Loops
Lesson outline
Concept of Nesting
A nested loop is a loop placed inside another loop. The inner loop runs all its iterations for each single iteration of the outer loop.
This is commonly used for 2D arrays, matrices, and grid-based problems.
Matrix Example
Execution flow:
Outer loop (row = 0) → Inner loop runs col = 0, 1, 2
Outer loop (row = 1) → Inner loop runs col = 0, 1, 2
Outer loop (row = 2) → Inner loop runs col = 0, 1, 2
Dependent Inner Loop (Triangles)
Inner-loop bounds can depend on the outer index - useful for triangular patterns:
Multiplication Table
A practical use of nested loops is generating tables:
Order & Locality with 2D Arrays
C++ stores multi-dimensional arrays in row-major order. Iterate rows in the outer loop and columns in the inner loop for better cache locality.
Performance Considerations
Keep the most frequently changing loop innermost for efficiency.
Avoid heavy calculations inside the innermost loop.
Prefer algorithms that reduce work (early exits, pruning) over micro-optimizations.
Common Pitfalls
- Forgetting to reset inner-loop variables when needed
- Off-by-one errors in loop bounds
- Reusing the same loop variable name in inner and outer loops
- Modifying loop bounds inside the loop body unintentionally