Add up to n

Easy
The course
Number Iteration, Accumulator
1

Understand

Before writing anything, get clear on what is being asked.

Think of it like this

Imagine counting a jar of coins. You do not somehow know the total by looking — you hold a running count in your head, pick up one coin at a time, and add it on. The running count is your variable; picking up each coin is the loop.

This shape — start a total at zero, walk through things one at a time, add each one on — is called an **accumulator**, and you will use it constantly for the rest of the course.

Write a function that adds up every whole number from 1 up to and including n, then gives back the total.

If n is 5, that is 1 + 2 + 3 + 4 + 5, which comes to 15. If n is 0 there is nothing to add, so the answer is 0.

Example 1

Given n = 5

Answer 15

1 + 2 + 3 + 4 + 5 = 15.

Example 2

Given n = 1

Answer 1

Example 3

Given n = 0

Answer 0

There are no numbers to add, so the total stays at 0.

What you can rely on

  • n is 0 or greater
2

Write it

Write the function in the editor, then run it against the examples.

The editor on the right already has the function signature filled in for you. Write your answer inside it and press Run — that checks your code against the examples above only, so you can experiment freely.

Run your code to tick this step off.

Stuck? Take one hint at a time

Each one nudges you a little further. There is no reveal-the-answer button — working it out is the part that actually teaches you.

3

Own it

Submit against every test, then check you can explain why it works.

A running total in a loop

O(n) time · O(1) space
Watching the total build up when n = 5
rounditotal beforetotal after
1101
2213
3336
44610
551015
Start at 0, add each number, return the total
total = 0
for i in range(1, n + 1):
    total += i
return total

Declare the total OUTSIDE the loop. If you create it inside, it gets reset to 0 on every round and you will always get back just the last number.

There is also a formula — n × (n + 1) ÷ 2 — that gets the answer instantly without any loop. It is worth knowing, but write the loop first: recognising when a loop can be replaced by maths is a week-19 skill, and the loop is the idea you need today.

Press Submit to run every test, including the hidden ones.