Programming Example
Write a C program that uses a recursive function for generating the Fibonacci numbers.
Write a C program that uses a recursive function for generating the Fibonacci numbers.
/*********************************************************/
/* 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));
}
Enter the number of terms: 10
Fibonacci sequence for 10 terms is: 1 1 2 3 5 8 13 21 34 55
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.