We are in a position to write some programs on recursions now.
Example
1: Write a C program to generate a Fibonacci series to n using recursion.
Solution 1:
The program is as follows:
#include
#include
void main( )
{
int n, i, t;
clrscr( );
printf(“\n Enter the number of terms to be generated”);
scanf(“%d”, &n);
printf(“\n\t The Fibonacci series is:”);
for (i =1; i <=n; i++)
{
t = fib (i);
printf(“\t %d”, t);
}
getch( );
}
fib (int n)
{
if (n = = 1)
return 0;
else
if ( n = = 2)
return ( 1);
else
return (fib (n – 1) + fib (n -2));
}
Do'stlaringiz bilan baham: |