Structured programming notes
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
-
Outer loop starts its first iteration.
-
Inner loop executes all its iterations.
-
Outer loop moves to its next iteration.
-
Inner loop runs again completely.
-
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
-
Performance: Nested loops can increase time complexity. A loop inside a loop is roughly O(n × m) if outer loop runs
ntimes and inner runsmtimes. -
Readability: Avoid deep nesting (more than 2–3 levels) to keep code readable.
-
Flexibility: Inner and outer loops can be of different types (for, while, do-while).