The Wayback Machine - https://web.archive.org/web/20250305174919/https://www.geeksforgeeks.org/recursive-functions/
Open In App

Recursive Functions

Last Updated : 27 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 down into simpler, similar subproblems.

Need of Recursive Function:

A recursive function is a function that solves a problem by solving smaller instances of the same problem. This technique is often used in programming to solve problems that can be broken down into simpler, similar subproblems.

1. Solving complex tasks:

Recursive functions break complex problems into smaller instances of the same problem, resulting in compact and readable code.

2. Divide and Conquer:

Recursive functions are suitable for divide-and-conquer algorithms such as merge sort and quicksort, breaking problems into smaller subproblems, solving them recursively, and merging the solutions with the original problem.

3. Backtracking:

Recursive backtracking is ideal for exploring and solving problems like N-Queens and Sudoku.

4. Dynamic programming:

Recursive functions efficiently solve dynamic programming problems by solving subproblems and combining their solutions into a complete solution.

5. Tree and graph structures:

Recursive functions are great for working with tree and graph structures, simplifying traversal and pattern recognition tasks.

How to write a Recursive Function:

Components of a recursive function:

Base case: Every recursive function must have a base case. The base case is the simplest scenario that does not require further recursion. This is a termination condition that prevents the function from calling itself indefinitely. Without a proper base case, a recursive function can lead to infinite recursion.

Recursive case: In the recursive case, the function calls itself with the modified arguments. This is the essence of recursion – solving a larger problem by breaking it down into smaller instances of the same problem. The recursive case should move closer to the base case with each iteration.

Let’s consider the example of factorial of number:

In this example, the base case is when n is 0, and the function returns 1. The recursive case multiplies n with the result of the function called with parameter n – 1. The process continues until the base case is reached.

It’s essential to ensure that the recursive function has a correct base case and that the recursive calls lead to the base case, otherwise, the procedure might run indefinitely, leading to a stack overflow (exceeding the available memory allocated for function calls).

Below is the implementation of factorial of a number:

C++
#include <iostream>
using namespace std;

// Recursive Function to calculate Factorial of a number
int factorial(int n)
{
    // Base case
    if (n == 0) {
        return 1;
    }

    // Recursive case
    return n * factorial(n - 1);
}

// Driver Code

int main()
{
    int n = 4;

    cout << "Factorial of " << n
         << " is:" << factorial(n);
    return 0;
}
Java
import java.util.Scanner;

public class Factorial {
    // Recursive Function to calculate the factorial of a number
    static int factorial(int n) {
        // Base case: If n is 0, the factorial is 1.
        if (n == 0) {
            return 1;
        }

        // Recursive case: Calculate the factorial by multiplying n with the factorial of (n - 1).
        return n * factorial(n - 1);
    }

    public static void main(String[] args) {
        int n = 4;

        // Calculate and print the factorial of n.
        int result = factorial(n);
        System.out.println("Factorial of " + n + " is: " + result);
    }
}
Python
# Recursive Function to calculate Factorial of a number
def factorial(n):
    # Base case
    if n == 0:
        return 1

    # Recursive case
    return n * factorial(n - 1)

# Driver Code
if __name__ == "__main__":
    n = 4

    print("Factorial of", n, "is:", factorial(n))
C#
using System;

class Program
{
    // Recursive Function to calculate Factorial of a number
    static int Factorial(int n)
    {
        // Base case
        if (n == 0)
        {
            return 1;
        }

        // Recursive case
        return n * Factorial(n - 1);
    }

    // Driver Code
    static void Main()
    {
        int n = 4;

        Console.WriteLine("Factorial of " + n + " is: " + Factorial(n));
    }
}
JavaScript
// Function to calculate the factorial of a number using recursion
function factorial(n) {
    // Base case: If n is 0, the factorial is 1.
    if (n === 0) {
        return 1;
    }

    // Recursive case: Calculate the factorial by multiplying n with the factorial of (n - 1).
    return n * factorial(n - 1);
}

// Main function
function main() {
    // Given number
    let n = 4;

    // Calculate the factorial of n.
    let result = factorial(n);

    // Print the result
    console.log("Factorial of " + n + " is: " + result);
}

