Nested loops: counting iterations and output

Computer Science · Programming fundamentals

Question 1 of 10

0

    What 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.

    Print a free worksheet (PDF)

    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 nn runs nn times. If the inner loop runs from 1 TO the outer variable, the inner counts are 1,2,3,…1, 2, 3, \ldots 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
    
    1. When i=1i = 1, the inner loop runs once. When i=2i = 2, it runs twice. When i=3i = 3, three times, and when i=4i = 4, four times.
    2. The total number of inner iterations is 1+2+3+4=101 + 2 + 3 + 4 = 10.
    3. The program outputs 1010.

    If the inner loop instead ran from 1 TO 3 for each of 4 outer passes, the total would be 4×3=124 \times 3 = 12.

    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