Last active
May 1, 2018 18:31
-
-
Save MorenoMdz/b4c7d4299dd77d6c60e7f73cf85a1a09 to your computer and use it in GitHub Desktop.
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
// This challenge requires you to add up all the numbers from 1 to a given argument. For example, if the parameter num is 4, your program should add up 1 + 2 + 3 + 4 and return 10. This will be pretty simple to write out as a loop. We'll maintain a variable and keep adding to it as we loop from 1 to num. | |
function SimpleAdding(num) { | |
let sum = 0; | |
for (i = 0; i <= num; i++) { | |
sum = sum + i; | |
} | |
return sum; | |
} | |
/* More complete */ | |
function SimpleAdding2(num) { | |
// code goes here | |
if (num < 1) return NaN; | |
else if (num === 1) return 1; | |
return SimpleAdding(num - 1) + num; | |
} | |
/* Appending */ | |
function SimpleAdding3(num) { | |
let answer = 0; | |
for (let i = 0; i <= num; i++) { | |
answer += i; | |
} | |
return answer; | |
} | |
/* Array (way overengineered) */ | |
function SimpleAdding(num) { | |
var numbers = []; | |
for(i=1;i<=num;i++){numbers.push(i);} | |
var init = numbers[0] + numbers [1]; | |
for(i=2;i<numbers.length;i++){init = init + numbers[i];} | |
return init; | |
} | |
/* Simple */ | |
function SimpleAdding(num) { | |
if(num === 1){ | |
return 1; | |
} | |
return num + SimpleAdding(num - 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment