C Program to Find Factorial of a Number
This program demonstrates how to calculate the factorial of a number using both for and while loops in C.
Concept Overview
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. Factorials are widely used in mathematics, combinatorics, and computer science. In C, we can compute factorial using loops and handle errors for negative inputs.
Program Using For Loop
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; ++i) {
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}
return 0;
}Program Using While Loop
#include <stdio.h>
int main()
{
int number,i=1;
unsigned long long facto =1;
printf("Enter the number :");
scanf("%d",&number);
if (number<0)
{
printf("Error! Factorial of a negative number doesn't exist.\n");
}
else{
while(i<=number)
{
facto = facto*i;
i++;
}
printf("the factorial of the number is %llu\n",facto);
}
return 0;
}Output
Enter an integer: 5 Factorial of 5 = 120 Enter the number: 5 The factorial of the number is 120
Explanation
- `unsigned long long fact = 1;` – Variable to store factorial result, supports large values.
- `if (n < 0)` – Checks for negative input and displays an error.
- `for` or `while` loop – Multiplies numbers from 1 to n to calculate factorial.
- `printf()` – Displays the factorial result to the user.