Exercise 3 of 30 · beginner · loops · quadratic · nested
A loop inside a loop
The code
pairs = 0
for i in range(n):
for j in range(n):
pairs += 1How many times does the inner statement run?
Count: increments of pairs.
Measured counts
Table
| n | count |
|---|---|
| 8 | 64 |
| 16 | 256 |
| 32 | 1,024 |
| 64 | 4,096 |
| 128 | 16,384 |
| 256 | 65,536 |
| 512 | 262,144 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n²)
- Extra space
- O(1)
- Exact count
- n²
- For each of the n values of i, the inner loop runs n times.
- Nested loops multiply: n × n = n².
Common mistake: Adding the loops (2n). The inner loop restarts for every i.
Check: measured count ÷ (n²) settles near 1.00 for large n.