Skip to content
Programs · Program 6-16

Q.Program 6-16: Program to demonstrate working of nested for loops.

CBSENCERTSubjective· 3mImportance★★★★★est
51% · 20/39 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Concept understanding — Nested For Loops

Nested For Loops: Loops Inside Loops

Imagine you're a teacher taking attendance in a school with 3 classrooms, each having 5 students. You go to Room 1, call out all 5 names, then move to Room 2, call out all 5 names, then Room 3, call out all 5 names. That's a loop inside a loop — for each classroom, you run through all students.

That's the entire intuition. A nested for loop is simply a for loop placed inside the body of another for loop. The outer loop runs once, and for that single iteration, the inner loop runs completely from start to finish. Then the outer loop moves to its next iteration, and the inner loop runs completely again.


The Precise Statement

for i in range(3):          # outer loop
    for j in range(5):      # inner loop
        print(i, j)

Here's exactly what happens, step by step:

  1. i becomes 0. Enter the inner loop.
  2. j runs through 0, 1, 2, 3, 4 — printing each pair (0,0), (0,1), ..., (0,4).
  3. Inner loop finishes. i becomes 1. Enter the inner loop again.
  4. j runs through 0, 1, 2, 3, 4 again — printing (1,0), (1,1), ..., (1,4).
  5. Inner loop finishes. i becomes 2. Inner loop runs a third time.
  6. j runs through 0, 1, 2, 3, 4 — printing (2,0), ..., (2,4).

Total printed lines: 3×5=153 \times 5 = 15.

Important

The inner loop completes all its iterations for each single iteration of the outer loop. The total number of times the inner body executes is:

(outer iterations)×(inner iterations)(\text{outer iterations}) \times (\text{inner iterations})


Why This Matters

Nested loops are how you work with tables, grids, matrices, and any data that has rows and columns. A 2D list (like a spreadsheet) is naturally processed with one loop for rows and another for columns.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:          # outer: pick a row
    for element in row:     # inner: pick each element in that row
        print(element, end=' ')
    print()                 # new line after each row

Output:

1 2 3 
4 5 6 
7 8 9 

The outer loop selects a row; the inner loop walks across that row's elements. When the inner loop finishes, the outer loop moves to the next row.


Common Mistake …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.