The Fibonacci series starts with 0 and 1 and after that, all the elements of the Fibonacci series (fn) are the sum of the previous two (fn-1 + fn-2) elements.
fn = fn-1 + fn-2 where f0 = 0 , f1 =1
C code for Fibonacci Series
let’s write c program for Fibonacci Series
#include <stdio.h>
void main()
{
int first = 0, second = 1, next, n;
printf("Enter the value of n ");
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
printf("%d, ", first);
next = first + second;
first = second;
second = next;
}
}
Output
The above C code is a simple program that helps us to print the Fibonacci series. We have to enter the value of n and the code will print the Fibonacci series till the nth terms.
Fibonacci Series Program in C by using Recursion
#include <stdio.h>
int fibonacci (int n){
if (n<=2){
return n-1;
}
else{
return fibonacci(n-1) + fibonacci (n-2);
}
}
void main()
{
int first = 0, second = 1, next, n;
printf("Enter the value of n ");
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
printf("%d, ", fibonacci(i));
}
}
Output
The above C code prints the Fibonacci series by using a recursive approach (recursion).
1 thought on “C Code For Fibonacci Series”