fibonacci

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones. In C++, you can write a program to calculate the Fibonacci sequence using recursion or iteration.

Here is an example of a C++ program to calculate the Fibonacci sequence using recursion:

#include <iostream>
using namespace std;

int fibonacci(int n) {
    if (n <= 1)
        return n;
    else
        return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    int n;
    cout << "Enter the number of terms: ";
    cin >> n;

    for (int i = 0; i < n; i++) {
        cout << fibonacci(i) << " ";
    }

    return 0;
}

Explanation of the code:

  1. The program starts with including the necessary header file iostream, which is used for input and output operations in C++.

  2. The fibonacci() function is defined to calculate the Fibonacci sequence. It takes an integer n as a parameter and returns the nth term of the sequence.

  3. In the fibonacci() function, there is a base case where if n is less than or equal to 1, it returns n. This base case is necessary to stop the recursion.

  4. If the base case is not met, the function recursively calls itself with n - 1 and n - 2 as parameters and returns the sum of the two recursive calls.

  5. In the main() function, an integer n is declared to store the number of terms the user wants to calculate.

  6. The user is prompted to enter the number of terms.

  7. A for loop is used to iterate from 0 to n - 1.

  8. Inside the loop, the fibonacci() function is called with the current index (i) as the argument, and the result is printed.

  9. Finally, the program returns 0 to indicate successful execution.

This program calculates the Fibonacci sequence by recursively calling the fibonacci() function. The base case ensures that the recursion stops when n is less than or equal to 1. The main() function prompts the user for input and prints the calculated Fibonacci sequence using a for loop.