JavaScript Program to Print the Fibonacci Series

Introduction

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. The sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, .... Fibonacci numbers have many applications in mathematics, computer science, and nature. This program helps print the Fibonacci series up to a specified number of terms.

Problem Statement

Create a JavaScript program that:

  • Accepts a number n (the number of terms in the Fibonacci sequence).
  • Prints the first n terms of the Fibonacci series.

Example:

  • Input: 7

  • Output: 0, 1, 1, 2, 3, 5, 8

  • Input: 10

  • Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Solution Steps

  1. Read the Input: Provide the number n (number of terms) either by user input or directly in the code.
  2. Initialize the First Two Terms: Set the first two terms of the Fibonacci series (0 and 1).
  3. Calculate the Fibonacci Sequence: Use a loop to calculate the remaining terms by summing the two previous terms.
  4. Display the Result: Print the Fibonacci series.

JavaScript Program

// JavaScript Program to Print the Fibonacci Series
// Author: https://www.javaguides.net/

function printFibonacciSeries(n) {
    let n1 = 0, n2 = 1, nextTerm;

    console.log('Fibonacci Series:');
    for (let i = 1; i <= n; i++) {
        console.log(n1);
        nextTerm = n1 + n2;
        n1 = n2;
        n2 = nextTerm;
    }
}

// Example input
let numberOfTerms = 7;
printFibonacciSeries(numberOfTerms);

Output

Fibonacci Series:
0
1
1
2
3
5
8

Example with Different Input

let numberOfTerms = 10;
printFibonacciSeries(numberOfTerms);

Output:

Fibonacci Series:
0
1
1
2
3
5
8
13
21
34

Explanation

Step 1: Initialize the First Two Terms

  • The first two terms of the Fibonacci series are initialized as n1 = 0 and n2 = 1.

Step 2: Calculate the Fibonacci Sequence

  • A for loop is used to iterate through the series. The next term is calculated as the sum of the two preceding terms (nextTerm = n1 + n2).
  • The values of n1 and n2 are updated after each iteration to continue generating the next terms.

Step 3: Display the Result

  • The terms of the Fibonacci series are printed to the console using console.log().

Conclusion

This JavaScript program demonstrates how to generate and print the Fibonacci series up to a specified number of terms. By using a simple loop and updating the terms dynamically, the program efficiently computes the Fibonacci sequence. This solution can be extended to handle more advanced Fibonacci-related problems or larger numbers of terms.

Comments