Write a recursive function and calculate factorial of inputted integer number.
Write a recursive function and calculate factorial of inputted integer number.
Answer: a recursive function calls itself with \(n-1\) until it reaches the base case, using \(n! = n\times(n-1)!\) and \(0! = 1! = 1\).
#include <stdio.h>
long fact(int n)
{
if (n <= 1) /* base case: 0! = 1! = 1 */
return 1;
return n * fact(n - 1); /* recursive call */
}
int main()
{
int n;
printf("Enter a non-negative integer: ");
scanf("%d", &n);
if (n < 0)
printf("Factorial is not defined for negative numbers\n");
else
printf("Factorial of %d = %ld\n", n, fact(n));
return 0;
}
How it works (for \(n = 4\)):
fact(4) returns 4 * fact(3)fact(3) returns 3 * fact(2)fact(2) returns 2 * fact(1)fact(1) hits the base case and returns 1.The calls then return one by one: \(2\times1 = 2\), \(3\times2 = 6\), \(4\times6 = 24\). Output: Factorial of 4 = 24.
Every recursive function needs a base case (here n <= 1); without it the function would keep calling itself until the stack overflows. long is used because factorials grow very fast (13! already exceeds a 32-bit int).
Log in or create a free account to answer this question.