Skip to content
Advertisement

Sum of the integers from 1 to n

I’m trying to write a program to add up the numbers from 1 to n. I’ve managed to get it to print the numbers several times but not to add them all. It keeps on just adding two of the numbers.

My 1st attempt is:

JavaScript

How can I fix this problem?


For the recursive version of this question, see Recursive function to calculate sum of 1 to n?

Advertisement

Answer

You need 2 different variables in your code — a variable where you can store the sum as you iterate through the values and add them (my_sum in my code), and another variable (i in my code) to iterate over the numbers from 0 to n.

JavaScript

You are using the my_sum variable in your code to both store the sum and iterate through the numbers.

Advertisement