21
loading...
This website collects cookies to deliver better user experience
We'll pass you an array of two numbers. Return the sum of those two numbers 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.
let arr = [1,2,3,4,5]
let sum = 0;
for(let i = 0; i < arr.length; i++){
// i = 0; 0 < 5; 0++
// i = 1; 1 < 5; 1++
// i = 2; 2 < 5; 2++
// i = 3; 3 < 5; 3++
// i = 4; 4 < 5; 4++
sum += arr[i]
// 1st loop: 0 += 1 = 1
// 2nd loop: 1 += 2 = 3
// 3rd loop: 3 += 3 = 6
// 4th loop: 6 += 4 = 10
// 5th loop: 10 += 5 = 15
}
console.log(sum)
//output: 15
console.log
to create visual representation to display it on your browser's console and see what's happening under the hood.for(let i = 0; i < arr.length; i++){
sum += arr[i]
console.log(sum)
//output: 1
// 3
// 6
// 10
// 15
}
[1, 2, 3, 4]
and get the sum of all the numbers in the array.function sumAll(arr) {
// pass in an array of two numbers
// return the sum of those numbers
// PLUS
// the sum of all numbers between them
// for example...
// [1,4] = 1 + 4 = 5
// [1,2,3,4] = 2 + 3 = 5
// 5 + 5 = 10
// get the lowest value using Math.min()
// get the largest value using Math.max()
let min = Math.min(arr[0], arr[1])
let max = Math.max(arr[0], arr[1])
// create a sum variable
let sum = 0;
// loop through the array
// let i = 1; min < arr.length; min++)
// loops 4 times
for(let i = min; min <= max; min++){
sum+= min
// 0 += 1 = 1
// 1 += 2 = 3
// 3 += 3 = 6
// 4 += 4 = 10
}
return sum;
}
console.log(sumAll([1, 4]));
//output: 10
// get the lowest value using Math.min()
// get the largest value using Math.max()
let min = Math.min(arr[0], arr[1])
let max = Math.max(arr[0], arr[1])
Math.min()
and Math.max()
.let sum = 0;
for loop
that will increment the min
value by 1 and add the min
value to sum
on each iteration.for(let i = min; min <= max; min++){
sum += min;
}
INPUT => PROCESS => OUTPUT
. So we use the return
on sum
and should return 10
return sum;