Fibonacci series program in C using Recursion
In this tutorial, we’ll explore how to utilise recursion to build the Fibonacci sequence in C language.
What does the term "Fibonacci Series" mean?
The following number in a Fibonacci number series is essentially the summation of the previous two values (preceding numbers). In every series, the first two integers are still 0 and 1. Thus, the sequence is as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, so on.
How to write the Fibonacci Sequence in C?
Two of the main approaches that can be used to write this series in C language:
- Using Recursion (Only this approach is discussed in this tutorial)
- Without Recursion
Fibonacci Series using Recursion:
Let's look at a recursive Program for the Fibonacci series in C Language
Code:
C Program to write Fibonacci Series
#include<stdio.h>
void printFibonacciseries(int p)
{
static int p1=0, p2=1, p3; //considering variables
if( p > 0 ) //if condition is true it will execute
{
//logic
p3 = p1 + p2;
p1 = p2;
p2 = p3;
printf("%d ", p3); //printing value of the series
printFibonacciseries( p - 1) ; //user-defined function
}
}
int main()
{
int p; //considering variable
printf("Enter any number to create Fibonacci Series: "); //asks user for a input
scanf("%d", & p); //storing value in variable p
printf("The Fibonacci Series should be: "); //printing statement
printf("%d %d ",0,1); //printing 0 and 1 as these are common for all fibonacci series
printFibonacciseries( p - 2 ); //using p-2 as we have already printed two numbers here
return 0;
}
Output: (If user puts 11 as input)
Enter any number to create Fibonacci Series: 11
The Fibonacci Series should be: 0 1 1 2 3 5 8 13 21 34 5
Output: (If user puts 9 as input)
Enter any number to create Fibonacci Series: 9
The Fibonacci Series should be: 0 1 1 2 3 5 8 13 21