Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

재귀를 사용하여 피보나치 수를 찾는 C++ 프로그램

<시간/>

다음은 재귀를 사용한 피보나치 수열의 예입니다.

예시

#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

위의 프로그램에서 실제 코드는 'fib' 함수에 다음과 같이 존재합니다. -

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

main() 함수에서 사용자가 여러 용어를 입력하고 fib()가 호출됩니다. 피보나치 수열은 다음과 같이 인쇄됩니다.

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