What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
Types of Recursions:
Recursion are mainly of two types depending on whether a function calls itself from within itself or more than one function call one another mutually. The first one is called direct recursion and another one is called indirect recursion. Thus, the two types of recursion are:
1. Direct Recursion: These can be further categorized into four types:
- Tail Recursion: If a recursive function calling itself and that recursive call is the last statement in the function then it's known as Tail Recursion. After that call the recursive function performs nothing. The function has to process or perform any operation at the time of calling and it does nothing at returning time.
Example:
C++
// Code Showing Tail Recursion
#include <iostream>
using namespace std;
// Recursion function
void fun(int n)
{
if (n > 0) {
cout << n << " ";
// Last statement in the function
fun(n - 1);
}
}
// Driver Code
int main()
{
int x = 3;
fun(x);
return 0;
}
// This code is contributed by shubhamsingh10
C
// Code Showing Tail Recursion
#include <stdio.h>
// Recursion function
void fun(int n)
{
if (n > 0) {
printf("%d ", n);
// Last statement in the function
fun(n - 1);
}
}
// Driver Code
int main()
{
int x = 3;
fun(x);
return 0;
}
Java
// Java code Showing Tail Recursion
class GFG {
// Recursion function
static void fun(int n)
{
if (n > 0)
{
System.out.print(n + " ");
// Last statement in the function
fun(n - 1);
}
}
// Driver Code
public static void main(String[] args)
{
int x = 3;
fun(x);
}
}
// This code is contributed by pratham76.
Python3
# Code Showing Tail Recursion
# Recursion function
def fun(n):
if (n > 0):
print(n, end=" ")
# Last statement in the function
fun(n - 1)
# Driver Code
x = 3
fun(x)
# This code is contributed by Shubhamsingh10
C#
// C# code Showing Tail Recursion
using System;
class GFG
{
// Recursion function
static void fun(int n)
{
if (n > 0)
{
Console.Write(n + " ");
// Last statement in the function
fun(n - 1);
}
}
// Driver Code
public static void Main(string[] args)
{
int x = 3;
fun(x);
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// Javascript code Showing Tail Recursion
// Recursion function
function fun(n)
{
if (n > 0)
{
document.write(n + " ");
// Last statement in the function
fun(n - 1);
}
}
// Driver Code
var x = 3;
fun(x);
// This code is contributed by shivanisinghss2110
</script>
Let's understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.

Time Complexity For Tail Recursion : O(n)
Space Complexity For Tail Recursion : O(n)
Note: Time & Space Complexity is given for this specific example. It may vary for another example.
Let's now converting Tail Recursion into Loop and compare each other in terms of Time & Space Complexity and decide which is more efficient.
C++
// Converting Tail Recursion into Loop
#include <iostream>
using namespace std;
void fun(int y)
{
while (y > 0) {
cout << y << " ";
y--;
}
}
// Driver code
int main()
{
int x = 3;
fun(x);
return 0;
}
//This Code is contributed by Shubhamsingh10
C
// Converting Tail Recursion into Loop
#include <stdio.h>
void fun(int y)
{
while (y > 0) {
printf("%d ", y);
y--;
}
}
// Driver code
int main()
{
int x = 3;
fun(x);
return 0;
}
Java
// Converting Tail Recursion into Loop
import java.io.*;
class GFG
{
static void fun(int y)
{
while (y > 0) {
System.out.print(" "+ y);
y--;
}
}
// Driver code
public static void main(String[] args)
{
int x = 3;
fun(x);
}
}
// This code is contributed by shivanisinghss2110
Python3
# Converting Tail Recursion into Loop
def fun(y):
while (y > 0):
print(y , end = " ")
y -= 1
# Driver code
x = 3
fun(x)
# This Code is contributed by shivanisinghss2110
C#
// Converting Tail Recursion into Loop
using System;
class GFG
{
static void fun(int y)
{
while (y > 0) {
Console.Write(" "+ y);
y--;
}
}
// Driver code
public static void Main(String[] args)
{
int x = 3;
fun(x);
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
function fun(y)
{
while (y > 0) {
document.write(" "+ y);
y--;
}
}
// Driver code
var x = 3;
fun(x);
// This code is contributed by shivanisinghss2110
</script>
Time Complexity: O(n)
Space Complexity: O(1)
Note: Time & Space Complexity is given for this specific example. It may vary for another example.
So it was seen that in case of loop the Space Complexity is O(1) so it was better to write code in loop instead of tail recursion in terms of Space Complexity which is more efficient than tail recursion.
Why space complexity is less in case of loop ?
Before explaining this I am assuming that you are familiar with the knowledge that's how the data stored in main memory during execution of a program. In brief,when the program executes,the main memory divided into three parts. One part for code section, the second one is heap memory and another one is stack memory. Remember that the program can directly access only the stack memory, it can't directly access the heap memory so we need the help of pointer to access the heap memory.
Let's now understand why space complexity is less in case of loop ?
In case of loop when function "(void fun(int y))" executes there only one activation record created in stack memory(activation record created for only 'y' variable) so it takes only 'one' unit of memory inside stack so it's space complexity is O(1) but in case of recursive function every time it calls itself for each call a separate activation record created in stack.So if there's 'n' no of call then it takes 'n' unit of memory inside stack so it's space complexity is O(n).
- Head Recursion: If a recursive function calling itself and that recursive call is the first statement in the function then it's known as Head Recursion. There's no statement, no operation before the call. The function doesn't have to process or perform any operation at the time of calling and all operations are done at returning time.
Example:
C++
// C++ program showing Head Recursion
#include <bits/stdc++.h>
using namespace std;
// Recursive function
void fun(int n)
{
if (n > 0) {
// First statement in the function
fun(n - 1);
cout << " "<< n;
}
}
// Driver code
int main()
{
int x = 3;
fun(x);
return 0;
}
// this code is contributed by shivanisinghss2110
C
// C program showing Head Recursion
#include <stdio.h>
// Recursive function
void fun(int n)
{
if (n > 0) {
// First statement in the function
fun(n - 1);
printf("%d ", n);
}
}
// Driver code
int main()
{
int x = 3;
fun(x);
return 0;
}
Java
// Java program showing Head Recursion
import java.io.*;
class GFG{
// Recursive function
static void fun(int n)
{
if (n > 0) {
// First statement in the function
fun(n - 1);
System.out.print(" "+ n);
}
}
// Driver code
public static void main(String[] args)
{
int x = 3;
fun(x);
}
}
// This code is contributed by shivanisinghss2110
Python3
# Python program showing Head Recursion
# Recursive function
def fun(n):
if (n > 0):
# First statement in the function
fun(n - 1)
print(n,end=" ")
# Driver code
x = 3
fun(x)
# this code is contributed by shivanisinghss2110
C#
// Java program showing Head Recursion
using System;
class GFG{
// Recursive function
static void fun(int n)
{
if (n > 0) {
// First statement in the function
fun(n - 1);
Console.Write(" "+ n);
}
}
// Driver code
public static void Main(String[] args)
{
int x = 3;
fun(x);
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
// JavaScript program showing Head Recursion
// Recursive function
function fun(n)
{
if (n > 0) {
// First statement in the function
fun(n - 1);
document.write(" "+ n);
}
}
// Driver code
var x = 3;
fun(x);
// This code is contributed by shivanisinghss2110
</script>
Let's understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.

Time Complexity For Head Recursion: O(n)
Space Complexity For Head Recursion: O(n)
Note: Time & Space Complexity is given for this specific example. It may vary for another example.
Note: Head recursion can't easily convert into loop as Tail Recursion but it can. Let's convert the above code into the loop.
C++
// Converting Head Recursion into Loop
#include <iostream>
using namespace std;
// Recursive function
void fun(int n)
{
int i = 1;
while (i <= n) {
cout <<" "<< i;
i++;
}
}
// Driver code
int main()
{
int x = 3;
fun(x);
return 0;
}
// this code is contributed by shivanisinghss2110
C
// Converting Head Recursion into Loop
#include <stdio.h>
// Recursive function
void fun(int n)
{
int i = 1;
while (i <= n) {
printf("%d ", i);
i++;
}
}
// Driver code
int main()
{
int x = 3;
fun(x);
return 0;
}
Java
// Converting Head Recursion into Loop
import java.util.*;
class GFG
{
// Recursive function
static void fun(int n)
{
int i = 1;
while (i <= n) {
System.out.print(" "+ i);
i++;
}
}
// Driver code
public static void main(String[] args)
{
int x = 3;
fun(x);
}
}
// this code is contributed by shivanisinghss2110
Python3
# Converting Head Recursion into Loop
# Recursive function
def fun(n):
i = 1
while (i <= n):
print(i,end=" ")
i+=1
# Driver code
x = 3
fun(x)
# This code is contributed by shivanisinghss2110
C#
// Converting Head Recursion into Loop
using System;
class GFG
{
// Recursive function
static void fun(int n)
{
int i = 1;
while (i <= n) {
Console.Write(" "+ i);
i++;
}
}
// Driver code
public static void Main(String[] args)
{
int x = 3;
fun(x);
}
}
// this code is contributed by shivanisinghss2110
JavaScript
<script>
// Converting Head Recursion into Loop
// Recursive function
function fun(n)
{
var i = 1;
while (i <= n) {
document.write(" "+ i);
i++;
}
}
// Driver code
var x = 3;
fun(x);
// this code is contributed by shivanisinghss2110
</script>
- Tree Recursion: To understand Tree Recursion let's first understand Linear Recursion. If a recursive function calling itself for one time then it's known as Linear Recursion. Otherwise if a recursive function calling itself for more than one time then it's known as Tree Recursion.
Example:
Pseudo Code for linear recursion
fun(n)
{
// some code
if(n>0)
{
fun(n-1); // Calling itself only once
}
// some code
}
Program for tree recursion
C++
// C++ program to show Tree Recursion
#include <iostream>
using namespace std;
// Recursive function
void fun(int n)
{
if (n > 0)
{
cout << " " << n;
// Calling once
fun(n - 1);
// Calling twice
fun(n - 1);
}
}
// Driver code
int main()
{
fun(3);
return 0;
}
// This code is contributed by shivanisinghss2110
C
// C program to show Tree Recursion
#include <stdio.h>
// Recursive function
void fun(int n)
{
if (n > 0) {
printf("%d ", n);
// Calling once
fun(n - 1);
// Calling twice
fun(n - 1);
}
}
// Driver code
int main()
{
fun(3);
return 0;
}
Java
// Java program to show Tree Recursion
class GFG
{
// Recursive function
static void fun(int n)
{
if (n > 0) {
System.out.print(" "+ n);
// Calling once
fun(n - 1);
// Calling twice
fun(n - 1);
}
}
// Driver code
public static void main(String[] args)
{
fun(3);
}
}
// This code is contributed by shivanisinghss2110
Python3
# C++ program to show Tree Recursion
# Recursive function
def fun(n):
if (n > 0):
print(n, end=" ")
# Calling once
fun(n - 1)
# Calling twice
fun(n - 1)
# Driver code
fun(3)
# This code is contributed by shivanisinghss2110
C#
// C# program to show Tree Recursion
using System;
class GFG
{
// Recursive function
static void fun(int n)
{
if (n > 0) {
Console.Write(" "+ n);
// Calling once
fun(n - 1);
// Calling twice
fun(n - 1);
}
}
// Driver code
public static void Main(String[] args)
{
fun(3);
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
// JavaScript program to show Tree Recursion
// Recursive function
function fun(n)
{
if (n > 0) {
document.write(" "+ n);
// Calling once
fun(n - 1);
// Calling twice
fun(n - 1);
}
}
// Driver code
fun(3);
// This code is contributed by shivanisinghss2110
</script>
Let's understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.

Time Complexity For Tree Recursion: O(2^n)
Space Complexity For Tree Recursion: O(n)
Note: Time & Space Complexity is given for this specific example. It may vary for another example.
- Nested Recursion: In this recursion, a recursive function will pass the parameter as a recursive call. That means "recursion inside recursion". Let see the example to understand this recursion.
Example:
C++
// C++ program to show Nested Recursion
#include <iostream>
using namespace std;
int fun(int n)
{
if (n > 100)
return n - 10;
// A recursive function passing parameter
// as a recursive call or recursion inside
// the recursion
return fun(fun(n + 11));
}
// Driver code
int main()
{
int r;
r = fun(95);
cout << " " << r;
return 0;
}
// This code is contributed by shivanisinghss2110
C
// C program to show Nested Recursion
#include <stdio.h>
int fun(int n)
{
if (n > 100)
return n - 10;
// A recursive function passing parameter
// as a recursive call or recursion
// inside the recursion
return fun(fun(n + 11));
}
// Driver code
int main()
{
int r;
r = fun(95);
printf("%d\n", r);
return 0;
}
Java
// Java program to show Nested Recursion
import java.util.*;
class GFG {
static int fun(int n)
{
if (n > 100)
return n - 10;
// A recursive function passing parameter
// as a recursive call or recursion
// inside the recursion
return fun(fun(n + 11));
}
// Driver code
public static void main(String args[])
{
int r;
r = fun(95);
System.out.print(" "+ r);
}
}
// This code is contributed by shivanisinghss2110
Python3
# Python program to show Nested Recursion
def fun(n):
if (n > 100):
return n - 10
# A recursive function passing parameter
# as a recursive call or recursion inside
# the recursion
return fun(fun(n + 11))
# Driver code
r = fun(95)
print("", r)
# This code is contributed by shivanisinghss2110
C#
// C# program to show Nested Recursion
using System;
class GFG {
static int fun(int n)
{
if (n > 100)
return n - 10;
// A recursive function passing parameter
// as a recursive call or recursion
// inside the recursion
return fun(fun(n + 11));
}
// Driver code
public static void Main(String []args)
{
int r;
r = fun(95);
Console.Write(" "+ r);
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
// JavaScript program to show Nested Recursion
function fun( n)
{
if (n > 100)
return n - 10;
// A recursive function passing parameter
// as a recursive call or recursion
// inside the recursion
return fun(fun(n + 11));
}
// Driver code
var r;
r = fun(95);
document.write(" "+ r);
// This code is contributed by shivanisinghss2110
</script>
Let's understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.

2. Indirect Recursion: In this recursion, there may be more than one functions and they are calling one another in a circular manner.

From the above diagram fun(A) is calling for fun(B), fun(B) is calling for fun(C) and fun(C) is calling for fun(A) and thus it makes a cycle.
Example:
C++
// C++ program to show Indirect Recursion
#include <iostream>
using namespace std;
void funB(int n);
void funA(int n)
{
if (n > 0) {
cout <<" "<< n;
// fun(A) is calling fun(B)
funB(n - 1);
}
}
void funB(int n)
{
if (n > 1) {
cout <<" "<< n;
// fun(B) is calling fun(A)
funA(n / 2);
}
}
// Driver code
int main()
{
funA(20);
return 0;
}
// this code is contributed by shivanisinghss2110
C
// C program to show Indirect Recursion
#include <stdio.h>
void funB(int n);
void funA(int n)
{
if (n > 0) {
printf("%d ", n);
// Fun(A) is calling fun(B)
funB(n - 1);
}
}
void funB(int n)
{
if (n > 1) {
printf("%d ", n);
// Fun(B) is calling fun(A)
funA(n / 2);
}
}
// Driver code
int main()
{
funA(20);
return 0;
}
Java
// Java program to show Indirect Recursion
import java.io.*;
class GFG{
static void funA(int n)
{
if (n > 0) {
System.out.print(" " +n);
// Fun(A) is calling fun(B)
funB(n - 1);
}
}
static void funB(int n)
{
if (n > 1) {
System.out.print(" " +n);
// Fun(B) is calling fun(A)
funA(n / 2);
}
}
// Driver code
public static void main (String[] args)
{
funA(20);
}
}
// This code is contributed by shivanisinghss2110
C#
// C# program to show Indirect Recursion
using System;
class GFG{
static void funA(int n)
{
if (n > 0) {
Console.Write(" " +n);
// Fun(A) is calling fun(B)
funB(n - 1);
}
}
static void funB(int n)
{
if (n > 1) {
Console.Write(" " +n);
// Fun(B) is calling fun(A)
funA(n / 2);
}
}
// Driver code
public static void Main (String[] args)
{
funA(20);
}
}
// This code is contributed by shivanisinghss2110
Python3
# Python program to show Indirect Recursion
def funA(n):
if (n > 0):
print("", n, end='')
# Fun(A) is calling fun(B)
funB(n - 1)
def funB( n):
if (n > 1):
print("", n, end='')
# Fun(B) is calling fun(A)
funA(n // 2)
# Driver code
funA(20)
# This code is contributed by shivanisinghss2110
JavaScript
<script>
// JavaScript program to show Indirect Recursion
function funA(n)
{
if (n > 0) {
document.write(n.toFixed(0) + "</br>");
// Fun(A) is calling fun(B)
funB(n - 1);
}
}
function funB(n)
{
if (n > 1) {
document.write(n.toFixed(0) + "</br>");
// Fun(B) is calling fun(A)
funA(n / 2);
}
}
// Driver code
funA(20);
// this code is contributed by shivanisinghss2110
</script>
Let's understand the example by tracing tree of recursive function. That is how the calls are made and how the outputs are produced.

Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem