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

C Programming Language / Function in C Language

989

Program:

/*********************************************************/
/* 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

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.