Evaluate f(x) Using Recursion in C

Written: August 14, 2026

Recursion needs a clear base case and a smaller subproblem. Factorial is the clearest first demo.

This walkthrough keeps the logic small and readable so you can type it, run it, and then change one input at a time to see what happens.

What you will build

We treat f(n) = n! so f(0)=1 and f(n)=n*f(n-1). That mirrors how many GTU recursion labs begin.

  • Define long factorial(int n)
  • Return 1 when n is 0 or 1
  • Otherwise return n * factorial(n-1)
  • Print f(n) for a small n

Working C example

#include <stdio.h>

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

int main(void) {
    int n;
    printf("Enter n (0-12): ");
    if (scanf("%d", &n) != 1 || n < 0 || n > 12) return 1;
    printf("f(%d) = %ld\n", n, factorial(n));
    return 0;
}

Advertisement

How the logic works

Read the program top to bottom: includes and main first, then the statements that change variables, then the print that proves the result.

If your output looks wrong, print the variables before and after the critical lines. That single habit catches most beginner bugs faster than rewriting the whole file.

Always protect the base case first. Without it, recursion becomes an infinite call stack.

Advertisement

Common mistakes

Forgetting a semicolon, using the wrong format specifier in printf/scanf, and mixing up assignment (=) with comparison (==) are the usual culprits.

Compile with warnings enabled (`gcc -Wall`) so the compiler points at risky casts and unused variables before you chase them by hand.

Try this next

Change the sample inputs, add a second test case, and briefly note what stayed the same. Teaching yourself with tiny experiments sticks better than copying a longer program you never run.

When you can explain every line without looking, you are ready for the next exercise in the series.

Advertisement

Previous Article

C Program to Swap Values Using Pointers

Next Article

Add First N Numbers in C Using a Function

Write a Comment

Leave a Comment

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

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