C Program to find the factorial of a given number
Objective
Write a C program to find the factorial of a given number.
Algorithm / Approach
- Declare an integer
nand initializefact = 1. - Read the number
nfrom the user. - Start a
forloop withi = n, conditioni >= 1, and decrementi--. - Inside the loop, multiply:
fact = fact * i. - Print the factorial.
main.c
#include<stdio.h>
int main( ) {
int i, fact=1, n;
printf("Enter Value of N: ");
scanf("%d", &n);
for(i=n; i>=1; i--)
{
fact = fact*i;
}
printf("FACTORIAL IS : %d\n",fact);
return 0;
}
Expected Output
Enter Value of N: 4 FACTORIAL IS : 24
Explanation of the Program
- The factorial of a number N (denoted as N!) is the product of all positive descending integers from N down to 1 (e.g., 4! = 4 * 3 * 2 * 1 = 24).
- Because we are multiplying, we must initialize
fact = 1. If we initialized it to 0 (like we did withsum), the result would always be 0 because anything multiplied by 0 is 0.
Complexity
Time Complexity
O(n) - Where n is the input number.
Space Complexity
O(1)