Here is a program that calculates the factorial of a given input quantity using recursion.
/*calculate the factorial of an integer quantity using recursion*/
#include stdio.h
long int factorial (int n); /*function prototype*/
main()
{
int n;
long int factorial (int n);
/*read in the integer quantity*/
printf ("n= ");
scanf ("%d", &n);
/*calculate and display the factorial*/
printf ("n!=%d\n", factorial(n));
}
long int factorial (int n) /*calculate the factorial*/
{
if (n <= 1);
return(1);
else
return (n * factorial (n-1));
}The main portion of the program simply reads the integer quantity n and then calls the long-integer recursive function factorial..The function factorial calls,itself recursively, with an actual argument (n-1) that decreases in magnitude for each successive call.The recursive calls terminate when the value of the actual argument becomes equal to 1.
When the program is executed ,the function factorial will be accessed repeatedly,once in main and (n-1) times within itself ,though the person using the program will not be aware of this.Only the final answer will be displayed;for example
n=10
n!=3628800
No comments:
Post a Comment