Press ESC to close

Fibonacci JavaScript

0 1568

In this lesson we will implement a Fibonacci sequence algorithm in JavaScript.

First of all, remember that the Fibonacci sequence is a sequence of positive integers in which each number, starting with the third, is the sum of the previous two and the first two are 1, 1.

So, for example if I want to see the first 10 terms of the Fibonacci sequence I have: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.

Fibonacci JavaScript – algorithm

Ask in input, through a prompt, how many numbers to calculate and display them one under the other.

To develop this algorithm, first of all we think about the variables that we will need. Surely you need to use two variables to store the first two terms. So, for example, first = 1 and then second = 1.

Then we will need a third variable to store the sum of the first term with the second. So third = first + second.

Well, after having defined this reasoning, we need to repeat some operations.

At the beginning we have this situation: first = 1, second = 1 and third = 1 + 1 = 2.

Then you need to move the value from second to first and the value from third to second, in order to add them together. So: first = 1, second = 2 and third = 3.

Going on with this procedure we will have first = 2, second = 3 and third = 5.

Ultimately we must therefore repeat (iterate some instructions).

Fibonacci JavaScript – algorithm development

Here is a possible solution of the algorithm in JavaScript.

We ask through a prompt how many numbers of the Fibonacci sequence to display. Then we declare the necessary variables and make the assignments.

With a for loop then we repeat the following instructions: c = a + b and then a = b and b = c, i.e. we exchange a with b and b with c.

Here is the complete code of Fibonacci algorithm in JavaScript:



n = prompt('How many numbers do yout want to see?: ');
var a = 1;
var b = 1;
var c;

document.write(a + '
' + b + '
'); for (var i = 0; i< n-2; i++){ c = a + b; a = b; b = c; document.write(c + '
'); }

We can also add an input check on N using for example the do while loop. We therefore ensure that the user enters a number greater than 2.



do {
  n = prompt('How many numbers do yout want to see?: ');
} while (n <= 2);

Similarly, a solution for checking the input could be found using the while.



n = prompt('How many numbers do yout want to see?: ');

while (n <= 2){
     n = prompt('How many numbers do yout want to see?: ');
}

Conclusion

In this lesson we have simply seen an example on the Fibonacci sequence, in the next lessons we will tackle other examples using loops in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

Other stories

JavaScript isNaN

Next Story

Nesting for loops

Previous Story