logo

Fibonacci-serien i C

Fibonacci-serien i C: I tilfælde af fibonacci-serien, næste tal er summen af ​​de to foregående tal for eksempel 0, 1, 1, 2, 3, 5, 8, 13, 21 osv. De første to tal i fibonacci-serien er 0 og 1.

Der er to måder at skrive fibonacci-serien på:

  • Fibonacci-serien uden rekursion
  • Fibonacci-serien ved hjælp af rekursion

Fibonacci-serien i C uden rekursion

Lad os se fibonacci-seriens program i c uden rekursion.

 #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)>

Fibonacci-serien ved hjælp af rekursion i C

Lad os se fibonacci-seriens program i c ved hjælp af rekursion.

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

Produktion:

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