Nested loops: counting iterations and output
Computer Science · Programming fundamentals
Question 1 of 10
0What is the final value of total after this Python code runs? total = 0 for x in range(1, 6): for y in range(1, 6): total += 1
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Nested loops: counting iterations and output explained
A loop repeats a block of statements. When one loop sits inside another, the inner loop runs completely for every single value of the outer loop. The total number of times the innermost statement runs is found by multiplying the counts of the loops, or by adding the counts when the inner loop's range depends on the outer variable.
To count iterations, work out how many times each loop runs. A FOR loop from 1 TO runs times. If the inner loop runs from 1 TO the outer variable, the inner counts are and the total is the sum of those values.
Trace the output by writing down the variable values for the first few passes, then look for a pattern. A variable that is set before the loops and changed inside them keeps its value between passes, so it is often used to count.
Worked example
What is output by this pseudocode?
total ← 0
FOR i ← 1 TO 4
FOR j ← 1 TO i
total ← total + 1
NEXT j
NEXT i
OUTPUT total
- When , the inner loop runs once. When , it runs twice. When , three times, and when , four times.
- The total number of inner iterations is .
- The program outputs .
If the inner loop instead ran from 1 TO 3 for each of 4 outer passes, the total would be .
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What is the final value of steps after this Python code runs? steps = 0 for i in range(2): for j in range(4): steps += 1
Medium
What is the final value of count after this Python code runs? count = 0 for a in range(0, 14, 3): for b in range(0, 12, 3): count += 1
Hard
What is the final value of steps after this Python code runs? steps = 0 for i in range(1, 3): j = 0 while j < i + 2: steps += 1 j += 2