C++ Program to Print Fibonacci Series up to N Numbers

1. Introduction

The Fibonacci series is one of the most well-known patterns in mathematics. It starts with 0 and 1, and each subsequent number in the series is the sum of the two preceding numbers. This sequence finds its significance in many natural phenomena, from the arrangement of leaves on a plant to the branching of trees. In this post, we'll walk through a C++ program that generates the Fibonacci series up to n numbers.

2. Program Overview:

Our program will follow these steps:

1. Prompt the user to provide the value of n.

2. Check if n is 1 or 2 and handle these cases separately.

3. If n is more than 2, start from the third term and generate the sequence iteratively until the n-th term.

4. Display the Fibonacci sequence.

3. Code Program

#include <iostream>
using namespace std;

// Function to generate the Fibonacci series up to n terms
void fibonacci(int n) {
    long long t1 = 0, t2 = 1, nextTerm; // Initialize variables for the first two terms

    for (int i = 1; i <= n; ++i) { // Iterate from 1 to n terms
        if(i == 1) {
            cout << t1 << ", "; // Output the first term (0)
            continue; // Skip the rest of the loop and continue to the next iteration
        }
        if(i == 2) {
            cout << t2 << ", "; // Output the second term (1)
            continue; // Skip the rest of the loop and continue to the next iteration
        }
        nextTerm = t1 + t2; // Calculate the next term in the sequence
        t1 = t2; // Update t1 to the value of t2
        t2 = nextTerm; // Update t2 to the value of the calculated nextTerm

        cout << nextTerm << ", "; // Output the current term
    }
}

int main() {
    int n;

    cout << "Enter the number of terms: ";
    cin >> n; // Read the input number of terms from the user

    cout << "Fibonacci Series: ";
    fibonacci(n); // Call the fibonacci function to generate and display the series
    return 0; // Indicate successful execution by returning 0
}

Output:

Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

4. Step By Step Explanation

1. Headers and Namespace: We begin by including the iostream library for input-output operations and declare usage of the standard namespace.

2. Fibonacci Function: The function fibonacci takes an integer n and prints the Fibonacci sequence up to n terms. We utilize three variables: t1, t2, and nextTerm to calculate and store values in the series. Loops and conditions help us generate the sequence.

3. Main Function: This is where the program starts its execution. We declare the variable n to store the number of terms.

4. User Input: A prompt is displayed using cout, and the user's response is acquired with cin.

5. Printing the Sequence: We call the fibonacci function and subsequently display the resulting series.

6. Program Termination: The program concludes with a return value of 0, indicating successful execution.

Comments