Could we help you? Please click the banners. We are young and desperately need the money
Fibonacci is an infinite sequence of numbers. It normally starts with [1, 1].
To calculate the fibonacci numbers you need to add the first number with the number following it.
So that means in the first step we are calculating 1 + 1 = 2
Now we have expanded our sequence of numbers and are now by [1, 1, 2].
To calculate further we need to add the last number to the number next-to-last.
Which means we are calculating now 1 + 2 = 3
Our sequence of number got expanded again and we are now by [1, 1, 2, 3]
We can calculate further but I would like to show you how to do this with loops in JavaScript, so read further.
You can achieve the fibonacci sequence with different loops, but the for loop is by far the most effective.
The procedure inside of the different loops is always the same. Just the different loops are making perfomance differences.
function fibonacciForLoop(fibonacciArray) { // Calculate fibonacci for 100 times in a for-loop for(let i = 0; i < 100 - 2;i++) { let cache = fibonacciArray[i]; let result = cache + fibonacciArray[i+1]; fibonacciArray.push(result); } console.log(`Fibonacci with for loop: ${fibonacciArray}`); }
The while loop is less effective than a for loop but you can achieve the same results.
function fibonacciWhileLoop(fibonacciArray) { let i = 0; while(i < 100 - 2) { let cache = fibonacciArray[i]; let result = cache + fibonacciArray[i+1]; // Push the new result into the array fibonacciArray.push(result); i++; } console.log(`Fibonacci with while loop: ${fibonacciArray}`); }
The do while loop is not often used anymore and is less effective than the while and the for loop. (So I suggest you to don't use this loop)
function fibonacciDoWhileLoop(fibonacciArray) { let i = 0; do { let cache = fibonacciArray[i]; let result = cache + fibonacciArray[i+1]; // Push the new result into the array fibonacciArray.push(result); i++; } while (i < 100 - 2); console.log(`Fibonacci with do while loop: ${fibonacciArray}`); }
You can download a simple project below which contains all loops that are creating the fibonacci sequence:
Fibonacci loops sample
You can see the fibonacci sequence in the nature. For example you can see it in flowers, shells, trees and a lot of more things in the nature. It can also be seen by animals.
The fibonacci sequence is often used in photography to get the perfect positioning of the model or landscape. When the picture is taken with use of the fibonacci sequence it attracts your eye a lot more.