Introduction to Recursion
Last Updated :
25 Dec, 2024
The 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.
- Since called function may further call itself, this process might continue forever. So it is essential to provide a base case to terminate this recursion process.
Need of Recursion
- Recursion helps in logic building. Recursive thinking helps in solving complex problems by breaking them into smaller subproblems.
- Recursive solutions work as a a basis for Dynamic Programming and Divide and Conquer algorithms.
- Certain problems can be solved quite easily using recursion like Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
Steps
Step1 – Define a base case: Identify the simplest (or base) case for which the solution is known or trivial. This is the stopping condition for the recursion, as it prevents the function from infinitely calling itself.
Step2 – Define a recursive case: Define the problem in terms of smaller subproblems. Break the problem down into smaller versions of itself, and call the function recursively to solve each subproblem.
Step3 – Ensure the recursion terminates: Make sure that the recursive function eventually reaches the base case, and does not enter an infinite loop.
step4 – Combine the solutions: Combine the solutions of the subproblems to solve the original problem.
Example 1 : Sum of Natural Numbers
Let us consider a problem to find the sum of natural numbers, there are several ways of doing that but the simplest approach is simply to add the numbers starting from 0 to n. So the function simply looks like this,
approach(1) – Simply adding one by one
f(n) = 0 + 1 + 2 + 3 +……..+ n
but there is another mathematical approach of representing this,
approach(2) – Recursive adding
f(n) = 0 n=0
f(n) = n + f(n-1) n>=1
C++
#include <iostream>
using namespace std;
// Recursive function to find the sum of
// numbers from 0 to n
int findSum(int n)
{
// Base case
if (n == 0)
return 0;
// Recursive case
return n + findSum(n - 1);
}
int main()
{
int n = 5;
cout << findSum(n);
return 0;
}
C
#include <stdio.h>
// Recursive function to find the sum of
// numbers from 0 to n
int findSum(int n)
{
// Base case
if (n == 0)
return 0;
// Recursive case
return n + findSum(n - 1);
}
int main()
{
int n = 5;
printf("%d", findSum(n));
return 0;
}
Java
// Recursive function to find the sum of
// numbers from 0 to n
public class GfG{
public static int findSum(int n) {
// Base case
if (n == 0)
return 0;
// Recursive case
return n + findSum(n - 1);
}
public static void main(String[] args) {
int n = 5;
System.out.println(findSum(n));
}
}
Python
# Recursive function to find the sum of
# numbers from 0 to n
def findSum(n):
# Base case
if n == 0:
return 0
# Recursive case
return n + findSum(n - 1)
n = 5
print(findSum(n))
C#
// Recursive function to find the sum of
// numbers from 0 to n
using System;
class Program {
public static int findSum(int n) {
// Base case
if (n == 0)
return 0;
// Recursive case
return n + findSum(n - 1);
}
static void Main() {
int n = 5;
Console.WriteLine(findSum(n));
}
}
JavaScript
// Recursive function to find the sum of
// numbers from 0 to n
function findSum(n) {
// Base case
if (n === 0)
return 0;
// Recursive case
return n + findSum(n - 1);
}
let n = 5;
console.log(findSum(n));
PHP
<?php
// Recursive function to find the sum of
// numbers from 0 to n
function findSum($n) {
// Base case
if ($n == 0)
return 0;
// Recursive case
return $n + findSum($n - 1);
}
$n = 5;
echo findSum($n);
?>
What is the base condition in recursion?
A recursive program stops at a base condition. There can be more than one base conditions in a recursion. In the above program, the base condition is when n = 1.\
How a particular problem is solved using recursion?
The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions that stop the recursion.
Example 2 : Factorial of a Number
Factorial of a number n (where n >= 0) is defined as multiplication of numbers from 1 to n. To recursive compute, we compute factorial n if we know the factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0.
C++
#include <iostream>
using namespace std;
int fact(int n)
{
// BASE CONDITION
if (n == 0)
return 1;
return n * fact(n - 1);
}
int main()
{
cout << "Factorial of 5 : " << fact(5);
return 0;
}
C
#include <stdio.h>
int fact(int n) {
// BASE CONDITION
if (n == 0)
return 1;
return n * fact(n - 1);
}
int main() {
printf("Factorial of 5 : %d\n", fact(5));
return 0;
}
Java
public class GfG {
public static int fact(int n) {
// BASE CONDITION
if (n == 0)
return 1;
return n * fact(n - 1);
}
public static void main(String[] args) {
System.out.println("Factorial of 5 : " + fact(5));
}
}
Python
def fact(n):
# BASE CONDITION
if n == 0:
return 1
return n * fact(n - 1)
print("Factorial of 5 : ", fact(5))
C#
using System;
class Program {
static int Fact(int n) {
// BASE CONDITION
if (n == 0)
return 1;
return n * Fact(n - 1);
}
static void Main() {
Console.WriteLine("Factorial of 5 : " + Fact(5));
}
}
JavaScript
function fact(n) {
// BASE CONDITION
if (n === 0)
return 1;
return n * fact(n - 1);
}
console.log("Factorial of 5 : " + fact(5));
PHP
<?php
function fact($n) {
// BASE CONDITION
if ($n == 0)
return 1;
return $n * fact($n - 1);
}
echo "Factorial of 5 : " . fact(5);
?>
OutputFactorial of 5 : 120
Illustration of the above code:

