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.

Independent Practice: A multiplication grid

+30 XP

Read a row count and column count, both from 1 to 4. Output each row-by-column product in row order, one number per line.

Write a complete program. Read inputs in the stated order. Output only the requested results, one per line, without input prompts. Test with your own values before submitting.

solution.pseudo
All-Access Required

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

โ—‹ Two by three
โ—‹ One by four
โ—‹ Three by one