logo

C의 피보나치 수열

피보나치 시리즈 C: 피보나치 수열의 경우, 다음 숫자는 이전 두 숫자의 합입니다. 예를 들어 0, 1, 1, 2, 3, 5, 8, 13, 21 등. 피보나치 수열의 처음 두 숫자는 0과 1입니다.

피보나치 수열 프로그램을 작성하는 방법에는 두 가지가 있습니다.

  • 재귀가 없는 피보나치 수열
  • 재귀를 이용한 피보나치 수열

재귀 없는 C의 피보나치 수열

재귀 없이 C에서 피보나치 급수 프로그램을 살펴보겠습니다.

 #include int main() { int n1=0,n2=1,n3,i,number; printf('Enter the number of elements:'); scanf('%d',&number); printf('
%d %d&apos;,n1,n2);//printing 0 and 1 for(i=2;i<number;++i) 0 1 2 loop starts from because and are already printed { n3="n1+n2;" printf(' %d',n3); n1="n2;" n2="n3;" } return 0; < pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements:15 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 </pre> <h2>Fibonacci Series using recursion in C</h2> <p>Let&apos;s see the fibonacci series program in c using recursion.</p> <pre> #include void printFibonacci(int n){ static int n1=0,n2=1,n3; if(n&gt;0){ n3 = n1 + n2; n1 = n2; n2 = n3; printf(&apos;%d &apos;,n3); printFibonacci(n-1); } } int main(){ int n; printf(&apos;Enter the number of elements: &apos;); scanf(&apos;%d&apos;,&amp;n); printf(&apos;Fibonacci Series: &apos;); printf(&apos;%d %d &apos;,0,1); printFibonacci(n-2);//n-2 because 2 numbers are already printed return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements:15 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 </pre> <hr></number;++i)>

C에서 재귀를 사용하는 피보나치 수열

재귀를 사용하여 C의 피보나치 시리즈 프로그램을 살펴보겠습니다.

 #include void printFibonacci(int n){ static int n1=0,n2=1,n3; if(n&gt;0){ n3 = n1 + n2; n1 = n2; n2 = n3; printf(&apos;%d &apos;,n3); printFibonacci(n-1); } } int main(){ int n; printf(&apos;Enter the number of elements: &apos;); scanf(&apos;%d&apos;,&amp;n); printf(&apos;Fibonacci Series: &apos;); printf(&apos;%d %d &apos;,0,1); printFibonacci(n-2);//n-2 because 2 numbers are already printed return 0; } 

산출:

 Enter the number of elements:15 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377