TypeScript: Generate Fibonacci Series

1. Introduction

The Fibonacci series is a sequence of numbers in which each number after the first two is the sum of the two preceding ones. The sequence begins: 0, 1, 1, 2, 3, 5, 8, 13, ... and so on. In this guide, we'll take a look at a TypeScript program that generates a Fibonacci series of a given length.

2. Program Overview

We'll design a function named generateFibonacci that will take an integer as an argument, which will determine the length of the Fibonacci series. This function will then generate the series and return it as an array of numbers.

3. Code Program

// Function to generate Fibonacci series of a given length
function generateFibonacci(length: number): number[] {
    if (length <= 0) return [];

    let series = [0, 1];
    for (let i = 2; i < length; i++) {
        series.push(series[i - 1] + series[i - 2]);
    }

    return length === 1 ? [0] : series;
}

// Testing the function
const lengthOfSeries = 7;
console.log(`Fibonacci series of length ${lengthOfSeries} is:`, generateFibonacci(lengthOfSeries));

Output:

Fibonacci series of length 7 is: 0,1,1,2,3,5,8

4. Step By Step Explanation

1. We begin by defining the generateFibonacci function that's designed to create a Fibonacci series of a stipulated length.

2. If the provided length is 0 or less, the function will immediately return an empty array.

3. We initialize the Fibonacci series with the first two numbers: 0 and 1.

4. Then, a for-loop is set up to continue generating the Fibonacci sequence. This is accomplished by adding the two most recent numbers in the series to derive the next number.

5. The loop continues until the series reaches the desired length.

6. In case the length is 1, it returns an array with only the first number of the Fibonacci series.

7. For testing purposes, we aim to generate a Fibonacci series of length 7.

8. After invoking the function with the number 7, it produces the series as 0,1,1,2,3,5,8 and displays the output.

Comments