Introduction
A factorial is a mathematical function that multiplies a given number by every whole number less than it down to 1.
Factorial is commonly denoted by “n!” and is calculated as:
n! = n × (n-1) × (n-2) × … × 1
Factorials are widely used in fields such as algebra, probability, and combinatorics. In this program, we will calculate
the factorial of a given number using a simple iterative approach.
Objective
The objective of this program is to:
- Understand how to calculate factorials in C programming.
- Implement a program that asks the user for an input number and calculates its factorial.
- Understand the usage of loops in C to perform iterative calculations.
Code
#include
// Function to calculate factorial
long long int factorial(int n) {
long long int result = 1;
for (int i = 1; i <= n; i++) {
result *= i; // Multiply the result by the current number
}
return result;
}
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num); // Taking input from the user
// Validate if the input is a positive integer
if (num < 0) {
printf("Error! Factorial of a negative number doesn't exist.\n");
} else {
// Call the factorial function and display the result
printf("Factorial of %d is %lld\n", num, factorial(num));
}
return 0;
}
Explanation of the Program
This program calculates the factorial of a given number using an iterative approach. Let’s break it down step by step:
- Function Declaration: The program defines a function
factorial
that takes an integern
as its argument and returns along long int
representing the factorial. - Iterative Loop: Inside the
factorial
function, a for loop runs from 1 ton
. For each iteration, it multiplies the result by the current loop indexi
. - User Input: In the
main
function, the program prompts the user to enter a positive integer. The input is read usingscanf
. - Error Handling: If the user enters a negative number, the program displays an error message stating that factorial for negative numbers is not possible.
- Output: If the input is valid, the program calls the
factorial
function and prints the result in the formatFactorial of is
.
How to Run the Program
To run this program, follow these steps:
- Ensure you have a C compiler installed, such as GCC or Clang.
- Create a new C source file, e.g.,
factorial.c
. - Copy the provided C code into this file.
- Open a terminal or command prompt and navigate to the folder containing your
factorial.c
file. - Compile the program using the command:
gcc -o factorial factorial.c
- Run the program by typing:
./factorial
- The program will prompt you to enter a number, and it will display the factorial result.
Conclusion
This simple program demonstrates the calculation of a factorial using an iterative approach in C programming.
The program is an excellent starting point for understanding loops, user input, and basic error handling in C.
You can also modify the program to handle larger numbers or optimize it for performance using recursion if desired.