How can you help?
You can support by buying a coffee ☕️
Follow me on Github
Follow me on Twitter
Instructions
Task:
our task is to make function, which returns the sum of a sequence of integers.
The sequence is defined by 3 non-negative values: begin, end, step (inclusive).
If begin value is greater than the end, function should returns 0
Examples
2,2,2 --> 2
2,6,2 --> 12 (2 + 4 + 6)
1,5,1 --> 15 (1 + 2 + 3 + 4 + 5)
1,5,3 --> 5 (1 + 4)
My solution:
const sequenceSum = (begin, end, step) => {
var count = 0;
for (let i = begin; i <= end; i += step) {
count += i;
}
return count;
};
Explanation
First I made the variable count, in which I'll save the results of the sums in the loop
var count = 0;
Then I used a for loop, in which I started with the value of the begin param, it will iterate until the "i" value is equal to the end value, and in each iteration the "i" value will be summed the "step" param value.
And in each iteration I summed the "i" value to count
for (let i = begin; i <= end; i += step) {
count += i;
}
At the end I just returned count
return count;
What do you think about this solution? 👇🤔
Top comments (0)