When does Stack Overflow error occur in recursion?
If the base case is not reached or not defined, then the stack overflow problem may arise. Let us take an example to understand this.
int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;
else
return n*fact(n-1);
}
If fact(10) is called, it will call fact(9), fact(8), fact(7), and so on but the number will never reach 100. So, the base case is not reached. If the memory is exhausted by these functions on the stack, it will cause a stack overflow error.
What is the difference between direct and indirect recursion?
A function fun is called direct recursive if it calls the same function fun. A function fun is called indirect recursive if it calls another function say fun_new and fun_new calls fun directly or indirectly. The difference between direct and indirect recursion has been illustrated in Table 1.
// An example of direct recursion
void directRecFun()
{
// Some code....
directRecFun();
// Some code...
}
// An example of indirect recursion
void indirectRecFun1()
{
// Some code...
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}
What is the difference between tailed and non-tailed recursion?
A recursive function is tail recursive when a recursive call is the last thing executed by the function. Please refer tail recursion article for details.
How memory is allocated to different function calls in recursion?
Recursion uses more memory to store data of every recursive call in an internal function call stack.
- Whenever we call a function, its record is added to the stack and remains there until the call is finished.
- The internal systems use a stack because function calling follows LIFO structure, the last called function finishes first.
When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to the calling function and a different copy of local variables is created for each function call. When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues.
Let us take the example of how recursion works by taking a simple function.
C++
// A C++ program to demonstrate working of
// recursion
#include <bits/stdc++.h>
using namespace std;
void printFun(int test)
{
if (test < 1)
return;
else {
cout << test << " ";
printFun(test - 1); // statement 2
cout << test << " ";
return;
}
}
// Driver Code
int main()
{
int test = 3;
printFun(test);
}
C
// A C program to demonstrate working of recursion
#include <stdio.h>
void printFun(int test)
{
if (test < 1)
return;
else {
printf("%d ", test);
printFun(test - 1); // statement 2
printf("%d ", test);
return;
}
}
// Driver Code
int main()
{
int test = 3;
printFun(test);
return 0;
}
Java
// A Java program to demonstrate working of
// recursion
class GFG {
static void printFun(int test)
{
if (test < 1)
return;
else {
System.out.printf("%d ", test);
printFun(test - 1); // statement 2
System.out.printf("%d ", test);
return;
}
}
// Driver Code
public static void main(String[] args)
{
int test = 3;
printFun(test);
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python
# A Python 3 program to
# demonstrate working of
# recursion
def printFun(test):
if (test < 1):
return
else:
print(test, end=" ")
printFun(test-1) # statement 2
print(test, end=" ")
return
# Driver Code
test = 3
printFun(test)
# This code is contributed by
# Smitha Dinesh Semwal
C#
// A C# program to demonstrate
// working of recursion
using System;
class GFG {
// function to demonstrate
// working of recursion
static void printFun(int test)
{
if (test < 1)
return;
else {
Console.Write(test + " ");
// statement 2
printFun(test - 1);
Console.Write(test + " ");
return;
}
}
// Driver Code
public static void Main(String[] args)
{
int test = 3;
printFun(test);
}
}
// This code is contributed by Anshul Aggarwal.
JavaScript
// A JavaScript program to demonstrate working of recursion
function printFun(test) {
if (test < 1)
return;
else {
console.log(test);
printFun(test - 1); // statement 2
console.log(test);
return;
}
}
// Driver Code
let test = 3;
printFun(test);
PHP
<?php
// PHP program to demonstrate
// working of recursion
// function to demonstrate
// working of recursion
function printFun($test)
{
if ($test < 1)
return;
else
{
echo("$test ");
// statement 2
printFun($test-1);
echo("$test ");
return;
}
}
// Driver Code
$test = 3;
printFun($test);
// This code is contributed by
// Smitha Dinesh Semwal.
?>
When printFun(3) is called from main(), memory is allocated to printFun(3) and a local variable test is initialized to 3 and statement 1 to 4 are pushed on the stack as shown in below diagram. It first prints ‘3’. In statement 2, printFun(2) is called and memory is allocated to printFun(2) and a local variable test is initialized to 2 and statement 1 to 4 are pushed into the stack. Similarly, printFun(2) calls printFun(1) and printFun(1) calls printFun(0). printFun(0) goes to if statement and it return to printFun(1). The remaining statements of printFun(1) are executed and it returns to printFun(2) and so on. In the output, values from 3 to 1 are printed and then 1 to 3 are printed. The memory stack has been shown in below diagram.

Recursion VS Iteration
| SR No. | Recursion | Iteration |
| 1) | Terminates when the base case becomes true. | Terminates when the loop condition becomes false. |
| 2) | Logic is built in terms of smaller problems. | Logic is built using iterating over something. |
| 3) | Every recursive call needs extra space in the stack memory. | Every iteration does not require any extra space. |
| 4) | Smaller code size. | Larger code size. |
Example 4 : Fibonacci with Recursion
Write a program and recurrence relation to find the Fibonacci series of n where n >= 0.
Mathematical Equation:
n if n == 0, n == 1;
fib(n) = fib(n-1) + fib(n-2) otherwise;
Recurrence Relation:
T(n) = T(n-1) + T(n-2) + O(1)
C++
// C++ code to implement Fibonacci series
#include <bits/stdc++.h>
using namespace std;
// Function for fibonacci
int fib(int n)
{
// Stop condition
if (n == 0)
return 0;
// Stop condition
if (n == 1 || n == 2)
return 1;
// Recursion function
else
return (fib(n - 1) + fib(n - 2));
}
// Driver Code
int main()
{
// Initialize variable n.
int n = 5;
cout<<"Fibonacci series of 5 numbers is: ";
// for loop to print the fibonacci series.
for (int i = 0; i < n; i++)
{
cout<<fib(i)<<" ";
}
return 0;
}
C
// C code to implement Fibonacci series
#include <stdio.h>
// Function for fibonacci
int fib(int n)
{
// Stop condition
if (n == 0)
return 0;
// Stop condition
if (n == 1 || n == 2)
return 1;
// Recursion function
else
return (fib(n - 1) + fib(n - 2));
}
// Driver Code
int main()
{
// Initialize variable n.
int n = 5;
printf("Fibonacci series "
"of %d numbers is: ",
n);
// for loop to print the fibonacci series.
for (int i = 0; i < n; i++) {
printf("%d ", fib(i));
}
return 0;
}
Java
// Java code to implement Fibonacci series
import java.util.*;
class GFG
{
// Function for fibonacci
static int fib(int n)
{
// Stop condition
if (n == 0)
return 0;
// Stop condition
if (n == 1 || n == 2)
return 1;
// Recursion function
else
return (fib(n - 1) + fib(n - 2));
}
// Driver Code
public static void main(String []args)
{
// Initialize variable n.
int n = 5;
System.out.print("Fibonacci series of 5 numbers is: ");
// for loop to print the fibonacci series.
for (int i = 0; i < n; i++)
{
System.out.print(fib(i)+" ");
}
}
}
// This code is contributed by rutvik_56.
Python
# Python code to implement Fibonacci series
# Function for fibonacci
def fib(n):
# Stop condition
if (n == 0):
return 0
# Stop condition
if (n == 1 or n == 2):
return 1
# Recursion function
else:
return (fib(n - 1) + fib(n - 2))
# Driver Code
# Initialize variable n.
n = 5;
print("Fibonacci series of 5 numbers is :",end=" ")
# for loop to print the fibonacci series.
for i in range(0,n):
print(fib(i),end=" ")
C#
using System;
public class GFG
{
// Function for fibonacci
static int fib(int n)
{
// Stop condition
if (n == 0)
return 0;
// Stop condition
if (n == 1 || n == 2)
return 1;
// Recursion function
else
return (fib(n - 1) + fib(n - 2));
}
// Driver Code
static public void Main ()
{
// Initialize variable n.
int n = 5;
Console.Write("Fibonacci series of 5 numbers is: ");
// for loop to print the fibonacci series.
for (int i = 0; i < n; i++)
{
Console.Write(fib(i) + " ");
}
}
}
// This code is contributed by avanitrachhadiya2155
JavaScript
// Function for fibonacci
function fib(n) {
// Stop condition
if (n === 0) return 0;
// Stop condition
if (n === 1 || n === 2) return 1;
// Recursion function
return fib(n - 1) + fib(n - 2);
}
// Driver Code
let n = 5;
console.log("Fibonacci series of 5 numbers is:");
// for loop to print the fibonacci series.
for (let i = 0; i < n; i++) {
console.log(fib(i) + " ");
}
OutputFibonacci series of 5 numbers is: 0 1 1 2 3
Recursion Tree for the above Code:

