Learn Programming and technology with ease @ developerpublish.com

HomeC ProgrammingC Program to Find the Factorial of a Number

# C Program to Find the Factorial of a Number

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?

1. The program includes the necessary header file `stdio.h` for input/output operations.
2. The `factorial` function is defined, which takes an integer `n` as an argument and returns the factorial of `n`.
3. In the `main` function:
• A variable `number` is declared to store the user input.
• The user is prompted to enter a positive integer.
• The entered value is stored in the `number` variable using `scanf`.
• If the entered number is negative, a message is displayed stating that factorial is not defined for negative numbers.
• Otherwise, the `factorial` function is called with the `number` as an argument and the result is stored in the `result` variable.
• The result is printed using `printf`.

Share:

### You May Also Like

#### C Program to Find Volume and Surface Area of Sphere

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...

#### C Program to Convert Roman Number to Decimal Number

This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...

#### C Program to Calculate the Value of sin(x)

This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...