Evaluate f(x) Using Recursion in C

Written: August 14, 2026 · Updated: August 15, 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)=nf(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

Keep learning

If this walkthrough on Evaluate f(x) Using Recursion in C helped, open the code again and change one input or assumption. Small experiments beat rereading the same example.

Want more step-by-step tutorials like this? Browse blog.xqa.io — and tell us which topic you want next.

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 ✨