C++ fibo

#include <iostream>
using namespace std;

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

int main() {
    int n = 10;
    cout << "Fibonacci Series up to " << n << " terms:" << endl;
    for (int i = 0; i < n; i++) {
        cout << fibonacci(i) << " ";
    }
    return 0;
}

Explanation:

  • #include \<iostream>: Includes the input/output stream library.
  • using namespace std: Allows usage of entities in the standard C++ library without specifying the namespace.
  • int fibonacci(int n): Function to calculate the nth Fibonacci number recursively.
  • Checks if n is less than or equal to 1.
    • If true, returns n.
    • If false, calls the fibonacci function recursively for (n - 1) and (n - 2) and returns their sum.
  • int main(): The main function where the program execution starts.
  • int n = 10;: Variable n holds the number of terms in the Fibonacci series to be displayed.
  • cout << "Fibonacci Series up to " << n << " terms:" << endl;: Prints a message indicating the number of terms to be displayed.
  • for (int i = 0; i < n; i++) { ... }: Iterates through each term up to the nth term.
    • cout << fibonacci(i) << " ";: Calls the fibonacci function for each term 'i' and displays it.