What are Factorial Using Recursion in C- C Programming Course For Engineering Students

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course | Functions | Lecture 34

Factorial Using Recursion in C

Learn factorial using recursion in C the way embedded engineers need it: how the base case works, how every call gets its own stack frame, and where recursion becomes risky on a small microcontroller.

Welcome to another lecture of our free C programming course on EmbeddedPathashala. Today we study factorial using recursion in C, the classic first example of a function that solves a problem by calling itself. This free C tutorial is written for students who want C programming for embedded systems, so besides the syntax we look at stack usage, integer overflow on 32-bit targets, and when you should prefer a plain loop.

If you are following our free embedded C course from the start, you already know how to declare, define and call functions. Recursion is simply a function call where the callee happens to be the same function. Nothing magical is added to the language; the compiler uses the same call mechanism you have already learned.

What You Will Learn

  • What recursion in C means and the two parts every recursive function must have
  • How to write factorial using recursion in C with a safe, embedded-friendly data type
  • How to trace a recursive call by hand using a call table
  • Why the base case decides whether your program finishes or crashes
  • How large a factorial fits in 16-bit, 32-bit and 64-bit unsigned types
  • When recursion is acceptable in embedded C programming and when to switch to iteration

Prerequisites

  • Function definition, declaration (prototype) and the return statement from the earlier lectures of this chapter
  • Basic if/else and the unsigned integer types
  • A working GCC setup so you can compile and run the examples on your laptop

What Is Recursion in C?

A function is recursive when its body contains a call to itself, directly or through another function. Recursion in C fits problems that can be described in terms of a smaller copy of the same problem. Computing the factorial is the textbook case: the factorial of a number is that number multiplied by the factorial of the number just below it.

Every correct recursive function has exactly two ingredients:

  1. Base case – an input small enough to answer directly, without another call. This is the exit door.
  2. Recursive case – a rule that reduces the problem and calls the same function on the smaller problem. Each call must move closer to the base case.
The two parts of every recursive function
PartQuestion it answersFor factorial
Base caseWhen do I stop calling myself?The value is 0 or 1, answer is 1
Recursive caseHow do I shrink the problem?Multiply n by the factorial of n minus 1
Progress guaranteeDoes each call get closer to the base case?n drops by exactly 1 on every call

The Mathematical Idea Behind Factorial

The factorial of a non-negative integer n, written n!, is the product of all whole numbers from 1 up to n. By convention 0! equals 1. The key observation for recursion is that the definition repeats itself: 5! is just 5 multiplied by 4!, and 4! is 4 multiplied by 3!, and so on until you reach a value you already know.

Factorial definition split into cases
ConditionResultExample
n is 0 or 110! = 1, 1! = 1
n is greater than 1n multiplied by (n – 1)!4! = 4 x 3! = 24

Factorial Using Recursion in C: Complete Program

The program below reads a value, validates it, and prints its factorial. We deliberately use fixed-width types from stdint.h, because on a microcontroller the size of int and long is something you must not guess.

#include <stdio.h>
#include <stdint.h>

#define FACT_LIMIT_U32  12u   /* 13! no longer fits in 32 bits */

/* Returns n! for n in the range 0..12 */
static uint32_t factorial_u32(uint32_t n)
{
    if (n <= 1u) {                    /* base case */
        return 1u;
    }
    return n * factorial_u32(n - 1u); /* recursive case */
}

int main(void)
{
    unsigned int value;

    printf("Enter a number from 0 to %u: ", FACT_LIMIT_U32);
    if (scanf("%u", &value) != 1 || value > FACT_LIMIT_U32) {
        puts("Input rejected");
        return 1;
    }

    printf("%u! = %lu\n", value, (unsigned long)factorial_u32(value));
    return 0;
}

How the Code Works

  • static keeps the helper private to this file, a good habit for embedded C programming where many source files share one image.
  • The base case uses n <= 1u. Treating 1 as a base case saves one needless call compared with stopping only at 0.
  • The recursive case multiplies the current n by the value that the deeper call hands back. The multiplication cannot happen until that deeper call returns.
  • The cast to unsigned long makes the %lu format specifier correct on every platform.
  • Input is validated before the call. A recursive function that trusts its caller is a bug waiting to happen.

Compile and Run

$ gcc -Wall -Wextra -std=c11 -o fact fact.c
$ ./fact
Enter a number from 0 to 12: 5
5! = 120
$ ./fact
Enter a number from 0 to 12: 15
Input rejected

Tracing Factorial Using Recursion in C by Hand

The best way to understand recursion in C is to trace one call. Take factorial_u32(4). The function does not finish its multiplication when it is called. Instead it parks the work, asks a smaller question, and waits. The table shows the descent. Read it from top to bottom.

Going down: each call waits for a smaller call
OrderCallIs n <= 1?What it does next
1factorial_u32(4)NoCalls factorial_u32(3) and waits
2factorial_u32(3)NoCalls factorial_u32(2) and waits
3factorial_u32(2)NoCalls factorial_u32(1) and waits
4factorial_u32(1)YesReturns 1 immediately
Coming back: answers travel up in reverse order
OrderCall that resumesValue receivedValue it returns
5factorial_u32(2)12 x 1 = 2
6factorial_u32(3)23 x 2 = 6
7factorial_u32(4)64 x 6 = 24

Make the Recursion Visible

You can have the program narrate itself. This version adds a depth parameter and prints when each call starts and ends. Use it only for learning, never in production firmware.

#include <stdio.h>
#include <stdint.h>

static uint32_t fact_trace(uint32_t n, unsigned depth)
{
    uint32_t answer;

    printf("%*senter fact(%u)\n", (int)(depth * 2u), "", (unsigned)n);
    answer = (n <= 1u) ? 1u : n * fact_trace(n - 1u, depth + 1u);
    printf("%*sleave fact(%u) = %lu\n", (int)(depth * 2u), "",
           (unsigned)n, (unsigned long)answer);
    return answer;
}

int main(void)
{
    fact_trace(4u, 0u);
    return 0;
}
enter fact(4)
  enter fact(3)
    enter fact(2)
      enter fact(1)
      leave fact(1) = 1
    leave fact(2) = 2
  leave fact(3) = 6
leave fact(4) = 24

Key Insight

There is only one copy of the factorial machine code in memory, but every active call owns a private set of variables on the stack. That is why the nested calls do not disturb each other even though they use the same parameter name.

How Many Calls Does Recursion Make?

For an input n with the base case n <= 1, the function is entered n times when n is at least 1. If your base case is only n == 0, the count rises to n + 1. The difference is tiny here, but the habit of counting calls will matter when we reach Fibonacci, where the number of calls explodes.

Input nCalls with base n <= 1Calls with base n == 0
334
556
101011

Overflow Limits: How Big Can the Factorial Be?

Factorials grow faster than almost anything you will meet in firmware. Choosing the return type is therefore part of the algorithm, not an afterthought. On a typical 32-bit ARM Cortex-M target, int and long are both 32 bits wide, so a book program that stores the result in a long overflows after 12! on such a chip.

TypeLargest n whose n! fitsValue of that n!
uint8_t5120
uint16_t840320
uint32_t12479001600
uint64_t202432902008176640000
Warning: Unsigned overflow in C wraps around silently, and signed overflow is undefined behaviour. Your factorial will happily print a wrong number instead of failing loudly. Always check the input range first.

A Second Recursive Example: Sum of Digits

Factorial is not the only shape recursion takes. Here is a function that adds the decimal digits of a number. The idea: the digit sum of a number is its last digit plus the digit sum of everything before that digit.

static unsigned digit_sum(unsigned long value)
{
    if (value < 10ul) {                      /* base case: one digit left */
        return (unsigned)value;
    }
    return (unsigned)(value % 10ul) + digit_sum(value / 10ul);
}

