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 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));
}
 
                        

🖥 Program 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
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.