How to calculate the sum of a range? Using a loop

How can I calculate the sum of all the values in the range between x and y ‚Äč‚Äčthat were output when the function executes so that after each complete loop it repeats decrementing y by one until *y * will not reach x. For example: rangeSum(0, 3); --> result: 10 (0+1+2+3+0+1+2+0+1+0)

I just don't know how to do it because I'm new to JS.

Add Comment
1 Answer(s)
Here is a simple approach using JavaScript `for` loops. We will loop starting from `x` up to `y` and keep reducing `y` by 1 every time the loop completes. We will store all the sums in variable `total`. ```javascript function rangeSum(x, y) { var total = 0; while(y >= x) { for(let i = x; i <= y; i++) { total += i; } y--; } return total; } console.log(rangeSum(0, 3)); // Outputs: 10 ``` In this function `rangeSum`, the outer `while` loop will keep decreasing `y` till `y` is not less than `x`. The inner `for` loop will keep adding `i` to `total` from `x` to `y`. This way you can get the sum of the range of numbers between `x` and `y` inclusive, and repeating the calculation after decrementing `y`. This function should give you the desired output. However, keep in mind that this function has a time complexity of `O(n^2)` due to the nested loops. Practicing with such simple functions will give you a good grasp over loops and conditionals in JavaScript. Happy Coding!
Answered on July 11, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.