Consider a situation that a user wants to print first n (any value, e.g. first 10) numbers of Fibonacci series. You need to implement a program that gets a number from user and prints first n Fibonacci series numbers. Write a function for this purpose that prints Fibonacci series recursively. This function should accept a number in parameter and then print n number of elements of Fibonacci series.
#include <iostream>
using namespace std;
int Fibonacci(int n);
int main() {
int n;
//gets a number from user
cout<<"Enter n: ";
cin>>n;
//prints first n Fibonacci series numbers.
for(int i = 0; i < n; i++){
cout<<Fibonacci(i)<<" ";
}
cout<<"\n\n";
system("pause");
return 0;
}
int Fibonacci(int n){
if(n == 0 || n == 1)
{
return n;
}
else
{
// recursive call
return Fibonacci(n-1) + Fibonacci(n-2);
}
}
Comments
Leave a comment