Published on : 3rd Oct 2021

Recursion in C programming
Definition :
A function can call itself. The process is called recursion and the function is called recursive function. Recursion has two things.
- Base case
- Recursive case
In base case, the function terminates recursion.
In recursive case, the function goes for recursion.
When a function goes for recursion, it creates a stack frame in the stack section.
Source Code :
#include <stdio.h> long fact(int n) { if(n <= 1) return 1; return n * fact(n-1); } int main(int argc, char** argv) { int num = 5; long f = fact(num); printf("%d! = %ld", num, f); return 0; }
Output :
5! = 120
Recursion vs Looping :
Recursion needs an extra stack frame when every time recurs. Looping does not need extra space for every iteration.
Stack Overflow :
When a function recurs more, if there is not enough memory to allocate a stack frame in stack section, it is known as stack overflow.