Spread the love

Generate the Fibonacci sequence in JavaScript

Fibonacci Sequence

The Fibonacci sequence is a series of numbers where each number (after the first two) is the sum of the two preceding ones. It typically starts with 0 and 1. So the sequence goes:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

JavaScript Example

Below is a JavaScript function that generates the Fibonacci sequence up to a given number of terms:

// Function to generate Fibonacci sequence

function generateFibonacci(n) {
let fibSequence = [0, 1]; // Start the sequence with 0 and 1

for (let i = 2; i < n; i++) {

fibSequence[i] = fibSequence[i - 1] + fibSequence[i - 2];
}
return fibSequence;
}
// Example: Generate the first 10 Fibonacci numbers

const numTerms = 10;
const fibonacciSequence = generateFibonacci(numTerms);
console.log(fibonacciSequence);

Explanation

  1. Initialization:
    • The function generateFibonacci takes one parameter n, which is the number of terms in the Fibonacci sequence you want to generate.
    • It initializes an array fibSequence with the first two Fibonacci numbers: 0 and 1.
  2. Loop:
    • A for loop starts at index 2 and continues until it reaches n.
    • In each iteration, the current Fibonacci number is calculated by adding the previous two numbers in the sequence:
      fibSequence[i] = fibSequence[i - 1] + fibSequence[i - 2];
    • This newly calculated number is then added to the fibSequence array.
  3. Return:
    • After the loop finishes, the function returns the complete Fibonacci sequence up to n terms.
  4. Usage Example:
    • In the example provided, generateFibonacci(10) generates the first 10 Fibonacci numbers, which are then logged to the console.

Output

When you run the code with numTerms set to 10, the output will be:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

This output represents the first 10 terms in the Fibonacci sequence.

Variations

You can modify the generateFibonacci function to start the sequence with different initial values, limit it to numbers below a certain value, or even generate it recursively for educational purposes.


techbloggerworld.com

Nagendra Kumar Sharma I Am Software engineer

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version