Home / Programs / Write a C program that uses a recursive function for generating the Fibonacci numbers.
Programming Example

Write a C program that uses a recursive function for generating the Fibonacci numbers.

👁 1,081 Views
💻 Practical Program
📘 Step by Step Learning
Write a C program that uses a recursive function for generating the Fibonacci numbers.

Program Code

/*********************************************************/
/* Program for computing the Fibonacci number sequence   */
/* using recursion.                                      */
/*********************************************************/
#include <stdio.h>
#include <stdlib.h>

int fib(int); /* function prototype */
int main()
{
	int i,j;
	printf("\n Enter the number of terms: ");
	scanf("%d",&i);
	if(i < 0)
	{
	printf("\n Error - Number of terms cannot be negative\n");
	exit(1);
	}

	printf("\n Fibonacci sequence for %d terms is: ",i);
	for( j=1; j<=i; ++j)
		printf(" %d",fib(j)); // function call to return jth Fibonacci term
	return 0;
}
/********************************************************/
/* Recursive function fib() 				   */
/*******************************************************/
int fib(int val)
{
	if(val == 1||val==2)
		return 1;
	else
		return(fib(val - 1) + fib(val - 2));
}
 

Output


 Enter the number of terms: 10

 Fibonacci sequence for 10 terms is:  1 1 2 3 5 8 13 21 34 55
 

Explanation

None

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.