Prem Tiwari - - C Programming Tutorial

Sometimes back, one of my user our website is asked to create a program in c to get the Fibonacci series of any given number. Additionally, I have also shared a program to get the Fibonacci series of first 15 numbers without using the recursion.

Fibonacci number is the number of any number in the series is obtained by adding previous two numbers of the series.

Below is the list of the first 21 Fibonacci series numbers Fn for n = 0, 1, 2, …, 20 are:

If you want to get the Fibonacci number of any input number by the user by using the Fibonacci series formula `Fn-1 + Fn-2`

. Example if user enters number 9, then the Fibonacci number is 34. Below is the example of Fibonacci series in C programming by using recursion.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //Fibonacci Series using Recursion #include<stdio.h> int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); } int main () { int n = 9; printf("%d", fib(n)); getchar(); return 0; } |

*Output of above program is:*

1 2 3 | 34 |

Another example of Fibonacci series is using dynamic programming.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //Fibonacci Series using Dynamic Programming #include<stdio.h> int fib(int n) { /* Declare an array to store Fibonacci numbers. */ int f[n+1]; int i; /* 0th and 1st number of the series are 0 and 1*/ f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { /* Add the previous 2 numbers in the series and store it */ f[i] = f[i-1] + f[i-2]; } return f[n]; } int main () { int n = 9; printf("%d", fib(n)); getchar(); return 0; } |

*Output of above program is:*

1 2 3 | 34 |

*Fibonacci Series in C Without Using Recursion*

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include<stdio.h> #include<conio.h> void main() { int n1=0,n2=1,n3,i,number; clrscr(); printf("Enter the number of elements:"); scanf("%d",&number); printf("\n%d %d",n1,n2);//printing 0 and 1 //loop starts from 2 because 0 and 1 are already printed for(i=2;i<number;++i) { n3=n1+n2; printf(" %d",n3); n1=n2; n2=n3; } getch(); } |

*Output of above program is:*

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

Prem Tiwari is the founder of FreeWebMentor.com and also a professional developer who has vast experience in PHP and open source technologies. Apart from this, he is a blogger by hobby and also he has been a regular speaker of WordPress sessions in various IT Companies. View all posts by Prem Tiwari

Tags: c program for fibonacci, c program for fibonacci number, c program for fibonacci series, c program in fibonacci series, fibonacci series in c program

We use cookies to ensure that we give you the best experience and deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.OkPrivacy policy