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

C
#include <stdio.h>

int main() {
    int num, i;
    unsigned long long factorial = 1;

    printf("Enter a number: ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Factorial is not defined for negative numbers.\n");
        return 1;
    }

    for(i = 1; i <= num; i++) {
        factorial *= i;
    }

    printf("Factorial of %d is %llu\n", num, factorial);

    return 0;
}

Program Using While Loop

C
#include <stdio.h>

int main() {
    int num, i = 1;
    unsigned long long factorial = 1;

    printf("Enter a number: ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Factorial is not defined for negative numbers.\n");
        return 1;
    }

    while(i <= num) {
        factorial *= i;
        i++;
    }

    printf("Factorial of %d is %llu\n", num, factorial);

    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.
Note: ⚠️ Note: Factorials grow very quickly. Using `unsigned long long` allows handling up to 20! safely in C.