Factorial Calculator
This program calculates the factorial of a given number using recursion in C.
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number < 0) {
printf("Factorial of a negative number is undefined.\n");
} else {
int result = factorial(number);
printf("Factorial of %d is %d.\n", number, result);
}
return 0;
}
Factorial Calculation Program
The above program is written in C and calculates the factorial of a given number using recursion.
Step 1:
The program starts with including the standard input/output library
stdio.h
, which provides functions like printf()
and scanf()
.Step 2:
The
factorial()
function is defined to calculate the factorial of a number. It takes an integer n
as an argument.Step 3:
Inside the
factorial()
function, there is a base case check. If n
is 0 or 1, which are the base cases for factorial, the function returns 1. This is because the factorial of 0 and 1 is defined as 1.Step 4:
If
n
is not 0 or 1, the function calls itself recursively with the argument n - 1
and multiplies it with n
. This recursion continues until the base case is reached.Step 5:
In the
main()
function, an integer variable number
is declared to store the user input.Step 6:
The program prompts the user to enter a number using
printf()
.Step 7:
The user's input is read using
scanf()
and stored in the number
variable.Step 8:
An
if-else
statement is used to check if the entered number is less than 0. If it is, the program prints a message stating that the factorial of a negative number is undefined.Step 9:
If the entered number is greater than or equal to 0, the program calls the
factorial()
function with the number as an argument and stores the result in the result
variable.Step 10:
Finally, the program prints the calculated factorial using
printf()
, displaying the original number and the result.Step 11:
The program ends with the
return 0;
statement, indicating successful execution.To summarize, this program takes a number as input, calculates its factorial using recursion, and outputs the result.
For more information on factorial and recursion, you can visit the following external links: Factorial on Wikipedia and Recursion on Wikipedia.
If you have any doubts, Please let me know