This program calculates the factorial of a given number using recursion.
Problem statement
Given a positive integer, we need to calculate its factorial.
C Program to Find the Factorial of a Number
#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("Factorial Calculator\n");
printf("Enter a positive integer: ");
scanf("%d", &number);
if (number < 0)
printf("Factorial is not defined for negative numbers.\n");
else {
int result = factorial(number);
printf("The factorial of %d is %d.\n", number, result);
}
return 0;
}
How it works?
- The program includes the necessary header file
stdio.hfor input/output operations. - The
factorialfunction is defined, which takes an integernas an argument and returns the factorial ofn. - In the
mainfunction:- A variable
numberis declared to store the user input. - The user is prompted to enter a positive integer.
- The entered value is stored in the
numbervariable usingscanf. - If the entered number is negative, a message is displayed stating that factorial is not defined for negative numbers.
- Otherwise, the
factorialfunction is called with thenumberas an argument and the result is stored in theresultvariable. - The result is printed using
printf.
- A variable