Created
September 25, 2016 18:42
-
-
Save mojenmojen/075a186c064b07b9f09cbbfa62cba13f to your computer and use it in GitHub Desktop.
Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end. Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55. As a bonus assignment, modify your…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// range function | |
function range( start, end, increment ) { | |
// create the result array | |
var result = []; | |
// test to see if we have an increment, otherwise set it to 1 | |
if ( increment == undefined ) | |
increment = 1; | |
// calculate the number of times to loop (this is because you might be going | |
// up or down with your increment) | |
numLoops = Math.abs( (end - start)/ increment ) + 1 ; | |
// loop that many times | |
for ( var i = 0; i < numLoops; i ++ ) { | |
// add (push) the value of start to the array | |
result.push( start ); | |
// increment the value of start | |
start += increment; | |
} | |
// return the array with all the things in it | |
return result; | |
} | |
function sum( numArray ) { | |
// set a variable to hold the sum | |
var arrayTotal = 0; | |
// see how many numbers are in the array | |
numLoops = numArray.length; | |
// loop that many times | |
for ( var i = 0; i < numLoops; i ++ ) { | |
// add the number at that index to the sum | |
arrayTotal += numArray[i]; | |
} | |
// return the sum | |
return arrayTotal; | |
} | |
console.log(range(1, 10)); | |
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
console.log(range(5, 2, -1)); | |
// → [5, 4, 3, 2] | |
console.log(sum(range(1, 10))); | |
// → 55 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment