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;
void printFibonacciNumbers(int n)
{
int f1 = 0, f2 = 1, i;
if (n < 1)
return;
cout << f1 << " ";
for (i = 1; i < n; i++) {
cout << f2 << " ";
int next = f1 + f2;
f1 = f2;
f2 = next;
}
}
int main() {
int n;
cout<<"Enter the number of elements of Fibonacci series to print: ";
cin>>n;
printFibonacciNumbers(n);
return 0;
}
Comments
Leave a comment