The Fibonacci series is a well-known mathematical series, In this article, we are going to write a C program that prints n numbers of the Fibonacci series.
Table of Contents
Fibonacci Series
Fibonacci series is characterized by recurrence relation, each term/element/number is the sum of two previous terms/element/number, Starting from 0 and 1. An example of the Fibonacci series is given below-
0,1,1,2,3,5,8,13,21,……..
C Program to Print Fibonacci Series
In C we can print the Fibonacci series either by using an iterative approach or using recursive approach
Iterative Approach to Print Fibonacci Series
We are going to print the Fibonacci series in C by using loops.
#include <stdio.h>
void main()
{
int first = 0, second = 1, next, n;
printf("Enter the number of elemnet for the Fibonacci series");
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
printf("%d ", first);
next = first + second;
first = second;
second = next;
}
}
Output
Fibonacci Series Using Recursion in C
#include <stdio.h>
int fibonacci(int n)
{
if (n <= 1)
{
return n;
}
else
{
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
void main()
{
int first = 0, second = 1, next, n;
printf("Enter the number of elemnet for the Fibonacci series");
scanf("%d", &n);
for (int i = 0; i <= n; i++)
{
printf("%d ", fibonacci(i));
}
}
Output
Happy Coding
4 thoughts on “Fibonacci Series in C”