Nested Loops & Multidimensional Iteration

A Nested Loop is a control structure where one loop resides completely inside the body of another loop.


1. Mechanics of Nested Loops

In a nested loop:

  1. The outer loop begins its first iteration.
  2. The inner loop executes and completes all of its iterations.
  3. Only after the inner loop finishes completely does the outer loop advance to its second iteration.
  4. This cycle repeats until the outer loop reaches its termination bound.
[Outer Iteration 1]
    ├── [Inner 1]
    ├── [Inner 2]
    └── [Inner 3]
[Outer Iteration 2]
    ├── [Inner 1]
    ├── [Inner 2]
    └── [Inner 3]

Total Inner Body Executions:

$$\text{Total Cycles} = (\text{Outer Iterations}) \times (\text{Inner Iterations})$$

2. Rules for Nested Loops

  1. Independent Identifiers: The outer loop and inner loop must use different counter variables (e.g. Row and Col, or i and j). Re-using the same counter corrupts loop progression.
  2. Proper Nesting Order: The inner loop must be completely closed (NEXT Inner) before the outer loop closes (NEXT Outer). Crossing loop boundaries is a syntax violation.

AI Socratic Tutor

All-Access
Sign in or create an account. AI Tutor is an All-Access benefit.
Sign Up

Need guidance? Ask a question or use the hint below.

AI Socratic Tutor is an All-Access Benefit

Unlock step-by-step Socratic hints, algorithm trace table walkthroughs, and error diagnostics for every Cambridge exercise.

You're chatting with an AI tutor, not a person. AI can make mistakes, so double-check its answers.

Exam-Style Check: Calculate Total Inner Loop Iterations

• Multiple Choice
+25 XP
Question

Consider this nested loop structure:

FOR Outer <- 1 TO 4
    FOR Inner <- 1 TO 5
        OUTPUT "*"
    NEXT Inner
NEXT Outer

How many total asterisks ("*") will be printed when this algorithm completes?

All-Access Required

Interactive exercises for Module 2 and beyond require an active plan.