C++ Program to Display Fibonacci Series

Source Code

#include <iostream>

using namespace std;

int main()
{
    int n; // Declare a variable to hold the number of terms

    cout << "Enter the number of terms: "; // Prompt the user to enter the number of terms
    cin >> n; // Read the number of terms from the standard input stream

    int a = 0, b = 1; // Declare variables to hold the current and previous terms, and initialize them to 0 and 1, respectively

    // Display the Fibonacci series
    for (int i = 1; i <= n; i++)
    {
        cout << a << " "; // Print the current term

        int temp = a; // Save the current term in a temporary variable
        a = b; // Update the current term to the previous term
        b = temp + b; // Update the previous term to the sum of the current and previous terms
    }

    return 0;
}

Code Explanation

This program declares a variable n of type int to hold the number of terms entered by the user, and variables a and b of type int to hold the current and previous terms of the Fibonacci series, respectively. It then uses the cout object to print a prompt asking the user to enter the number of terms, and the cin object to read the number of terms from the standard input stream.

To generate the Fibonacci series, the program uses a for loop to iterate over the range [1, n] and calculate the current and previous terms of the series on each iteration. The loop variable i is initialized to 1, and the loop continues as long as i is less than or equal to n. The loop variable is incremented by 1 on each iteration.

The program uses the cout object to print the current term of the series, and update the current and previous terms using the formulas a = b, b = temp + b, where temp is a temporary variable used to hold the value of the current term?

What is the Fibonacci series?

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The Fibonacci sequence is named after the Italian mathematician Leonardo Fibonacci, who introduced it to the Western world in his 1202 book “Liber Abaci”.

The first few terms of the Fibonacci series are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

The Fibonacci series has many interesting properties and appears in many different areas of mathematics and science. It is often used as a benchmark for computer performance, as it involves a large number of recursive calculations.

In mathematics, the Fibonacci series appears in various forms, such as the Fibonacci sequence of numbers, the Fibonacci sequence of primes, and the Fibonacci sequence of squares. It also appears in the study of geometry, where it is used to model the growth of natural objects, such as plants, trees, and shells.