factorial - Returns the factorial of a given number.
@n: The number to find the factorial of.
Return: If n > 0 - the factorial of n.
If n < 0 - 1 to indicate an error.
*/
int factorial(int n) //n: An integer representing the number for which we want to calculate the factorial.
{
int result = n; // Here, we declare an integer variable result and initialize it with the value of n. This variable will be used to store the intermediate results of the factorial calculation.
if (n < 0) /This condition checks if n is negative. If n is less than 0, it returns -1 to indicate an error. Factorials are defined only for non-negative integers, so a negative input is considered invalid./
return (-1);
else if (n >= 0 && n <= 1) /This condition checks if n is 0 or 1. In these cases, the factorial is defined as 1, so the function returns 1./
return (1);
/*If none of the above conditions are met, the function enters the else block:
result = factorial(n - 1);: Here, it calculates the factorial of n by making a recursive call to the factorial function with the argument n - 1. This recursive call calculates the factorial of the number one less than the current n and multiplies it with n (the current value of result). This process continues recursively until it reaches the base cases of n < 0 or n <= 1./
result *= factorial(n - 1);
int main(void) {
// your code goes here
int num;
int i =1;
scanf("%d",&num);
for(int a = 1; a <= num; a = a + 1 )
{
i = i * a;
}
printf("The factorial of the given number is: %d",i);
return 0;
}
include "main.h"
/**
If n < 0 - 1 to indicate an error. */ int factorial(int n) //n: An integer representing the number for which we want to calculate the factorial. { int result = n; // Here, we declare an integer variable result and initialize it with the value of n. This variable will be used to store the intermediate results of the factorial calculation.
if (n < 0) /This condition checks if n is negative. If n is less than 0, it returns -1 to indicate an error. Factorials are defined only for non-negative integers, so a negative input is considered invalid./ return (-1);
else if (n >= 0 && n <= 1) /This condition checks if n is 0 or 1. In these cases, the factorial is defined as 1, so the function returns 1./ return (1); /*If none of the above conditions are met, the function enters the else block:
result = factorial(n - 1);: Here, it calculates the factorial of n by making a recursive call to the factorial function with the argument n - 1. This recursive call calculates the factorial of the number one less than the current n and multiplies it with n (the current value of result). This process continues recursively until it reaches the base cases of n < 0 or n <= 1./ result *= factorial(n - 1);
}