Subscribe

RSS Feed (xml)

Sunday, February 22, 2009

Write a C program to generate the Fibonocci series using Recursion.

#include(stdio.h) // place this '<' & '>' instead of '(' & ')' before stdio.h
#include(conio.h)
int fibno(int); // function declaration.
void main( )
{
int ct, no, disp;
clrscr( );
printf("Enter the no. of terms:");
scanf("%d", &no);
printf("\n The Fibonocci series:\n");
for( ct=0; ct<=n-1; ct++) {
disp= fibno(ct); //calling function.
printf("%5d", disp);
}
getch( );
}

int fibno( int n)
{
int x, y;
if(n==0)
return 0;
else if(n==1)
return 1;
else
{
x= fibno( n-1);
y= fibno( n-2);
return (x+y);
}
}

Here the 'main' function variables
'ct' is to count the no. of values displayed in output.
'no' is for total no.of terms.
'disp' is for display the fibonocci numbers.

Here the loop 'ct<= n-1' displays the values when 'ct' equals to 'n-1'.
Suppose, Let us assume n=10 (ie., no. of terms )
Then the loop terminates, when ct==9.

Output:- Enter the no. of terms: 10

The Fibonocci series:
0 1 1 2 3 5 8 13 21 34

Note:- If u have any doubt regarding this program or logic, please feel free to contact me.

2 comments:

  1. only 0 and 1 is displayed and then d program ends immedietly. I cant understand d function. Can anyone help. only 0 and 1 is displayed and then d program ends immedietly. I cant understand d function. Can anyone help.

    ReplyDelete