Recursion
• Recursion is the ability of a function to call itself.
• It is often used to solve problems that can be divided
into smaller, similar sub-problems — for example:
factorial, sum of numbers, Fibonacci series, etc.
How Recursion Works
When a recursive function calls itself, it must have a
stopping condition, known as the base case, to prevent
it from repeating forever.
Example: Recursive Function to Add Numbers
This program calculates the sum of numbers from n down to 1
👉 (i.e. n + (n-1) + (n-2) + … + 2 + 1)
#include <stdio.h>
int add(int); // Function declaration
int main(void) {
int num, ans;
printf("Enter any number: ");
scanf("%d", &num);
ans = add(num);
printf("Answer = %d", ans);
return 0;
}
// Recursive function definition
int add(int n) {
if (n == 1)
return 1; // Base case: stop recursion
else
return n + add(n - 1); // Recursive call
}
OUTPUT:
If the user enters 4, then:
add(4) = 4 + add(3)
add(3) = 3 + add(2)
add(2) = 2 + add(1)
add(1) = 1(base case)
add(4) = 4 + 3 + 2 + 1 = 10