Last active
February 24, 2021 18:25
-
-
Save jcolebot/db240b23922fdf83ebca54c7e446e0a5 to your computer and use it in GitHub Desktop.
Fibonacci Sequence solution using a for loop in JavaScript. Sequence grows by adding the sum of the two numbers that precede it. Remember to change the value of "n" when calling the function based on how long you want the sequence to be.
This file contains hidden or 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
| function fibonacciGenerator(n) { | |
| var fibArray = []; //create empty array to push sequence into | |
| if (n == 1) { | |
| fibArray = [0]; //sets first element to 0 | |
| } | |
| else if (n == 2) { | |
| fibArray = [0, 1]; //sets second element to 1 | |
| } | |
| else { | |
| fibArray = [0, 1]; //if n is more than 2, following loop will begin | |
| for (var i = 2; i < n; i++) { | |
| fibArray.push(fibArray[fibArray.length - 2] + fibArray[fibArray.length - 1]); //adds the previous 2 elements together and pushes it into the array. | |
| } | |
| } | |
| return fibArray; | |
| } | |
| fibArray = fibonacciGenerator(n); | |
| console.log(fibArray); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment