Home  >  Article  >  Backend Development  >  Fibonacci sequence program written in C language

Fibonacci sequence program written in C language

WBOY
WBOYforward
2023-09-05 18:53:061051browse

Fibonacci sequence program written in C language

Given 'n' numbers, the task is to generate the Fibonacci sequence from 0 to n, where the Fibonacci sequence of integers has the form

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Among them, the integers 0 and 1 will have fixed spaces, and then add two digits, for example,

After translating the original text into Chinese, retain the HTML code as follows:

Among them, the integers 0 and 1 will have fixed spaces, and then add two digits, for example,

0+1=1(3<sup>rd</sup> place)
1+1=2(4<sup>th</sup> place)
2+1=3(5<sup>th</sup> place) and So on

The sequence F of the Fibonacci sequence (n) will have a recurrence relation defined as −.

Fn = Fn-1 + Fn-2
Where, F(0)=0 and F(1)=1 are always fixed

Several methods can be used to generate the Fibonacci sequence −

Recursive method − In this method, the function is called after each integer value itself. It's simple and easy, but results in exponential time complexity, making this approach less efficient.

Using a for loop − By using a for loop to generate the Fibonacci sequence, the time complexity can be reduced to O(n), making this method more efficient.

Example

Input-: n=10
Output-: 0 1 1 2 3 5 8 13 21 34

Algorithm

Start
Step 1 -> Declare function for Fibonacci series
   Void Fibonacci(int n)
      Declare variables as int a=0,b=1,c,i
      Print a and b
      Loop For i=2 and i<n and ++i
         Set c=a+b
         Print c
         Set a=b
         Set b=c
      End
Step 2 -> In main()
   Declare int as 10
   Call Fibonacci(n)
Stop

Example

Chinese translation is:

Example

#include<stdio.h>
void fibonacci(int n){
   int a=0,b=1,c,i;
   printf("fibonacci series till %d is ",n);
   printf("</p><p>%d %d",a,b);//it will print 0 and 1
   for(i=2;i<n;++i) //loop starts from 2 because 0 and 1 are the fixed values that series will take{
      c=a+b;
      printf(" %d",c);
      a=b;
      b=c;
   }
}
int main(){
   int n=10;
   fibonacci(n);
   return 0;
}

Output

fibonacci series till 10 is
0 1 1 2 3 5 8 13 21 34

The above is the detailed content of Fibonacci sequence program written in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete