C program to calculate factorial of a number
Learn how to write a C program to calculate the factorial of a number. This article provides a detailed explanation and sample code for computing the factorial of a given number using loops in C programming.
Calculating the factorial of a number is a common task in computer programming and mathematics. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. This article will guide you through writing a C program to calculate the factorial of a given number, providing a detailed explanation and sample code.
Understanding Factorials
The factorial of a number n is defined as:
n! = n x (n-1) x (n-2) x … x 1
For example:
- 5!=54321=120
- 3!=321=6
- 0!=1 (by definition)
Steps to Calculate Factorial
- Input the Number: Read the number from the user.
- Initialize the Result: Start with a result variable set to 1.
- Loop through Numbers: Multiply the result by each number from 1 to n.
- Output the Result: Print the calculated factorial.
Write a C program to calculate factorial of a number
Here is a C program to calculate the factorial of a given number:
#include <stdio.h>
int main() {
int number;
unsigned long long result = 1;
// Input the number
printf("Enter a non-negative integer: ");
scanf("%d", &number);
// Calculate factorial
for (int i = 1; i <= number; ++i) {
result *= i;
}
// Output the result
printf("Factorial of %d is %llu", number, result);
return 0;
}
Output
Enter a non-negative integer: 5
Factorial of 5 is 120
Explanation
- Input the Number:
- The program prompts the user to enter a non-negative integer using
printf
. - The number is read using
scanf
and stored in the variablenumber
.
- The program prompts the user to enter a non-negative integer using
- Initialize the Result:
- The variable
result
is initialized to 1. This will hold the product of numbers as we compute the factorial.
- The variable
- Calculate the Factorial:
- A
for
loop is used to multiplyresult
by each number from 1 tonumber
. - The loop runs
number
times, and in each iteration,result
is updated with the product ofresult
and the current value ofi
.
- A
- Output the Result:
- After the loop completes, the program prints the calculated factorial using
printf
.
- After the loop completes, the program prints the calculated factorial using
Example
For an input of 5
, the program will:
- Initialize
result
to 1. - Multiply
result
by each number from 1 to 5:- 1*1=1
- 1*2=2
- 2*3=6
- 6*4=24
- 24*5=120
- Print
Factorial of 5 is 120
.