C++ Program to Print Fibonacci Series upto N

Write a C++ program that takes an integer N from the user and displays the Fibonacci series up to the nth term.

Input and Output Examples

  1. Input: N = 5 Output: 0, 1, 1, 2, 3
  2. Input: N = 10 Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Algorithm to print fibonacci series

  1. Read the number N from the user.
  2. Initialize the first two terms of the Fibonacci series.
  3. Use a loop to calculate the next terms of the series up to N.
  4. Print each term of the series during the iteration.

Below is the C++ code that implements the Fibonacci series up to the nth term.

cpp
#include <iostream>
using namespace std;

int main() {
    int N, t1 = 0, t2 = 1, nextTerm = 0;

    // Step 1: Read the number of terms from the user
    cout << "Enter the number of terms: ";
    cin >> N;

    // Output the first two terms of the Fibonacci series if N is at least 2
    cout << "Fibonacci Series: ";
    for (int i = 1; i <= N; ++i) {
        if (i == 1) {
            cout << t1 << ", ";
            continue;
        }
        if (i == 2) {
            cout << t2 << ", ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        
        // Step 4: Print each term of the series
        cout << nextTerm;
        if (i != N) cout << ", "; // Format output with commas
    }

    return 0; // Indicates successful termination
}

Testing with Different Input Values

This program can accommodate any positive integer value of N to generate the corresponding Fibonacci sequence:

Input and Output Examples:

  1. Input: N=1 Output: 0
  2. Input: N=7 Output: 0, 1, 1, 2, 3, 5, 8

Programming

8231

733

Related Articles