Recursion
Recursion
Recursion
Contributors:
Ms Ridmi Wimalasiri
•Recursion in C++ is a
technique in which a function
calls itself repeatedly until a
given condition is satisfied.
•Recursion is the process of
solving a problem by
breaking it down into smaller,
simpler sub-problems.
Recursive Function
• A function that calls itself is called a recursive function. When a recursive
function is called, it executes a set of instructions and then calls itself to
execute the same set of instructions with a smaller input. This process
continues until a base case is reached, which is a condition that stops the
recursion and returns a value.
Base Condition
• The base condition is the condition that is used to terminate the
recursion. The recursive function will keep calling itself till the base
condition is satisfied.
int Sum(int n)
{
// base condition to terminate the recursion when N = 0
if (n == 0) {
return 0;
}
return res;
}
int factorial(int n) {
// Factorial of 0 or 1 is 1
if (n == 0 || n == 1)
return 1;