Computer >> Máy Tính >  >> Lập trình >> C ++

Chương trình C ++ để tìm số Fibonacci bằng cách sử dụng đệ quy

Sau đây là một ví dụ về chuỗi fibonacci sử dụng đệ quy.

Ví dụ

#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;
}

Đầu ra

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

Trong chương trình trên, mã thực có trong hàm ‘fib’ như sau -

if((x==1)||(x==0)) {
   return(x);
}else {
   return(fib(x-1)+fib(x-2));
}

Trong hàm main (), một số thuật ngữ được nhập bởi người dùng và fib () được gọi. Chuỗi fibonacci được in như sau.

cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
   cout << " " << fib(i);
   i++;
}