# Generating the Fibonacci sequence

The Fibonacci sequence is a sequence of numbers where the next term is the sum of the previous two terms. The first two terms are defined to be 0 and 1.

This JavaScript function generates up to 1000 terms of the Fibonacci sequence and stores them in an array. The result is then displayed to the user.

### The HTML code needed

The HTML consists of three elements:

• An input field where the user enters how many terms they wish to generate
• An input button which will calls the JavaScript function 'generateFibonacci' when pressed
• A paragraph with id 'sequence' to display the result

Copy this code into the body section of your HTML document.

 <input id="terms"> <input type="button" value="Generate Fibonacci Sequence" onclick="generateFibonacci(document.getElementById('terms').value)"> <p id="sequence">    Enter the number of terms you wish to generate.    Minimum 2, maximum 1000 terms. </p> 

### The JavaScript function used to generate the sequence

The function accepts as parameter for the total number of terms to generate and checks this is between 2 and 1000. An array is created and the first two elements are defined to be 0 and 1.

A while loop then runs adding the previous two terms together and storing this as the next element in the array. This continues until the required number of terms is generated.

Finally the array is looped through and displayed to the user in the 'sequence' paragraph element.

 <script> function generateFibonacci(totalTerms) {    // Check the totalTerms is a number between 2 and 1000.    if (isNaN(totalTerms) || totalTerms > 1000 || totalTerms < 2) {       document.getElementById('sequence').innerHTML = "Please enter a number from 2 to 1000.";       return;    }    // Creeate an array to store the sequence and set the first two elements to 0 and 1.    var F = new Array();    F = 0;    F = 1;    // Loop through creating the next term by adding the previous two together.    var currentTerm = 2;    while (currentTerm < totalTerms) {       F[currentTerm] = F[currentTerm - 1] + F[currentTerm - 2];       currentTerm += 1;    }    // Finally display the array to the user.    document.getElementById('sequence').innerHTML = "The first " + totalTerms + " terms of the Fibonacci sequence are ";    for (var i = 0; i < totalTerms; i++) {       document.getElementById('sequence').innerHTML += F[i] + ", ";    } } </script> 

### Use the code to generate terms of the Fibonacci sequence

See the JavaScript function in action below. Generate between 2 and 1000 terms of the Fibonacci sequence.

Enter the number of terms you wish to generate. Minimum 2, maximum 1000 terms.