Fibonacci series program in C using recursive method

Ans: 

In this tutorial we are going to learn how to print Fibonacci series in c program using recursion.

Before moving directly on the writing Fibonacci series in c program using recursion, first you should know

What is Fibonacci Series?

A Fibonacci series is a series in which next number is a sum of previous two numbers.

For example : 0, 1, 1, 2, 3, 5, 8 ……

In Fibonacci Series, first number starts with 0 and second is with 1 and then its grow like,

0

1

0 + 1 = 1

1 + 1 = 2

1 + 2 = 3

2 + 3 = 5 and 

so on…

How our program will behave?

Its Logic is different from Fibonacci series program in c using iterative method.

Here we have a function named fibonacci() which will take a input and return next element as output. Each time it will call itself to calculate the elements of the series. 

Like if someone given 6 as a input then our program should return,

0, 1, 1, 2, 3, 5

C program to print Fibonacci series program using recursive methods

#include<stdio.h>
#include<conio.h>
int fibonacci(int);
int main(){ 
	int n, i; 
	printf("Enter the number of element you want in series :"); 
	scanf("%d",&n); 
	printf("fibonacci series is : \n");
	for(i=0;i<n;i++) { 
		printf("%d \n",fibonacci(i));
	}
	getch();
}
int fibonacci(int i){ 
	if(i==0) return 0; 
	else if(i==1) return 1; 
	else return (fibonacci(i-1)+fibonacci(i-2));
} 

Output:

Enter the number of element you want in series :6
fibonacci series is : 
0 
1 
1 
2 
3 
5

Explanation of program written in C to print Fibonacci series using recursive method

  • Here first of all we have declared one function named fibonacci which will take integer as a input and will return a next integer element.
  • In the above program I have taken 2 variables n and i of integer type.
  • Now our main logic will start from a “for loop”. This loop will be called n number of times, where n is given as input. 
  • And each time when loop condition will satisfy the value of i will pass as a parameter to fibonacci() method as a input.
  • In the body of fibonaaci(int i) function we have nested if-else. 
  • If input is 0 then it will return 0.
  • It input is 1 then it will return 1.
  • And if the value is greater then one then calculation will perform using fibonacci(i-1) + fibonacci(i-2).

I believe Fibonacci Series program is now clear to you.

Leave a Comment