The Wayback Machine - https://web.archive.org/web/20240717180321/https://www.geeksforgeeks.org/what-is-implicit-recursion/
Open In App

What is Implicit recursion?

Last Updated : 13 Feb, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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 condition is met.

What is Implicit Recursion?

A specific sort of recursion called implicit recursion occurs when a function calls itself without making an explicit recursive call. This can occur when a function calls another function, which then calls the original code once again and starts a recursive execution of the original function. This can sometimes be difficult to spot and can lead to unintended behavior if not handled carefully.

Example of the implicit recursion:

We will use implicit recursion to find the second-largest elements from the array:

C++14




#include <bits/stdc++.h>
 
using namespace std;
 
int findLargest(vector<int> numbers) {
  int largest = numbers[0];
  for (int number : numbers) {
    if (number > largest) {
      largest = number;
    }
  }
  return largest;
}
 
int findSecondLargest(vector<int> numbers) {
  // Remove the largest number from the list
  numbers.erase(remove(numbers.begin(), numbers.end(), findLargest(numbers)), numbers.end());
 
  // Return the largest remaining number
  return findLargest(numbers);
}
 
int main() {
  vector<int> numbers = {1, 2, 3, 4, 5};
 
  // Function call
  int secondLargest = findSecondLargest(numbers);
  cout << secondLargest << endl;
 
  return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
 
class GFG {
 
  public static int findLargest(List<Integer> numbers)
  {
    int largest = numbers.get(0);
    for (int number : numbers) {
      if (number > largest) {
        largest = number;
      }
    }
    return largest;
  }
 
  public static int
    findSecondLargest(List<Integer> numbers)
  {
    final int largest = findLargest(numbers);
    // Remove the largest number from the list
    numbers = numbers.stream()
      .filter(n -> n != largest)
      .collect(Collectors.toList());
 
    // Return the largest remaining number
    return findLargest(numbers);
  }
 
  public static void main(String[] args)
  {
    List<Integer> numbers
      = Arrays.asList(1, 2, 3, 4, 5);
 
    // Function call
    int secondLargest = findSecondLargest(numbers);
    System.out.println(secondLargest);
  }
}
 
// This code is contributed by lokeshmvs21.


Python3




def find_largest(numbers):
    largest = numbers[0]
    for number in numbers:
        if number > largest:
            largest = number
    return largest
 
 
def find_second_largest(numbers):
 
    # Remove the largest number from the list
    numbers.remove(find_largest(numbers))
 
    # Return the largest remaining number
    return find_largest(numbers)
 
# Driver code
 
 
numbers = [1, 2, 3, 4, 5]
 
# Function call
second_largest = find_second_largest(numbers)
print(second_largest)


C#




using System;
using System.Collections.Generic;
 
class GFG {
  public static int findLargest(List<int> numbers)
  {
    int largest = numbers[0];
    for (int i = 1; i < numbers.Count; i++) {
      if (numbers[i] > largest) {
        largest = numbers[i];
      }
    }
    return largest;
  }
 
  public static int findSecondLargest(List<int> numbers)
  {
    int largest = findLargest(numbers);
     
    // Remove the largest number from the list
    numbers.Remove(largest);
 
    // Return the largest remaining number
    return findLargest(numbers);
  }
 
  public static void Main(string[] args)
  {
    List<int> numbers = new List<int>{ 1, 2, 3, 4, 5 };
 
    // Function call
    int secondLargest = findSecondLargest(numbers);
    Console.WriteLine(secondLargest);
  }
}
 
// This code is contributed by aadityamaharshi21.


Javascript




function findLargest(numbers) {
  let largest = numbers[0];
  for (let number of numbers) {
    if (number > largest) {
      largest = number;
    }
  }
  return largest;
}
 
function findSecondLargest(numbers)
{
 
  // Remove the largest number from the list
  numbers = numbers.filter(n => n !== findLargest(numbers));
 
  // Return the largest remaining number
  return findLargest(numbers);
}
 
let numbers = [1, 2, 3, 4, 5];
 
// Function call
let secondLargest = findSecondLargest(numbers);
console.log(secondLargest);
 
// This code is contributed by aadityamaharshi21.


Output

4

Time Complexity: O(N)
Auxiliary Space: O(1)

In this case, the find_second_largest( It’s crucial to remember that explicit recursion could also be used to accomplish this example, which would make the code simpler to read and comprehend. ) method calls the find_largest() function via implicit recursion to locate the second-largest number in a provided list of numbers. Implicit recursion can be used in this way to get the second-largest integer without having to write any more code, which is a handy use.

Problem with implicit recursion:

In the case of the implicit recursion, the issue of an infinite function call may occur. Here is a case where implicit recursion can cause the problem:

C++




#include <iostream>
 
using namespace std;
 
void func2();
void func1();
 
void func1() {
  cout << "This is the first function" << endl;
  func2();
}
 
void func2() {
  cout << "This is the second function" << endl;
  func1();
}
 
int main() {
  func1();
 
  return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
   
      static void func1(){
        System.out.println("This is the first function");
          func2();
    }
   
      static void func2(){
        System.out.println("This is the second function");
          func1();
    }
   
    public static void main (String[] args) {
        func1();
    }
}
 
// This code is contributed by lokeshmvs21.


Python3




def func1():
    print("This is the first function")
    func2()
 
def func2():
    print("This is the second function")
    func1()
 
func1()


C#




using System;
 
public class GFG {
 
    static void func1()
    {
        Console.WriteLine("This is the first function");
        func2();
    }
 
    static void func2()
    {
        Console.WriteLine("This is the second function");
        func1();
    }
 
    static public void Main()
    {
 
        // Code
        func1();
    }
}
 
// This code is contributed by lokesh.


Javascript




// Define func2
function func2() {
  console.log("This is the second function");
  // Call func1 inside func2
  func1();
}
 
// Define func1
function func1() {
  console.log("This is the first function");
  // Call func2 inside func1
  func2();
}
 
// Call func1 from main
func1();


Output: 

This is the first function
This is the second function
This is the first function
This is the second function
...
...

In this example, the func1() function calls func2(), which then calls func1() once again.

Steps to avoid this issue:

  • When utilizing implicit recursion, caution must be taken since if the recursive calls are not handled correctly, it is simple to produce an endless loop. 
  • Additionally, it’s typically recommended to avoid implicit recursion if feasible because it might make your code more challenging to read and maintain. 
  • Instead, explicit recursion, which is simpler to read and understand, is typically preferred.

Related Articles:



Previous Article
Next Article

Similar Reads

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 recursive function in which the recursive call is the f
4 min read
Derivatives of Implicit Functions - Continuity and Differentiability | Class 12 Maths
Implicit functions are functions where a specific variable cannot be expressed as a function of the other variable. A function that depends on more than one variable. Implicit Differentiation helps us compute the derivative of y with respect to x without solving the given equation for y, this can be achieved by using the chain rule which helps us e
4 min read
The Great Tree-List Recursion Problem.
Asked by Varun Bhatia. Question: Write a recursive function treeToList(Node root) that takes an ordered binary tree and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The”previous” pointers should be stored in the “small” field and the “next” pointers should be stored in the “large” field. The list sho
1 min read
Inorder Tree Traversal without recursion and without stack!
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. 1. Initialize current as root 2. While current
9 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 by shubhamsingh10 C/C++ Code class Node: def __ini
11 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 == 0) return y; else return fun1(x - 1, x + y); } C/C
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 0; else return 1 + fun1(n / 2); } C/C++ Code # As
3 min read
Practice Questions for Recursion | Set 4
Question 1 Predict the output of the following program. C/C++ Code #include &lt;iostream&gt; using namespace std; void fun(int x) { if(x &gt; 0) { fun(--x); cout &lt;&lt; x &lt;&lt;&quot; &quot;; fun(--x); } } int main() { int a = 4; fun(a); return 0; } // This code is contributed by SHUBHAMSINGH10 C/C++ Code #include&lt;stdio.h&gt; void fun(int x)
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 &lt;iostream&gt; 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 &lt;&lt; fun(4, 3) ; return 0; } // This code is contribut
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. C/C++ Code void abc(char *s) { if(s[0] == '&#92;&#48;') return; abc(s + 1); abc(s + 1); cout &lt;&lt; s[0]; } // This code
4 min read
three90RightbarBannerImg