Fibonacci Series in C
Here, you will get the program code to create Fibonacci Series in C programming language. We will be make this program by using two different methods ( Fibonacci series using recursion, and Fibonacci Series using for loop).
What is Fibonacci Series?
The Fibonacci sequence is the series of the sum of previous two digits in a sequence. The first two numbers must be 0 and 1 from starting. The example Fibonacci series is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
The Fibonacci sequence formula:
F(n) = F(n-1) + F(n-2)
where,
F(0)=0
F(1)=1
F(n) is nth Fibonacci number.
Fibonacci series in C by using two ways
Method 1 (Recursion): Use a function that calls itself to calculate Fibonacci numbers. Input the term count and print the series.
Method 2 (For Loop): Initialize first two terms, then use a loop to calculate and print Fibonacci series by summing previous two terms in each step.
Fibonacci Series in c using recursion
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 | //Fibonacci Series using recursion //C Program code for Fibonacci Series using recursion #include<stdio.h> int fib(int); int main() { int n,i; printf("Enter the number of terms:"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("%d ",fib(i)); } return 0; } int fib(int n) { if(n==1 || n==2) { return 1; } return(fib(n-1)+fib(n-2)); } |
Output
Fibonacci Series in c using for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //Fibonacci series using loop in C #include<stdio.h> int main() { int a=0,b=1,c,i,n; printf("Enter the number of terms:"); scanf("%d",&n); printf("Fibonacci Series: %d %d",a,b); for(i=2;i<n;i++) { c=a+b; a=b; b=c; printf(" %d",c); } return 0; } |
Check out our other C programming Examples