Algorithm


  1. Input:

    Take the number of terms (n) as input from the user.
  2. Initialize Variables:

    Initialize three variables, first and second to 0 and 1 respectively (the first two terms of the Fibonacci series), and next to 0.
  3. Display First Two Terms:

    • Display the first two terms of the series (first and second).
  4. Generate Fibonacci Series:

    • Run a loop from 3 to n to generate the series.
    • Inside the loop, calculate the next term (next) by adding the previous two terms (first and second).
    • Update first and second with the current terms.
    • Display the current term.
  5. Display Result:

    • After the loop, the program would have displayed the Fibonacci series up to the specified number of terms.

Code Examples

#1 Code Example- C++ Program Fibonacci Series up to n number of terms

Code - C++ Programming

#include <iostream>
using namespace std;

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

    cout << "Enter the number of terms: ";
    cin >> n;

    cout << "Fibonacci Series: ";

    for (int i = 1; i <= n; ++i) {
        // Prints the first two terms.
        if(i == 1) {
            cout << t1 << ", ";
            continue;
        }
        if(i == 2) {
            cout << t2 << ", ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        
        cout << nextTerm << ", ";
    }
    return 0;
}
Copy The Code & Try With Live Editor

Output

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

#2 Code Example- C++ Programing Program to Generate Fibonacci Sequence Up to a Certain Number

Code - C++ Programming

#include <iostream>
using namespace std;

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

    cout << "Enter a positive number: ";
    cin >> n;

    // displays the first two terms which is always 0 and 1
    cout << "Fibonacci Series: " << t1 << ", " << t2 << ", ";

    nextTerm = t1 + t2;

    while(nextTerm <= n) {
        cout << nextTerm << ", ";
        t1 = t2;
        t2 = nextTerm;
        nextTerm = t1 + t2;
    }
    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
Advertisements

Demonstration


C++ Programing Example to Display Fibonacci Series-DevsEnv