logo

C のフィボナッチ数列

フィボナッチ数列 in C: フィボナッチ数列の場合、 次の数値は前の 2 つの数値の合計です たとえば、0、1、1、2、3、5、8、13、21 などです。フィボナッチ数列の最初の 2 つの数値は 0 と 1 です。

フィボナッチ数列プログラムを作成するには 2 つの方法があります。

  • 再帰なしのフィボナッチ級数
  • 再帰を使用したフィボナッチ数列

再帰なしの 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