What is recursion in C?

Recursion means a function calls itself to solve a smaller part of the problem. It must have a base case, otherwise it never stops.

#include <stdio.h>

int factorial(int n) {
    if (n <= 1) return 1;          // base case
    return n * factorial(n - 1);
}

int main(void) {
    printf("%d\n", factorial(5));
    return 0;
}

Output:

Output of the above program is

120

Each call uses stack memory, so a very deep recursion causes a stack overflow. See C Recursion.


Learn more about the similar topics:
Tutorials
C Functions
C Function Arguments and Return Value
C Call by Value and Call by Reference
C Recursion
C Scope and Storage Classes
Exercises & Assignments
Write a C program to find the factorial of a number using recursion
Write a C program to swap two numbers using a function and pointers
Interview Questions & Answers
What is the difference between call by value and call by reference in C?
What is recursion in C?
What is the difference between local and global variables in C?
What are storage classes in C?
What is the use of the static keyword in C?