# Principles of Recursion in Data Structures

Data StructureAnalysis of AlgorithmsAlgorithms

The recursion is a process by which a function calls itself. We use recursion to solve bigger problem into smaller sub-problems. One thing we have to keep in mind, that if each sub-problem is following same kind of patterns, then only we can use the recursive approach.

A recursive function has two different parts. The base case and the recursive case. The base case is used to terminate the task of recurring. If base case is not defined, then the function will recur infinite number of times (Theoretically).

In computer program, when we call one function, the value of the program counter is stored into the internal stack before jumping into the function area. After completing the task, it pops out the address and assign it into the program counter, then resume the task. During recursive call, it will store the address multiple times, and jumps into the next function call statement. If one base case is not defined, it will recur again and again, and store address into stack. If the stack has no space anymore, it will raise an error as “Internal Stack Overflow”.

One example of recursive call is finding the factorial of a number. We can see that the factorial of a number n = n! is same as the n * (n-1)!, again it is same as n * (n - 1) * (n - 2)!. So if the factorial is a function, then it will be called again and again, but the argument is decreased by 1. When the argument is 1 or 0, it will return 1. This could be the base case of the recursion.

## Example

Live Demo

#include<iostream>
using namespace std;
long fact(long n){
if(n <= 1)
return 1;
return n * fact(n-1);
}
main(){
cout << "Factorial of 6: " << fact(6);
}

## Output

Factorial of 6: 720
Published on 26-Aug-2019 14:54:06