Introduction to Recursion
Definition
Recursion is a technique where a function calls itself to solve a problem.
Important Points
Self Calling → Function calls itself.
Base Condition → Stops the recursion.
Recursive Call → Function calls itself again.
Syntax
return_type function_name()
{
if(condition)
return;
function_name();
}
Easy Point (Remember)
✅ Recursion = Function calling itself.
One-Line Definition
Recursion → A function calling itself repeatedly until a base condition is met.
Factorial Using Recursion
Definition
The factorial of a number is the product of all positive integers from 1 to that
number.
Formula
5! = 5 × 4 × 3 × 2 × 1 = 120
Important Points
Base Condition → n == 1
Recursive Call → factorial(n-1)
Return Type → int
Program
#include <stdio.h>
int factorial(int n)
{
if(n == 1)
return 1;
return n * factorial(n - 1);
}
int main()
{
printf("%d", factorial(5));
return 0;
}
Output
120
Easy Point (Remember)
✅ Factorial = n × factorial(n-1)
One-Line Definition
Factorial → Product of all positive integers from 1 to n.
Fibonacci Using Recursion
Definition
A Fibonacci series is a sequence where each number is the sum of the previous
two numbers.
Series
0 1 1 2 3 5 8 13 ...
Important Points
Base Condition
o fib(0) = 0
o fib(1) = 1
Recursive Formula
o fib(n) = fib(n-1) + fib(n-2)
Program
#include <stdio.h>
int fib(int n)
{
if(n == 0)
return 0;
if(n == 1)
return 1;
return fib(n-1) + fib(n-2);
}
int main()
{
int n = 7;
for(int i = 0; i < n; i++)
{
printf("%d ", fib(i));
}
return 0;
}
Output
0112358
Easy Point (Remember)
✅ Next Number = Previous Number + Previous Previous Number
One-Line Definition
Fibonacci Series → A series where each term is the sum of the previous two
terms.