Find Fibonacci Series Using Functions

Beginner

Introduction

In this lab, you will learn how to write a C++ program to find the Fibonacci series using functions. We will show you two different solutions to the problem. You can choose the one that suits your needs.

Writing the code

We will now write the code to find the Fibonacci series. We will write two different programs, one to find the Fibonacci series up to n terms and the other to find the Fibonacci series up to a specific number.

Program 1: Fibonacci Series up to n number of terms

This program generates the Fibonacci series up to n number of terms.

#include <iostream>
using namespace std;

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

    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 << ", ";
    }
}

int main() {
    int n;

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

    fibonacci(n);

    return 0;
}
Program 2: Fibonacci Sequence up to a Certain Number

This program generates the Fibonacci sequence up to a certain number.

#include <iostream>
using namespace std;

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

    // 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;
    }
}

int main() {
    int n;

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

    fibonacci(n);

    return 0;
}

Compiling and Running the Code

To compile and run the above programs, you need to follow the below mentioned steps:

  • Open the terminal and navigate to the ~/project directory
  • Type the following command to compile the code:
g++ main.cpp -o main
  • Type the following command to run the program:
./main
  • Enter the inputs as required by the programs

Summary

In this lab, we learned how to write a C++ program to find the Fibonacci series using functions. We wrote two programs, one to find the Fibonacci series up to n terms and the other to find the Fibonacci series up to a specific number.

Other Tutorials you may like