RareComputer science
What does the loop that adds the integers from 1 through 5 print?
Short answer
15
Exercise
s = 0
for k in range(1, 6):
s += k
print(s)
Solution
1 + 2 + 3 + 4 + 5 = 15
The upper endpoint of range is excluded, making five the final term. Starting from zero, s holds the sum of all values of k processed so far. The print statement is outside the loop, so only the final total appears.
k: 1 → 2 → 3 → 4 → 5. s: 0 → 1 → 3 → 6 → 10 → 15. (1 + 5) + (2 + 4) + 3 = 15.
Trace the instructions in order. A test reads the current values, an assignment replaces a value, and output uses the value present when execution reaches it. Recording each new state makes the result checkable.
Platforms
- MAXIMUM
