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

Fibonacci sequence program written in C language

WBOY
Release: 2023-09-05 18:53:06
forward
1121 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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;
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template