3. Nested Control Structures

3.2. Nested loops

A nested loop is a loop inside another loop.

  • The outer loop controls the number of times the inner loop runs.

  • The inner loop executes completely for each iteration of the outer loop.

In simple terms:

“For every single pass of the outer loop, the inner loop runs all of its cycles.”

Structure

Here’s the general structure:

Pseudocode:

for (initialization1; condition1; increment1) { # Outer loop for (initialization2; condition2; increment2) { # Inner loop // Code block to execute }

  • Outer loop: Controls the number of times the inner loop executes.

  • Inner loop: Runs completely for each iteration of the outer loop.

Flow of Execution

  1. Outer loop starts its first iteration.

  2. Inner loop executes all its iterations.

  3. Outer loop moves to its next iteration.

  4. Inner loop runs again completely.

  5. Repeat until the outer loop finishes.

Notice that for each value of i, the inner loop completes all iterations of j.

Applications of Nested Loops

  • Printing patterns (triangles, pyramids, etc.)

  • Traversing 2D arrays or matrices

  • Performing repetitive calculations in multiple dimensions

  • Generating combinations or permutations

Points to Remember

  1. Performance: Nested loops can increase time complexity. A loop inside a loop is roughly O(n × m) if outer loop runs n times and inner runs m times.

  2. Readability: Avoid deep nesting (more than 2–3 levels) to keep code readable.

  3. Flexibility: Inner and outer loops can be of different types (for, while, do-while).