A loop visits every box
Add up every value with one loop. About 6 minutes.
Visit every box, one after another
Think of a shopkeeper totting up a bill: they go down the list, one item at a time, from the first to the last. They never skip one and never count one twice.
A loop does exactly that with an array. It starts at box 0, does something with the value there, moves to box 1, and keeps going until it has visited the last box. Then it stops, before it runs off the end.
total = 0 + 3 = 3
Keep a running total
Before the loop starts, set a total to 0, like clearing a calculator. Each time the loop visits a box, add that box's value to the total. When the loop ends, the total is the sum of everything.
An empty array just means the loop never runs, so the total stays at 0, which is the right answer.
total = 0
for x in nums:
total += x
return totalA loop adds each value of 2, 5, 1 to a total that starts at 0. What's the total when the loop ends?
- A8
- B7
- C0
Show the answer
8. 2 + 5 + 1 = 8. Every box was added once.
Add them up
Return the sum of all the numbers in the list. An empty list adds up to 0.
nums = [3, 1, 4, 1, 5] → 14
0 ≤ n ≤ 1,000 · −1,000 ≤ each value ≤ 1,000