Add up the numbers from 1 to n

“Add them all up”, a White belt challenge from the CurlyScript Dojo. It uses what Grade 5: Loops: Doing Things Over and Over teaches, and 4 tests check your answer.

The challenge

Write sumTo(n) that returns 1 + 2 + 3 + … + n. For 0 or less, return 0.

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • sumTo(3) gives 6
  • sumTo(100) gives 5050
  • sumTo(1) gives 1
  • sumTo(0) gives 0

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

The accumulator pattern: let total = 0; before a loop from 1 to n.

Hint 2

If n is 0, the loop never runs, so the total stays 0.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function sumTo(n) {
  let total = 0;
  for (let i = 1; i <= n; i++) {
    total += i;
  }
  return total;
}

Learn what you need

This exercise uses what Grade 5: Loops: Doing Things Over and Over teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning