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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.