AP CSP Day 49: Nested Iteration - 2D Traversal
Share
Big Idea 3
Day 49 Practice
Focus: Nested Iteration - 2D Traversal
Practice Question
What does this code display?
grid ← [[1,2,3], [4,5,6], [7,8,9]]
count ← 0
FOR EACH row IN grid
{
FOR EACH value IN row
{
count ← count + 1
}
}
DISPLAY(count)Why This Answer?
The nested loops visit every element in the 2D list. 3 rows × 3 columns = 9 elements total. Count increments once per element.
Why Not the Others?
A) This is only the number of rows.
B) This counts only 2 rows.
D) This would be the sum of values, not count.
Common Mistake
Watch Out!
Confusing counting elements with summing values. Count increments regardless of element value.
AP Exam Tip
Nested FOR EACH with 2D lists: outer loop = rows, inner loop = values in each row. Total iterations = rows × columns.