Bonfire Sum All Numbers in a Range - GJSmith3rd/FreeCodeCamp-BootCamp GitHub Wiki
Contact me
Gilbert Joseph Smith III
Github | FreeCodeCamp | CodePen | LinkedIn | Blog/Site | E-Mail
Details
- Difficulty: 2/5
We'll pass you an array of two numbers. Return the sum of those two numbers and all numbers between them.
The lowest number will not always come first.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Useful Links
Problem Script:
function sumAll(arr) {
return 1;
}
sumAll([1, 4]);
Problem Explanation:
- You need to create a program that will take an array of two numbers who are not necessarily in order, and then add not just those numbers but any numbers in between. For example, [3,1] will be the same as
1+2+3and not just3+1
Hint: 1
- Use
Math.max()to find the maximum value of two numbers.
Hint: 2
- Use
Math.min()to find the maximum value of two numbers.
Hint: 3
- Remember to that you must add all the numbers in between so this would require a way to get those numbers.
Spoiler Alert!
Solution ahead!
Code Solution:
function sumAll(arr) {
var max = Math.max(arr[0], arr[1]);
var min = Math.min(arr[0], arr[1]);
var temp = 0;
for (var i=min; i <= max; i++){
temp += i;
}
return(temp);
}
sumAll([1, 4]);
Code Explanation:
- First create a variable to store the max number between two.
- The same as before for the Smallest number.
- We create a temporary variable to add the numbers.
Since the numbers might not be always in order, using max() and min() will help organize.