DSA Factory
Free lessonsArrays · Stage 1 · Traversal · Step 1

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.

From box 0 to the last box: every box visited exactly once.
Stop at the length: there's no box with that number.
Add as you go
3
0
1
1
4
2
1
3
5
4
i

total = 0 + 3 = 3

Move 1 of 5

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.

Start at 0, before the loop: then add one value per visit.
In code
total = 0
for x in nums:
    total += x
return total
Quick check

A loop adds each value of 2, 5, 1 to a total that starts at 0. What's the total when the loop ends?

  1. A8
  2. B7
  3. C0
Show the answer

8. 2 + 5 + 1 = 8. Every box was added once.

Your problem

Add them up

Return the sum of all the numbers in the list. An empty list adds up to 0.

Example
nums = [3, 1, 4, 1, 5] → 14

0 ≤ n ≤ 1,000 · −1,000 ≤ each value ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding