Beginner Number Problems C

Factorial Program in C Using Recursion

Compute n! in C with a recursive function, and understand how the calls are made and returned.

  • TimeO(n), one call per value from n down to 1
  • SpaceO(n) for the call stack
  • Hints3
  • Read4 min
Quick answer

A recursive factorial function in C calls itself with a smaller number: return n * factorial(n - 1);, and stops at the base case if (n <= 1) return 1;. So factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * factorial(1) = 24. Use long long as the return type, because an int overflows after 12! and long long after 20!.

RecursionBase caseCall stackInteger overflow
1

Problem statement

Write a factorial program in C using recursion. Read a non-negative integer n and print n! using a function that calls itself.

Show the full call trace for n = 4, so it is clear how each call waits for the next one and how the results come back.

Input

A non-negative integer n.

Output

Factorial of n = <value>.

Examples

Example 1
Inputn = 5
OutputFactorial of 5 = 120

5 x 4 x 3 x 2 x 1 = 120.

Example 2
Inputn = 0
OutputFactorial of 0 = 1

0! is defined as 1, and the base case returns 1 straight away.

Example 3
Inputn = 20
OutputFactorial of 20 = 2432902008176640000

The largest factorial that fits in a 64-bit long long.

Constraints

  • 0 <= n <= 20 when the result is stored in long long
  • Factorial is not defined for negative numbers
2

Think before you code

Reveal the questions to ask yourself first
  • How can you write n! using (n - 1)!?
  • What is the smallest input the function can answer without calling itself?
  • What happens if there is no base case?
3

Hints

Open one at a time — try again after each.
1 Hint 1
n! = n x (n - 1)!, so return n * factorial(n - 1).
2 Hint 2
The base case is n <= 1, which returns 1. It covers both 0! and 1!.
3 Hint 3
Use long long for the return type and print it with %lld.
4

Approach

Reveal the step-by-step approach

Recursive factorial in C

A recursive function has two parts:

  1. Base case: an input small enough to answer directly. Here, if (n <= 1) return 1;.
  2. Recursive case: solve a smaller version of the same problem. Here, return n * factorial(n - 1);.

Each call makes n one smaller, so it always reaches the base case. Without the base case, the function keeps calling itself until the stack runs out and the program crashes.

How the call stack works

When factorial(4) runs, it cannot finish until factorial(3) returns. That call waits for factorial(2), which waits for factorial(1). Each waiting call is kept on the call stack. When factorial(1) returns 1, the calls finish one by one in reverse order. See what is recursion for more examples.

Type Largest n! that fits
int (32-bit) 12! = 479001600
long long (64-bit) 20! = 2432902008176640000
5

Dry run

Walk through the example step by step

Call trace for factorial(4):

Calls going down                 Returns coming back up
----------------                 ----------------------
factorial(4) -> 4 * factorial(3)   = 4 * 6 = 24
factorial(3) -> 3 * factorial(2)   = 3 * 2 = 6
factorial(2) -> 2 * factorial(1)   = 2 * 1 = 2
factorial(1) -> base case          = 1

The calls go down from 4 to 1. Nothing is multiplied until the base case returns 1. Then each waiting call multiplies and returns: 1, 2, 6, 24.

6

Solution

Reveal the full C solution
solution.c
#include <stdio.h>

long long factorial(int n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

int main(void) {
    int n;
    printf("Enter a number: ");
    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;
}

Output (separate runs):

Enter a number: 5
Factorial of 5 = 120
Enter a number: 0
Factorial of 0 = 1
Enter a number: 20
Factorial of 20 = 2432902008176640000

In n * factorial(n - 1), n is an int and factorial returns long long, so C does the multiplication in long long. The n < 0 check in main stops negative input before it reaches the function.

See the call trace for n = 4

This version prints a line every time the function is called and every time it returns. The depth argument adds indentation so you can see how deep the recursion is.

#include <stdio.h>

int factorial(int n, int depth) {
    for (int i = 0; i < depth; i++) printf("  ");
    printf("factorial(%d) called\n", n);

    if (n <= 1) {
        for (int i = 0; i < depth; i++) printf("  ");
        printf("factorial(%d) returns 1\n", n);
        return 1;
    }

    int result = n * factorial(n - 1, depth + 1);

    for (int i = 0; i < depth; i++) printf("  ");
    printf("factorial(%d) returns %d\n", n, result);
    return result;
}

int main(void) {
    printf("Result: %d\n", factorial(4, 0));
    return 0;
}
factorial(4) called
  factorial(3) called
    factorial(2) called
      factorial(1) called
      factorial(1) returns 1
    factorial(2) returns 2
  factorial(3) returns 6
factorial(4) returns 24
Result: 24

Four calls are made going down, and four returns happen coming back up. At the deepest point, four calls are on the stack at the same time.

Where int and long long overflow

#include <stdio.h>

int factInt(int n) {
    return (n <= 1) ? 1 : n * factInt(n - 1);
}

unsigned long long factULL(int n) {
    return (n <= 1) ? 1ULL : n * factULL(n - 1);
}

int main(void) {
    printf("12! as int                = %d\n", factInt(12));
    printf("12! as unsigned long long = %llu\n", factULL(12));
    printf("13! as unsigned long long = %llu\n", factULL(13));
    printf("20! as unsigned long long = %llu\n", factULL(20));
    return 0;
}
12! as int                = 479001600
12! as unsigned long long = 479001600
13! as unsigned long long = 6227020800
20! as unsigned long long = 2432902008176640000

13! = 6227020800 is larger than the int limit of 2147483647, so factInt(13) would overflow. Signed overflow is undefined behaviour in C, which is why it is not printed here. 21! is too big even for 64 bits.

Recursion or loop?

Both take O(n) time. The loop uses O(1) extra memory, while recursion uses one stack frame per call. For factorial, the loop is the practical choice, and recursion is the classic first example for learning how a function calls itself.

The Java versions are find the factorial of a number using recursion and find the factorial of a number using a loop. The Python version, with both methods, is the factorial program in Python. Another recursion example in C is the Fibonacci series program in C.

TimeO(n), one call per value from n down to 1
SpaceO(n) for the call stack
7

Review before the interview

Common mistakes

  • Leaving out the base case. The function calls itself forever and the program crashes with a stack overflow.
  • Writing the base case as if (n == 1) only. factorial(0) then calls factorial(-1), factorial(-2) and so on without stopping.
  • Using int as the return type and expecting correct values beyond 12!.
  • Printing a long long with %d instead of %lld, which prints a wrong value.

Edge cases to test

  • 0! and 1! both return 1 from the base case.
  • Negative input: factorial is not defined. Check it in main before calling the function.
  • 21! and above overflow even long long. Use a big-number method or a language with big integers.

Interview follow-ups

  • How would you write the same function with a loop instead of recursion?
  • How would you count the trailing zeros of n! without computing it?
  • What is tail recursion, and can factorial be written that way?

Keep practising

Building your programming basics?

CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.

Chat with us