Example: Real Applications of Recursion in real problems
Recursion is a powerful technique that has many applications in computer science and programming. Here are some of the common applications of recursion:
- Tree and graph traversal: Recursion is frequently used for traversing and searching data structures such as trees and graphs. Recursive algorithms can be used to explore all the nodes or vertices of a tree or graph in a systematic way.
- Sorting algorithms: Recursive algorithms are also used in sorting algorithms such as quicksort and merge sort. These algorithms use recursion to divide the data into smaller subarrays or sublists, sort them, and then merge them back together.
- Divide-and-conquer algorithms: Many algorithms that use a divide-and-conquer approach, such as the binary search algorithm, use recursion to break down the problem into smaller subproblems.
- Fractal generation: Fractal shapes and patterns can be generated using recursive algorithms. For example, the Mandelbrot set is generated by repeatedly applying a recursive formula to complex numbers.
- Backtracking algorithms: Backtracking algorithms are used to solve problems that involve making a sequence of decisions, where each decision depends on the previous ones. These algorithms can be implemented using recursion to explore all possible paths and backtrack when a solution is not found.
- Memoization: Memoization is a technique that involves storing the results of expensive function calls and returning the cached result when the same inputs occur again. Memoization can be implemented using recursive functions to compute and cache the results of subproblems.
These are just a few examples of the many applications of recursion in computer science and programming. Recursion is a versatile and powerful tool that can be used to solve many different types of problems.
What are the disadvantages of recursive programming over iterative programming?
Note every recursive program can be written iteratively and vice versa is also true.
- Recursive programs typically have more space requirements and also more time to maintain the recursion call stack.
- Recursion can make the code more difficult to understand and debug, since it requires thinking about multiple levels of function calls..
What are the advantages of recursive programming over iterative programming?
Summary of Recursion:
- There are two types of cases in recursion i.e. recursive case and a base case.
- The base case is used to terminate the recursive function when the case turns out to be true.
- Each recursive call makes a new copy of that method in the stack memory.
- Infinite recursion may lead to running out of stack memory.
- Examples of Recursive algorithms: Merge Sort, Quick Sort, Tower of Hanoi, Fibonacci Series, Factorial Problem, etc.
Output based practice problems for beginners:
Practice Questions for Recursion | Set 1
Practice Questions for Recursion | Set 2
Practice Questions for Recursion | Set 3
Practice Questions for Recursion | Set 4
Practice Questions for Recursion | Set 5
Practice Questions for Recursion | Set 6
Practice Questions for Recursion | Set 7
Quiz on Recursion
Coding Practice on Recursion:
All Articles on Recursion
Recursive Practice Problems with Solutions
Similar Reads
Introduction to Recursion
The 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
15+ min read
What is Recursion?
Recursion is defined as a process which calls itself directly or indirectly and the corresponding function is called a recursive function. Properties of Recursion: Recursion has some important properties. Some of which are mentioned below: The primary property of recursion is the ability to solve a
2 min read
Difference between Recursion and Iteration
A program is called recursive when an entity calls itself. A program is called iterative when there is a loop (or repetition). Example: Program to find the factorial of a number C/C++ Code // C program to find factorial of given number #include <stdio.h> // ----- Recursion ----- // method to f
8 min read
Types of Recursions
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), Inord
15+ min read
Finite and Infinite Recursion with examples
The process in which a function calls itself directly or indirectly is called Recursion and the corresponding function is called a Recursive function. Using Recursion, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Tr
6 min read
What is Tail Recursion
Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following C++ function print() is tail recursive. C/C++ Code // An example of tail r
8 min read
What is Implicit recursion?
What is Recursion? Recursion is a programming approach where a function repeats an action by calling itself, either directly or indirectly. This enables the function to continue performing the action until a particular condition is satisfied, such as when a particular value is reached or another con
6 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recur
4 min read
Recursive Functions
A Recursive function can be defined as a routine that calls itself directly or indirectly. In other words, a recursive function is a function that solves a problem by solving smaller instances of the same problem. This technique is commonly used in programming to solve problems that can be broken do
4 min read
Difference Between Recursion and Induction
Recursion and induction are fundamental ideas in computer science and mathematics that might be regularly used to solve problems regarding repetitive structures. Recursion is a programming technique in which a function calls itself to solve the problem, whilst induction is a mathematical proof techn
4 min read
Recursion in different languages
Recursion in Python
Recursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks. Python Recursive FunctionIn Python, a recursive function is de
6 min read
Recursion in Java
In Java, Recursion is a process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. A few Java recursion examples are Towers of Hanoi (TOH)
6 min read
Recursion in C#
Recursion is a function that calls itself. Or in other words, recursion is a process where a function calls itself repeatedly until some specified conditions have been completed. It is just like a loop; in the loop, if the condition is satisfied, the function will call itself similarly if the condit
7 min read
How to Understand Recursion in JavaScript ?
In this article, we will understand the basic details which are associated with the understanding part as well as the implementation part of Recursion in JavaScript. Let us first understand what exactly is Recursion. Recursion: We could define recursion formally in simple words, that is, function ca
3 min read
Standard Problems on Recursion
Program for Tower of Hanoi Algorithm
Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C) and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest disk is placed on the top and they are on rod A. The objective of the puzzle is to move the entire stack to another rod
6 min read
Time Complexity Analysis | Tower Of Hanoi (Recursion)
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and
2 min read
Find the value of a number raised to its reverse
Given a number N and its reverse R. The task is to find the number obtained when the number is raised to the power of its own reverse. The answer can be very large, return the result modulo 109+7. Examples: Input : N = 2, R = 2Output: 4Explanation: Number 2 raised to the power of its reverse 2 gives
9 min read
Recursively remove all adjacent duplicates
Given a string S, the task is to remove all its adjacent duplicate characters recursively. Examples: Input: S = "geeksforgeek"Output: "gksforgk"Explanation: g(ee)ksforg(ee)k -> gksforgk Input: S = "abccbccba"Output: ""Explanation: ab(cc)b(cc)ba->abbba->a(bbb)a->aa->(aa)->"" (empty
13 min read
Print 1 to n without using loops
You are given an integer N. Print numbers from 1 to N without the help of loops. Examples: Input: N = 5Output: 1 2 3 4 5Explanation: We have to print numbers from 1 to 5. Input: N = 10Output: 1 2 3 4 5 6 7 8 9 10Explanation: We have to print numbers from 1 to 10. Approach: If we take a look at this
3 min read
Print N to 1 without loop
You are given an integer N. Print numbers from N to 1 without the help of loops. Examples: Input: N = 5Output: 5 4 3 2 1Explanation: We have to print numbers from 5 to 1. Input: N = 10Output: 10 9 8 7 6 5 4 3 2 1Explanation: We have to print numbers from 10 to 1. Approach: If we take a look at this
3 min read
Sort the Queue using Recursion
Given a queue and the task is to sort it using recursion without using any loop. We can only use the following functions of queue: empty(q): Tests whether the queue is empty or not. push(q): Adds a new element to the queue. pop(q): Removes front element from the queue. size(q): Returns the number of
10 min read
Reversing a queue using recursion
Given a queue, write a recursive function to reverse it. Standard operations allowed : enqueue(x) : Add an item x to rear of queue. dequeue() : Remove an item from front of queue. empty() : Checks if a queue is empty or not. Examples : Input : Q = [5, 24, 9, 6, 8, 4, 1, 8, 3, 6] Output : Q = [6, 3,
4 min read
Mean of array using recursion
To find the mean of the elements of the array. Mean = (Sum of elements of the Array) / (Total no of elements in Array) Examples: Input : 1 2 3 4 5 Output : 3 Input : 1 2 3 Output : 2 To find the mean using recursion assume that the problem is already solved for N-1 ie you have to find for n Sum of f
4 min read
Binary to Gray code using recursion
Given the Binary code of a number as a decimal number, we need to convert this into its equivalent Gray Code. Assume that the binary number is in the range of integers. For the larger value, we can take a binary number as string. In gray code, only one bit is changed in 2 consecutive numbers. Exampl
5 min read
Sum of natural numbers using recursion
Given a number n, find sum of first n natural numbers. To calculate the sum, we will use a recursive function recur_sum().Examples : Input : 3 Output : 6 Explanation : 1 + 2 + 3 = 6 Input : 5 Output : 15 Explanation : 1 + 2 + 3 + 4 + 5 = 15 Below is code to find the sum of natural numbers up to n us
3 min read
Delete a linked list using recursion
Given a linked list, the task is to delete the linked list using recursion. Examples: Input: Linked List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: NULLExplanation: Linked List is Deleted Input: Linked List = 1 -> 12 -> 1 -> 4 -> 1 -> NULL Output: NULLExplanation: Linked L
5 min read
Product of 2 Numbers using Recursion
Given two numbers x and y find the product using recursion. Examples : Input : x = 5, y = 2 Output : 10 Input : x = 100, y = 5 Output : 500 Method 1) If x is less than y, swap the two variables value 2) Recursively find y times the sum of x 3) If any of them become zero, return 0 C/C++ Code // C++ P
4 min read
Decimal to binary number using recursion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number. Examples : Input : 7 Output :111 Input :10 Output :1010 We have discussed one iterative solution in below post. Program for Decimal to Binary ConversionBelow is Recursi
6 min read
Sum of array elements using recursion
Given an array of integers, find sum of array elements using recursion. Examples: Input : A[] = {1, 2, 3} Output : 6 1 + 2 + 3 = 6 Input : A[] = {15, 12, 13, 10} Output : 50Recommended ProblemSum of ArraySolve Problem We have discussed iterative solution in below post. Sum of elements in a given arr
3 min read
How to Sort a Stack using Recursion
Given a stack, the task is to sort it using recursion. Example: Input: elements present in stack from top to bottom -3 14 18 -5 30Output: 30 18 14 -3 -5Explanation: The given stack is sorted know 30 > 18 > 14 > -3 > -5 Input: elements present in stack from top to bottom 1 2 3Output: 3 2
14 min read
Reverse a Doubly linked list using recursion
Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked List Algorithm: If list is empty, return Reverse head by swapping head->prev and head->next If prev = NULL it means th
9 min read
Programs for Printing Pyramid Patterns using Recursion
This article is aimed at giving a recursive implementation for pattern printing. Simple triangle pattern: C/C++ Code // C++ code to demonstrate star pattern #include <iostream> using namespace std; // function to print a row void printn(int num) { // base case if (num == 0) return; cout <
15+ min read
DFS traversal of a Tree
Given a Binary tree, Traverse it using DFS using recursion. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. Generally, there are 2 widely used ways for traversing trees: DFS or Depth-F
15+ min read
Length of longest palindromic sub-string : Recursion
Given a string S, the task is to find the length longest sub-string which is a palindromeExamples: Input: S = "aaaabbaa" Output: 6 Explanation: Sub-string "aabbaa" is the longest palindromic sub-string.Input: S = "banana" Output: 5 Explanation: Sub-string "anana" is the longest palindromic sub-strin
8 min read
Count Set-bits of number using Recursion
Given a number N. The task is to find the number of set bits in its binary representation using recursion. Examples: Input : 21 Output : 3 21 represented as 10101 in binary representation Input : 16 Output : 1 16 represented as 10000 in binary representation Approach: First, check the LSB of the num
4 min read
Print reverse of a string using recursion
Write a recursive function to print the reverse of a given string. Code: C/C++ Code // C++ program to reverse a string using recursion #include <bits/stdc++.h> using namespace std; /* Function to print reverse of the passed string */ void reverse(string str) { if(str.size() == 0) { return; } r
9 min read
Print Fibonacci Series in reverse order using Recursion
Given an integer N, the task is to print the first N terms of the Fibonacci series in reverse order using Recursion. Examples: Input: N = 5Output: 3 2 1 1 0Explanation: First five terms are - 0 1 1 2 3. Input: N = 10Output: 34 21 13 8 5 3 2 1 1 0 Approach: The idea is to use recursion in a way that
3 min read
Java Program to Reverse a Sentence Using Recursion
A sentence is a sequence of characters separated by some delimiter. This sequence of characters starts at the 0th index and the last index is at len(string)-1. By reversing the string, we interchange the characters starting at 0th index and place them from the end. The first character becomes the la
2 min read
Program for length of a string using recursion
Given a string calculate length of the string using recursion. Examples: Input : str = "abcd" Output :4 Input : str = "GEEKSFORGEEKS" Output :13 We have discussed 5 Different methods to find length of a string in C++ How to find length of a string without string.h and loop in C? Algorithm: recLen(st
3 min read
Sum of digit of a number using recursion
Given a number, we need to find sum of its digits using recursion.Examples: Input : 12345Output : 15Input : 45632Output :20 The step-by-step process for a better understanding of how the algorithm works. Let the number be 12345. Step 1-> 12345 % 10 which is equal-too 5 + ( send 12345/10 to ne
4 min read
Program to calculate value of nCr using Recursion
Given two numbers N and r, find the value of NCr using recursion Examples: Input: N = 5, r = 2Output: 10Explanation: The value of 5C2 is 10 Input: N = 3, r = 1Output: 3 Approach 1: One very interesting way to find the C(n,r) is the recursive method which is based on the recursive equation. C(n,r) =
5 min read
Find geometric sum of the series using recursion
Given an integer N, we need to find the geometric sum of the following series using recursion. 1 + 1/3 + 1/9 + 1/27 + ... + 1/(3^n) Examples: Input N = 5 Output: 1.49794 Input: N = 7 Output: 1.49977 Approach:In the above-mentioned problem, we are asked to use recursion. We will calculate the last te
3 min read
Bottom View of a Binary Tree using Recursion
Given a Binary Tree, the task is to print the bottom view from left to right using Recursion. Note: If there are multiple bottom-most nodes for a horizontal distance from the root, then the latter one in the level traversal is considered. Examples: Example1: The Green nodes represent the bottom view
12 min read
Convert a String to an Integer using Recursion
Given a string str representing a string, the task is to convert the given string into an integer.Examples: Input: str = "1234" Output: 1234Input: str = "0145" Output: 145 Approach: Write a recursive function that will take the first digit of the string and multiply it with the appropriate power of
4 min read
Tail recursion to calculate sum of array elements.
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last stat
3 min read
Practice Sets on Recursion
Recursive Practice Problems with Solutions
Basics - Recursion Recursive Functions Tail Recursion Strings - Given a string, print all possible palindromic partitions Check if a number is Palindrome Print all possible strings of length k that can be formed from a set of n characters Recursive Implementation of atoi() Find all even length binar
4 min read
Practice Questions for Recursion | Set 1
Explain the functionality of the following functions. Question 1 C/C++ Code int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } C/C++ Code int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } Java Code static int fun1(int x, int y) { if (x ==
5 min read
Practice Questions for Recursion | Set 2
Explain the functionality of the following functions. Question 1 C/C++ Code /* Assume that n is greater than or equal to 1 */ int fun1(int n) { if (n == 1) return 0; else return 1 + fun1(n / 2); } Java Code /* Assume that n is greater than or equal to 1 */ static int fun1(int n) { if (n == 1) return
3 min read
Practice Questions for Recursion | Set 3
Explain the functionality of below recursive functions. Question 1 C/C++ Code void fun1(int n) { int i = 0; if (n > 1) fun1(n - 1); for (i = 0; i < n; i++) cout << " * "; } // This code is contributed by shubhamsingh10 C/C++ Code void fun1(int n) { int i = 0; if (n > 1) fun1
3 min read
Practice Questions for Recursion | Set 4
Question 1 Predict the output of the following program. C/C++ Code #include <iostream> using namespace std; void fun(int x) { if(x > 0) { fun(--x); cout << x <<" "; fun(--x); } } int main() { int a = 4; fun(a); return 0; } // This code is contributed by SHUBHAMSINGH10
6 min read
Practice Questions for Recursion | Set 5
Question 1Predict the output of the following program. What does the following fun() do in general? C/C++ Code #include <iostream> using namespace std; int fun(int a, int b) { if (b == 0) return 0; if (b % 2 == 0) return fun(a + a, b/2); return fun(a + a, b/2) + a; } int main() { cout <<
5 min read
Practice Questions for Recursion | Set 6
Question 1 Consider the following recursive C function. Let len be the length of the string s and num be the number of characters printed on the screen. Give the relation between num and len where len is always greater than 0. [GFGTABS] C++ void abc(char *s) { if(s[0] == '\0') return; abc(s
4 min read
Practice Questions for Recursion | Set 7
Question 1 Predict the output of the following program. What does the following fun() do in general? C/C++ Code #include <iostream> using namespace std; int fun(int n, int* fp) { int t, f; if (n <= 2) { *fp = 1; return 1; } t = fun(n - 1, fp); f = t + *fp; *fp = t; return f; } int main() {
4 min read
Practice questions for Linked List and Recursion
Assume the structure of a Linked List node is as follows. C/C++ Code struct Node { int data; struct Node *next; }; // This code is contributed by SHUBHAMSINGH10 C/C++ Code struct Node { int data; struct Node *next; }; Java Code static class Node { int data; Node next; }; // This code is contributed
11 min read
Top MCQs on Recursion Algorithm with Answers
Recursion : The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function.... Read More [mtouchquiz 45]
1 min read