निम्नलिखित रिकर्सन का उपयोग करते हुए फाइबोनैचि श्रृंखला का एक उदाहरण है।
उदाहरण
#include <iostream>
using namespace std;
int fib(int x) {
if((x==1)||(x==0)) {
return(x);
}else {
return(fib(x-1)+fib(x-2));
}
}
int main() {
int x , i=0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
cout << " " << fib(i);
i++;
}
return 0;
} आउटपुट
Enter the number of terms of series : 15 Fibonnaci Series : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
उपरोक्त कार्यक्रम में, वास्तविक कोड फ़ंक्शन 'फ़ाइब' में इस प्रकार मौजूद है -
if((x==1)||(x==0)) {
return(x);
}else {
return(fib(x-1)+fib(x-2));
} मुख्य () फ़ंक्शन में, उपयोगकर्ता द्वारा कई शब्द दर्ज किए जाते हैं और फ़ाइब () कहा जाता है। फाइबोनैचि श्रृंखला निम्नानुसार मुद्रित होती है।
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
cout << " " << fib(i);
i++;
}