Print Factorial in C
In C programming, the factorial of a non-negative integer can be calculated using a recursive function or a loop.
What is factorial?
The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, the factorial of 5 (written as 5!) is equal to 5 x 4 x 3 x 2 x 1 = 120. Factorials are commonly used in combinatorics, probability, and algebra. Factorial of 0 is defined as 1.
Approach to print factorial of a number in C language
The approach to print the factorial of a number in C language can be done using the following steps:
- First, include the
stdio.h
header file in the program, which is necessary for input/output operations. - Define a function called
print_factorial
that takes in a single integer argument,n
. - Initialize a variable
result
to 1. - Use a for loop to iterate over the integers from 1 to
n
. - Within the for loop, multiply
result
by the current value of the loop variable at each iteration. - After the for loop, use the
printf
function to print the final value ofresult
, along with a message that describes the result. - In the
main
function, prompt the user to enter a number using theprintf
function, and read the user’s input using thescanf
function. - Pass the user’s input as an argument to the
print_factorial
function.
Pseudo code to print Factorial of a number
Here is some sample pseudocode for a function that calculates and prints the factorial of a given number in C:
function print_factorial(n) {
result = 1;
for (i = 1; i <= n; i++) {
result = result * i;
}
print(result);
}
This function, called print_factorial
, takes in a single argument, n
, and uses a for loop to iteratively multiply the variable result
by the integers from 1 to n
. The final value of result
is then printed.
C program to print factorial of a number
#include <stdio.h>
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int num, fact;
printf("Enter a number: ");
scanf("%d", &num);
fact = factorial(num);
printf("The factorial of %d is %d\n", num, fact);
return 0;
}
When this program is run and user inputs number 5, for example, the output will be:
Enter a number: 5
The factorial of 5 is 120
In this program, I have defined a function factorial
which takes an integer as input and returns the factorial of the number, this function uses a for loop to iterate over the integers from 1 to n
and multiply the result with the current value of the loop variable at each iteration. In the main
function, the program prompts the user to enter a number, reads that number using the scanf function, calls the factorial function and assigns the return value to a variable. Finally, the program prints the result using the printf function.