// Call the main function
main();

Output
Factorial of 4 is:24

Time Complexity: O(n)
Auxiliary Space: O(n)


Master Data Structures and Algorithms at your own pace with our DSA Self-Paced course. In just 90 days, you’ll cover core concepts, solve real-world problems, and sharpen your problem-solving skills. Take the Three 90 Challenge: complete 90% of the course in 90 days and get a 90% refund. Stay motivated, track progress, and achieve DSA mastery. Start today!


Next Article
Article Tags :
Practice Tags :

Similar Reads

Auxiliary Space with Recursive Functions
Prerequisite: RecursionMemory used by a program is sometimes as important as running time, particularly in constrained environments such as mobile devices. For example if we need to create an array of size n, it will require O(n) space. If we need a two-dimensional array of size n x n , it will require O(n2). Stack space in recursive calls counts t
3 min read
Hash Functions and Types of Hash functions
Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. In data structures and algorithms (DSA), hash functions are primarily used in hash tables, which are essential for efficient data management. This article delves into the intricacies of hash
4 min read
Count full nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the full nodes (Nodes which have both children as not NULL) without using recursion and with recursion? Note leaves should not be touched as they have both children as NULL. Nodes 2 and 6 are full nodes has both child's. So count of full nodes in the above tree is 2 Method: Iterative The idea is to use lev
12 min read
Matrix Multiplication | Recursive
Given two matrices A and B. The task is to multiply matrix A and matrix B recursively. If matrix A and matrix B are not multiplicative compatible, then generate output "Not Possible". Examples : Input: A = 12 56 45 78 B = 2 6 5 8Output: 304 520 480 894Input: A = 1 2 3 4 5 6 7 8 9 B = 1 2 3 4 5 6 7 8 9Output: 30 36 42 66 81 96 102 126 150 It is rec
9 min read
Recursive Selection Sort
The Selection Sort algorithm sorts maintain two parts. The first part that is already sortedThe second part is yet to be sorted. The algorithm works by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the end of the sorted part. arr[] = 64 25 12 22 11 // Find the minimum element in arr
6 min read
Recursive selection sort for singly linked list | Swapping node links
Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data. Examples: Input : 10 -> 12 -> 8 -> 4 -> 6 Output : 4 -> 6 -> 8 -> 10 -> 12 In Selection Sort, we first
12 min read
Bitwise recursive addition of two integers
Given two integers x and y, the task is to perform bitwise recursive addition of two integers.Examples : Input: x = 45, y = 45Output: 90Input: x = 4, y = 78Output: 82Approach:The idea is to mimic the manual process of binary addition, where we calculate the carry and add it to the sum of x and y. Using bitwise operations, the XOR (x ^ y) gives the
5 min read
Recursive program to generate power set
Given a set represented as a string, write a recursive code to print all subsets of it. The subsets can be printed in any order. Examples: Input : set = "abc"Output : { "", "a", "b", "c", "ab", "ac", "bc", "abc"}Input : set = "abcd"Output : { "", "a" ,"ab" ,"abc" ,"abcd", "abd" ,"ac" ,"acd", "ad" ,"b", "bc" ,"bcd" ,"bd" ,"c" ,"cd" ,"d" }Using Pic
12 min read
Recursive program to check if number is palindrome or not
Given a number, the task is to write a recursive function that checks if the given number is a palindrome or not. Examples: Input: 121Output: yes Input: 532Output: no The approach for writing the function is to call the function recursively till the number is wholly traversed from the back. Use a temp variable to store the reverse of the numbe
4 min read
Recursive program to print all subsets with given sum
Given an array and a number, print all subsets with sum equal to given the sum.Examples: Input : arr[] = {2, 5, 8, 4, 6, 11}, sum = 13 Output : 5 8 2 11 2 5 6 Input : arr[] = {1, 5, 8, 4, 6, 11}, sum = 9 Output : 5 4 1 8 This problem is an extension of check if there is a subset with given sum. We recursively generate all subsets. We keep track
6 min read