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.
It prints
What the tests check
sumTo(3)gives6sumTo(100)gives5050sumTo(1)gives1sumTo(0)gives0
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
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.