
Patrick B. answered 02/07/21
Math and computer tutor/teacher
Recursive Function is a function which calls itself.
To solve a problem recrusively, there are TWO conditions
which must be met:
(1) Stopping case: no recursion occurs, which ends the
chain of recrusive calls made to the function
(2) Recursive case: The main part of the problem
where the recursive calls are made
The example of factorials:
For NON-Negative integer N:
N! = N * (N-1)! if N>1
1 if N>=0
So for example 5! = 5 * 4!
= 5 * 4 * 3!
= 5 * 4 * 3 * 2!
= 5 * 4 * 3 * 2 * 1!
= 5 * 4 * 3 * 2 * 1
= 120
/*******************************************/
#include <stdio.h>
long factorial( long N)
{
long returnVal=-1;
if (N>1) //N=2,3,4,....
{
returnVal = N * factorial(N-1); //recursive call
}
else //invalid input parameter N must be non-negative
{
returnVal=1; //0! = 1! = 1
}
return(returnVal);
}
int main()
{
printf("%ld",factorial(5));
}