recursion
recursion
Operations
🌀 1. RECURSION
🔹 What is Recursion?
Recursion is a programming technique where a function calls itself to solve smaller
instances of the same problem.
🔹 Structure of a Recursive Function
return_type function_name(parameters) {
if (base_condition) {
// stop recursion
return result;
} else {
// recursive call
return function_name(modified_parameters);
}
}
🔹 Two Key Parts:
Base Case: Stops recursion (prevents infinite calls)
Recursive Case: Calls itself with modified input
✅ Recursive Examples
➤ Factorial
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
➤ Fibonacci Series
int fibonacci(int n) {
if (n == 0 || n == 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
PROGRAM
#include <stdio.h>
int factorial(int n) {
//base case
if(n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
int fibbonacci(int n) {
if(n == 0){
return 0;
} else if(n == 1) {
return 1;
} else {
return (fibbonacci(n-1) + fibbonacci(n-2));
}
}
int main() {
int n = 5;
int i;
for(i = 0;i<n;i++) {
printf("%d ",fibbonacci(i));
}
}
🛠 Usage in Functions
➤ Sum of N Numbers (Recursive)
int sum(int n) {
if (n == 0)
return 0;
else
return n + sum(n - 1);
}
➤ Multiplication Using Recursion
int multiply(int x, int y) {
if (y == 0)
return 0;
else
return x + multiply(x, y - 1);
}