DSA Factory
Free lessonsProgramming basics · Stage 3 · Loops that count · Step 1

Doing it again and again

Repeat some lines for every number in a range, keeping a running total. About 9 minutes.

Say it once, run it many times

Imagine a teacher who makes you write "I will not talk in class" 100 times. You wouldn't want to type it out 100 times in code. A loop says it once and the computer repeats it.

A for loop runs its lines once for every value in a range. In Python, range(1, 6) gives 1, 2, 3, 4 and 5. A box called i takes each value in turn. Watch out: the end of a range is not included, so to reach 5 you write 6.

The end is not included: a range that stops at 6 gives you 1 to 5.
In code
for i in range(1, 6):
    ...   # runs 5 times

A running total

Say you want to add up 1 to 5. Keep a box called total, and start it at zero before the loop begins. On each pass of the loop, add the current number into it.

When the loop ends, the total holds the answer. The box lives outside the loop so that each pass can see what the previous one left behind. If you made the box inside the loop, it would start over on every pass.

Make the total before the loop, so every pass can add to it.
In code
total = 0
for i in range(1, 6):
    total = total + i
Adding 1 to 5
1
0
2
1
3
2
4
3
5
4
i
i
1
total
1

Pass one: i is 1. Add it to the total, which goes from 0 to 1.

Move 1 of 5
Quick check

How many times does for i in range(1, 6) run its lines?

  1. A5 times
  2. B6 times
  3. C4 times
Show the answer

5 times. i takes the values 1, 2, 3, 4 and 5. The end value, 6, is not included.

Your problem

Add up to n

Return the sum of all whole numbers from 1 up to n, including n. The sum can get bigger than an int can hold, so the result is a long.

Example
n = 5 → 15

0 ≤ n ≤ 100,000

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