This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Monday, March 13, 2023

Write a program to generate Fibonacci series up to n terms using recursive function.

 Here's a C++ program to generate the Fibonacci series up to n terms using a recursive function:

#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;
    cout << "Enter the number of terms: ";
    cin >> n;
    cout << "Fibonacci Series: ";
    for (int i = 0; i < n; i++) {
        cout << fibonacci(i) << " ";
    }
    return 0;
}

Output:

Enter the number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8

Explanation:

  • The program defines a function fibonacci() that takes an integer argument n and returns the n-th term in the Fibonacci series. The function uses recursion to calculate the Fibonacci number. If n is 0 or 1, the function returns n itself. Otherwise, it returns the sum of the previous two terms in the series, which are calculated by recursively calling the fibonacci() function with arguments n-1 and n-2.
  • In the main() function, the program prompts the user to enter the number of terms they want to generate in the Fibonacci series using cin.
  • The program then uses a for loop to generate the first n terms in the series by calling the fibonacci() function for each value of i from 0 to n-1. The terms are printed to the console using cout.
  • The program then exits by returning 0.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget