Given with ‘n’ numbers the task is to generate the fibonacci series till starting from 0 to n where fibonacci series of integer is in the form
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Where, integer 0 and 1 will have fixed space, after that two digits are added for example,
0+1=1(3rd place) 1+1=2(4th place) 2+1=3(5th place) and So on
Sequence F(n) of fibonacci series will have recurrence relation defined as −
Fn = Fn-1 + Fn-2 Where, F(0)=0 and F(1)=1 are always fixed
There can be multiple approaches that can be used to generate the fiboacce series −
Recursive approach − in this, approach function will make a call to itself after every integer value. It is simple and easy to implement but it will lead to exponential time complexity which makes this approach ineffective.
Using For Loop − By using For loop in generating Fibonacci series time complexity can be reduced to O(n) which makes this approach effective.
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
#include<stdio.h> void fibonacci(int n){ int a=0,b=1,c,i; printf("fibonacci series till %d is ",n); printf("\n%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