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

Recursive Functions

Last Updated : 27 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
49.57%
50.7K

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)



Previous Article
Next Article

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
Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here. Example:Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the le
10 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Recursive program to print formula for GCD of n integers
Given a function gcd(a, b) to find GCD (Greatest Common Divisor) of two number. It is also known that GCD of three elements can be found by gcd(a, gcd(b, c)), similarly for four element it can find the GCD by gcd(a, gcd(b, gcd(c, d))). Given a positive integer n. The task is to print the formula to find the GCD of n integer using given gcd() functi
4 min read
Add 1 to number represented as array | Recursive Approach
Given an array which represents a number, add 1 to the array. Suppose an array contain elements [1, 2, 3, 4] then the array represents decimal number 1234 and hence adding 1 to this would result 1235. So new array will be [1, 2, 3, 5]. Examples: Input : [1, 2, 3, 4] Output : [1, 2, 3, 5] Input : [1, 2, 9, 9] Output : [1, 3, 0, 0] Input: [9, 9, 9, 9
6 min read
Print 1 to 100 without loop using Goto and Recursive-main
Our task is to print all numbers from 1 to 100 without using a loop. There are many ways to print numbers from 1 to 100 without using a loop. Two of them are the goto statement and the recursive main. Print numbers from 1 to 100 Using Goto statement Follow the steps mentioned below to implement the goto statement: declare variable i of value 0decla
5 min read
Recursive sum of digit in n^x, where n and x are very large
Given very large numbers n and x, we need to find the sum of digits of n^x such that : If n^x &lt; 10 digSum(n^x) = n^x Else digSum(n^x) = Sum(digSum(n^x)) Examples: Input : 5 4 Output : 4 We know 54 = 625 Sum of digits in 625 = 6 + 2 + 5 = 13 Sum of digits in 13 = 1 + 3 = 4 Input : 546878 56422 Output : 7 Prerequisite : Recursive sum of digits. Th
6 min read
Count consonants in a string (Iterative and recursive methods)
Given a string, count total number of consonants in it. A consonant is an English alphabet character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, and g. Examples : Input : abc de Output : 3 There are three consonants b, c and d. Input : geeksforgeeks portal Output : 12 1. Iterative Method C/C++ Code // Iterative CPP p
7 min read
First uppercase letter in a string (Iterative and Recursive)
Given a string find its first uppercase letterExamples : Input : geeksforgeeKs Output : K Input : geekS Output : S Method 1: linear search Using linear search, find the first character which is capital C/C++ Code // C++ program to find the first // uppercase letter using linear search #include &lt;bits/stdc++.h&gt; using namespace std; // Function
6 min read
Simple Recursive solution to check whether BST contains dead end
Given a Binary Search Tree that contains positive integer values greater than 0. The task is to check whether the BST contains a dead end or not. Here Dead End means, we are not able to insert any integer element after that node. Examples: Input : 8 / \ 5 9 / \ 2 7 / 1 Output : Yes Explanation : Node "1" is the dead End because after that we cant i
10 min read
Recursive approach for alternating split of Linked List
Given a linked list, split the linked list into two with alternate nodes. Examples: Input : 1 2 3 4 5 6 7 Output : 1 3 5 7 2 4 6 Input : 1 4 5 6 Output : 1 5 4 6 We have discussed Iterative splitting of linked list. The idea is to begin from two nodes first and second. Let us call these nodes as 'a' and 'b'. We recurs Implementation: C/C++ Code //
7 min read
Recursive program for prime number
Given a number n, check whether it's prime number or not using recursion.Examples: Input : n = 11 Output : Yes Input : n = 15 Output : No The idea is based on school method to check for prime numbers. C/C++ Code // CPP Program to find whether a Number // is Prime or Not using Recursion #include &lt;bits/stdc++.h&gt; using namespace std; // Returns
4 min read
Recursive sum of digits of a number formed by repeated appends
Given two positive number N and X. The task is to find the sum of digits of a number formed by N repeating X number of times until sum become single digit. Examples : Input : N = 24, X = 3 Output : 9 Number formed after repeating 24 three time = 242424 Sum = 2 + 4 + 2 + 4 + 2 + 4 = 18 Sum is not the single digit, so finding the sum of digits of 18,
5 min read
Function to copy string (Iterative and Recursive)
Given two strings, copy one string to another using recursion. We basically need to write our own recursive version of strcpy in C/C++ Examples: Input : s1 = "hello" s2 = "geeksforgeeks" Output : s2 = "hello" Input : s1 = "geeksforgeeks" s2 = "" Output : s2 = "geeksforgeeks" Iterative: Copy every character from s1 to s2 starting from index = 0 and
6 min read
Bitwise recursive addition of two integers
When adding two binary numbers by hand we keep the carry bits in mind and add it at the same time. But to do same thing in program we need a lot of checks. Recursive solution can be imagined as addition of carry and a^b (two inputs) until carry becomes 0. Examples : Input : int x = 45, y = 45 Output : 90 Input : int x = 4, y = 78 Output : 82 Sum of
4 min read
Level order traversal with direction change after every two levels | Recursive Approach
Given a binary tree, print the level order traversal in such a way that first two levels are printed from left to right, next two levels are printed from right to left, then next two from left to right and so on. So, the problem is to reverse the direction of level order traversal of the binary tree after every two levels. Examples: Input: 1 / \ 2
10 min read
Modular exponentiation (Recursive)
Given three numbers a, b and c, we need to find (ab) % cNow why do “% c” after exponentiation, because ab will be really large even for relatively small values of a, b and that is a problem because the data type of the language that we try to code the problem, will most probably not let us store such a large number.Examples: Input : a = 2312 b = 34
6 min read
Recursive Approach to find nth node from the end in the linked list
Find the nth node from the end in the given linked list using a recursive approach. Examples: Input : list: 4-&gt;2-&gt;1-&gt;5-&gt;3 n = 2 Output : 5 Algorithm: findNthFromLast(head, n, count, nth_last) if head == NULL then return findNthFromLast(head-&gt;next, n, count, nth_last) count = count + 1 if count == n then nth_last = head findNthFromLas
8 min read
Count all sub-sequences having product &lt;= K - Recursive approach
Given an integer K and a non-negative array arr[], the task is to find the number of sub-sequences having the product ? K. This problem already has a dynamic programming solution. This solution aims to provide an optimized recursive strategy to the problem. Examples: Input: arr[] = { 1, 2, 3, 4 }, K = 10 Output: 11 The sub-sequences are {1}, {2}, {
13 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 of
6 min read
Print the last k nodes of the linked list in reverse order | Recursive approach
Given a linked list containing N nodes and a positive integer k should be less than or equal to N. The task is to print the last k nodes of the list in reverse order. Examples: Input: list: 1-&gt;2-&gt;3-&gt;4-&gt;5, k = 2 Output: 5 4 Input: list: 3-&gt;10-&gt;6-&gt;9-&gt;12-&gt;2-&gt;8, k = 4 Output: 8 2 12 9 Source: Amazon Interview Experience SD
7 min read
Recursive Program to Print extreme nodes of each level of Binary Tree in alternate order
Given a binary tree, the task is to print nodes of extreme corners of each level but in alternate order.Examples: Input : 1 / \ 2 3 / / \ 4 5 6 / / \ 7 8 9 Output : 1 2 6 7 Print the rightmost node at 1st level: 1 Print the leftmost node at 2nd level: 2 Print the rightmost node at 3rd level: 6 Print the leftmost node at 4th level: 7 Other possible
14 min read
Recursive Program to print multiplication table of a number
Given a number N, the task is to print its multiplication table using recursion. Examples Input: N = 5 Output: 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50 Input: N = 8 Output: 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 8 * 10 = 8
5 min read
Floor square root without using sqrt() function : Recursive
Given a number N, the task is to find the floor square root of the number N without using the built-in square root function. Floor square root of a number is the greatest whole number which is less than or equal to its square root. Examples: Input: N = 25 Output: 5 Explanation: Square root of 25 = 5. Therefore 5 is the greatest whole number less th
7 min read
Recursive program to find the Sum of the series 1 - 1/2 + 1/3 - 1/4 ... 1/N
Given a positive integer N, the task is to find the sum of the series 1 - (1/2) + (1/3) - (1/4) +.... (1/N) using recursion. Examples: Input: N = 3 Output: 0.8333333333333333 Explanation: 1 - (1/2) + (1/3) = 0.8333333333333333 Input: N = 4 Output: 0.5833333333333333 Explanation: 1- (1/2) + (1/3) - (1/4) = 0.5833333333333333 Approach: The idea is to
4 min read
What is the Recursive stack size ?
Recursion: The function calling itself is called recursion. Stack: A stack is a data structure in which elements are inserted and deleted only at one end called the top of the stack. It follows the LIFO (Last In First Out) mechanism. Recursive Stack Size: When a recursive function is invoked, its parameters are stored in a data structure called act
3 min read
Recursive Program to find Factorial of a large number
Given a large number N, the task is to find the factorial of N using recursion. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. Examples: Input : N = 100Output : 933262154439441526816992388562667004-907159682643816214685929638952175999-9322
6 min read
Why Recursive Function returns "Undefined"?
What is Recursion? In simple words, recursion is when a function is calling itself directly or indirectly. It is used to break down the problem into subproblems which makes us easy to solve. It also reduces the length of the code. It has certain advantages over just iterating through that is discussed here. The function of recursion looks simply li
4 min read
Count Subtrees that sum up to a given value X only using single Recursive Function
Given a binary tree containing n nodes. The problem is to count subtrees having the total node's data sum equal to a given value using only single recursive functions. Examples: Input: X = 7, 5 / \ -10 3 / \ / \ 9 8 -4 7 Output: 2Explanation: There are 2 subtrees with sum 7.1st one is leaf node:72nd one is: -10 / \ 9 8 Recommended PracticeCount Num
15+ min read
Article Tags :
Practice Tags :