Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find the factorial of a given number

C Code Example — Loop Programs

ADVERTISEMENT

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

  1. Declare an integer n and initialize fact = 1.
  2. Read the number n from the user.
  3. Start a for loop with i = n, condition i >= 1, and decrement i--.
  4. Inside the loop, multiply: fact = fact * i.
  5. 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 with sum), 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)
ADVERTISEMENT