by CodeChum Admin
This one’s probably one of the most popular recursion problems in programming. Your task is to create a recursive function that prints out the the first up to the nth number in the Fibonacci sequence by going through the numbers using recursion.
In case you forgot, here is the definition of a Fibonacci sequence:
Instructions:
Input
1. Elements to be printed
Output
Enter·n:·4
1·1·2·3
#include <iostream>
using namespace std;
void displayFibonacci(int n) {
int f2 = 0;
int f1 = 1;
int f = 1;
cout << f;
if (n == 1) {
cout << endl;
return;
}
for (int i=1; i<n; i++) {
f = f1 + f2;
f2 = f1;
f1 = f;
cout << " " << f;
}
cout << endl;
return;
}
int main() {
int n;
cout<< "Enter n: ";
cin >> n;
displayFibonacci(n);
return 0;
}
Comments
Leave a comment