For the input 4821 the calls reduce the value to 482, then 48, then 4, which is the base case. The answers come back as 4, then 4 + 8, then 12 + 2, then 14 + 1, giving 15. Notice that the problem shrinks by dividing, not by subtracting one, which shows that “smaller” can mean many things as long as you reach the base case.

Recursion vs Iteration in Embedded C Programming

Any recursive factorial can be rewritten with a loop. In desktop software the choice is mostly about readability. In embedded C programming the choice also affects RAM, because each pending call consumes stack.

AspectRecursive factorialLoop-based factorial
Stack useGrows with nConstant
Readability for recursive definitionsVery close to the mathsSlightly less direct
SpeedCall overhead per stepUsually faster
Worst failureStack overflowWrong answer on overflow only
Static analysis friendlinessHard to boundEasy to bound

Real-World Use Cases

  • Walking tree-shaped data such as directory structures or a parsed configuration
  • Divide-and-conquer algorithms like quicksort and binary search
  • Parsers for expressions and protocol messages with nested fields
  • Mathematical helpers such as greatest common divisor, power and combinations

Many safety standards used in automotive and medical firmware discourage or forbid recursion, because the maximum stack depth cannot be proven. Know the rule of your project before you use it.

Common Mistakes and Troubleshooting

SymptomLikely causeFix
Program crashes with segmentation fault on a PC, or resets on a microcontrollerMissing or unreachable base case, so the stack fills upCheck that every path either returns a constant or shrinks the input
Result is negative or tiny for a moderate inputInteger overflow in the result typeUse a wider type and validate the range
Wrong answer for 0Base case forgotten or written as n == 1 onlyUse n <= 1
Infinite descent for negative inputSigned parameter walks away from the base caseUse an unsigned parameter or reject negatives
Compiler warns about format mismatchUsing %d for a long resultMatch specifier and type, cast if needed

Best Practices, Performance and Security

  • Write the base case first, then the recursive case.
  • Validate arguments before the first call, not inside every call.
  • Prefer fixed-width unsigned types for results in firmware.
  • Estimate the worst-case depth and multiply by the frame size to check it fits your stack budget.
  • Performance: each call pushes a return address and saved registers, so deep recursion costs time as well as memory. Enable optimisation and compare against a loop.
  • Security: if recursion depth depends on external input such as a network packet, an attacker can force a stack overflow. Cap the depth explicitly.

Summary and Key Takeaways

  • Recursion in C means a function calling itself on a smaller problem.
  • A base case and a shrinking recursive case are both mandatory.
  • Factorial using recursion in C waits for deeper calls and then multiplies on the way back.
  • Result types overflow quickly: 12! is the limit for 32-bit unsigned values.
  • Every active call uses stack, so depth matters in embedded systems.

Conclusion

You now know how factorial using recursion in C works from the mathematical definition down to the stack. You can trace a call by hand, pick a safe return type, and decide whether recursion suits your target. In the next lecture of this free C programming course we look closely at the two phases of recursion and write a recursive power function.

Frequently Asked Questions

What is recursion in C in simple words?

It is a function that solves a problem by calling itself with a smaller version of the same problem until it reaches a case it can answer directly.

Why does factorial using recursion in C need a base case?

Without it the function would keep calling itself forever until the stack runs out of memory and the program crashes.

Is a loop better than recursion for factorial in embedded systems?

Usually yes. A loop uses constant stack and is easy to analyse, while recursion uses stack in proportion to the input.

What is the largest factorial a 32-bit unsigned integer can hold?

12 factorial, which is 479001600. The next value, 13 factorial, needs more than 32 bits.

Can recursion be used in MISRA C or safety-critical firmware?

Many coding standards prohibit it because the maximum stack depth cannot be proven statically. Check your project rules.

Does each recursive call get its own copy of the function code?

No. The code exists once. Each call gets its own stack frame holding parameters, locals and the return address.

Continue Your Free C Tutorial

EmbeddedPathashala offers a complete free embedded C course with worked examples, quizzes and interview questions. Keep going to master C programming for embedded systems.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →