Back to Freecodecamp

Design a Sum All Numbers Algorithm

curriculum/challenges/english/blocks/lab-sum-all-numbers-algorithm/a3566b1109230028080c9345.md

latest1.3 KB
Original Source

--description--

In this lab, you will need to design a sum all numbers algorithm.

Objective: Fulfill the user stories below and get all the tests to pass to complete the lab.

User Stories:

  1. You should have a function named sumAll that accepts an array of two numbers.
  2. sumAll([n, m]) should return the sum of n and m plus the sum of all the numbers between them. The lowest number will not always come first. For example, sumAll([4,1]) should return 10 because sum of all the numbers between 1 and 4 (both inclusive) is 10.

--hints--

You should have a function named sumAll.

js
assert.isFunction(sumAll);

sumAll([1, 4]) should return a number.

js
assert.isNumber(sumAll([1, 4]));

sumAll([1, 4]) should return 10.

js
assert.equal(sumAll([1, 4]), 10);

sumAll([4, 1]) should return 10.

js
assert.equal(sumAll([4, 1]), 10);

sumAll([5, 10]) should return 45.

js
assert.equal(sumAll([5, 10]), 45);

sumAll([10, 5]) should return 45.

js
assert.equal(sumAll([10, 5]), 45);

--seed--

--seed-contents--

js

--solutions--

js
function sumAll(arr) {
  let sum = 0;
  
  arr.sort((a, b) => a - b);

  for (var i = arr[0]; i <= arr[1]; i++) {
    sum += i;
  }

  return sum;
}