Pages

Ads 468x60px

Saturday, 2 June 2012

C PROGRAM FOR FACTORIAL USING RECURSION




C PROGRAM FOR FACTORIAL USING RECURSION



This program asks the user to input an integer value. The integer is sent to  function factorial where it recursively calls itself over and over with the next smallest integer until the number 1 is hit. Once at 1, the values are returned to the previous factorial call and multiplied together. This program has been tested and works for small integers, (due to C++ integer limitations).



CODE:
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int a,b=0,c;
clrscr();
printf("Enter the N value:");
scanf("%d",&a);
while(a<0)
{printf("\n\Enter only positive number.\n");
printf("Enter N value:");
scanf("%d",&a);
}
b=fact(a);
printf("%d",b);
getch();
}
int fact(int x)
{
if(x==0)
{
return(1);
}
else
{
return((x)*(fact(x-1)));
}
}

0 comments:

Post a Comment

Total Pageviews