C Program to Find Factorial of a Number - Loop & Recursion

Find Factorial Using a Loop

#include <stdio.h>

int main() {
    int n;
    long long factorial = 1;  // factorial can grow quickly, so use a large type

    printf("Enter a non-negative integer: ");
    scanf("%d", &n);

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

    // Multiply numbers from 1 to n
    for (int i = 1; i <= n; ++i) {
        factorial *= i;
    }

    printf("Factorial of %d = %lld\n", n, factorial);
    return 0;
}
Enter a non-negative integer: 5
Factorial of 5 = 120
        

The factorial of a number n (written n!) is the product of all integers from 1 to n. An iterative solution multiplies numbers in sequence, storing the result in a variable.

Find Factorial Using Recursion

#include <stdio.h>

// Recursive function declaration
long long factorial(int n) {
    // Base case: 0! is defined as 1
    if (n == 0)
        return 1;
    else
        // Recursive case: n! = n * (n-1)!
        return n * factorial(n - 1);
}

int main() {
    int n;
    printf("Enter a non-negative integer: ");
    scanf("%d", &n);

    if (n < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        printf("Factorial of %d = %lld\n", n, factorial(n));
    }
    return 0;
}
Enter a non-negative integer: 5
Factorial of 5 = 120
        

Recursion solves a problem by defining a function that calls itself with a smaller argument. Each call reduces the problem size until a base case is reached. In this factorial example, the base case is 0, and the recursion continues until n equals 0. Remember to ensure the base case is reachable; otherwise, the program will run indefinitely.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...