recursion c
recursion c
UNDERSTANDING
RECURSIONS IN C LANGUAGE
Recursion is a technique in programming where a function calls itself directly or indirectly to solve a
problem. It is widely used for problems that can be broken down into smaller subproblems with a
base case to stop the recursion.
2. Recursive Case: The part of the function where it calls itself with a smaller or simpler input.
3. Stack Memory Usage: Each recursive call is stored in the call stack, and when the base case
is met, the stack starts unwinding.
return_type function_name(parameters)
if (base_condition)
else
#include <stdio.h>
int factorial(int n)
if (n == 0) // Base case
return 1;
else
}
int main()
int num = 5;
return 0;
factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1 * factorial(0)
• 1*1=1
• 2*1=2
• 3*2=6
• 4 * 6 = 24
• 5 * 24 = 120
sum(123)=1+2+3=6
#include <stdio.h>
int sumOfDigits(int n)
if (n == 0) // Base case
return 0;
return (n % 10) + sumOfDigits(n / 10); // Recursive call
int main()
return 0;
Execution Breakdown
sumOfDigits(1234) = 4 + sumOfDigits(123)
sumOfDigits(123) = 3 + sumOfDigits(12)
sumOfDigits(12) = 2 + sumOfDigits(1)
sumOfDigits(1) = 1 + sumOfDigits(0)
Now it returns:
• 1+0=1
• 2+1=3
• 3+3=6
• 4 + 6 = 10
Types of Recursion
1. Direct Recursion
void functionA()
if (condition)
return;
functionA();
2. Indirect Recursion
• A function calls another function, which calls the first function again.
void functionA();
void functionB();
void functionA()
if (condition)
return;
functionB();
void functionB()
if (condition)
return;
functionA();
Example:
#include <stdio.h>
void even(int n)
if (n == 0)
printf("Even\n");
else
odd(n - 1);
}
void odd(int n)
if (n == 0)
printf("Odd\n");
else
even(n - 1);
int main()
return 0;
3. Tail Recursion
void tailRecursion(int n)
if (n == 0)
return;
#include <stdio.h>
void printNumbers(int n)
if (n == 0)
return;
printNumbers(n - 1);
}
int main()
printNumbers(5);
return 0;
Output: 5 4 3 2 1
4. Non-Tail Recursion
int nonTailRecursion(int n)
if (n == 0) return 0;
#include <stdio.h>
int sum(int n)
if (n == 0) return 0;
int main()
return 0;
Advantages
• Simplifies complex problems like tree traversal, factorial, Fibonacci.
Disadvantages
Given an integer n, write a recursive function to find the sum of its digits.
Step-by-Step Solution
• The sum of digits can be broken down into the last digit and the sum of the remaining digits.
#include <stdio.h>
int sumOfDigits(int n)
{
return n;
int main()
return 0;
Output:
✔ How It Works?
sumOfDigits(1234) = 4 + sumOfDigits(123)
sumOfDigits(123) = 3 + sumOfDigits(12)
sumOfDigits(12) = 2 + sumOfDigits(1)
Final result: 4 + 3 + 2 + 1 = 10
Conclusion
Here are five problems for each type of recursion, along with hints on how to solve them.
1. Direct Recursion Problems
3. Reverse a number
(One function calls another function, which calls the first one back)
2. Reverse a string