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