Questions tagged [recursion]

Recursion is a kind of function call in which a function calls itself. Such functions are also called recursive functions. Structural recursion is a method of problem solving where the solution to a problem depends on solutions to smaller instances of the same problem.

The term, "recursion," describes a code structure in which a function potentially calls itself. Such functions are also called recursive functions.

Structural recursion is a method of problem solving where the solution to a problem depends on solutions to smaller or simpler instances of the same problem.

In computer science, a recursive function calls itself directly or indirectly, for example when several mutually recursive functions are working together. A recursion cannot be endless; each recursion level requires memory. This is the reason why recursive functions need conditions to not call themselves; hence, a recursive function potentially calls itself but not unconditionally.

Some functional programming languages do not define any looping constructs, but rely solely on recursion to repeatedly call code. Likewise, in languages that do provide loops, it is possible for any recursive function to be written using loops without requiring recursion.

This defines two basic approach to repeatedly call some piece of code.

  • Iterative approach (Using loop constructs)
  • Recursive approach (Using recursion)

In addition to program code, recursion can also occur in data structures, where a nested object or array may contain a reference to an element further up the data tree.

Examples in several languages

C

void recursiveFunction(int num) {
   if (num < 4)
      recursiveFunction(num + 1);
   printf("%d\n", num);
}

C++

void recursiveFunction(int num) {
   if (num < 4)
      recursiveFunction(num + 1);
   std::cout << num;
}

Java

public static int factorial(int N) { 
   if (N == 1) return 1; 
   return N * factorial(N-1); 
}

OCaml

let rec factorial n =
    if n <= 1 then 1 else n * factorial (n - 1)

Haskell

factorial n = if n == 0 then 1 else n * factorial (n - 1)

Perl

sub factorial {
    my $n = shift;
    return 1 if $n == 1;
    return $n * factorial($n - 1);
}

Haxe

function factorial(num:Int) { 
   if (num == 1) return 1; 
   return num * factorial(num - 1); 
}

Python (2 or 3)

def factorial(n):
    return 1 if n <= 1 else n * factorial(n - 1)

Tag usage

should be used for programming-related problems when using recursion in any programming language. On Stack Overflow, please avoid theoretical questions such as "how does recursion work?"

References

Further information

46639 questions
78
votes
7 answers

Why is Python recursion so expensive and what can we do about it?

Suppose we want to compute some Fibonacci numbers, modulo 997. For n=500 in C++ we can run #include #include std::array fib(unsigned n) { if (!n) return {1, 1}; auto x = fib(n - 1); return {(x[0] +…
jtallk
  • 961
  • 1
  • 4
  • 6
77
votes
4 answers

How to search a folder and all of its subfolders for files of a certain type

I am trying to search for all files of a given type in a given folder and copy them to a new folder. I need to specify a root folder and search through that folder and all of its subfolders for any files that match the given type. How do I search…
ab217
  • 16,900
  • 25
  • 74
  • 92
77
votes
26 answers

Finding height in Binary Search Tree

I was wondering if anybody could help me rework this method to find the height of a binary search tree. So far, my code looks like this. However, the answer I'm getting is larger than the actual height by 1. But when I remove the +1 from my return…
mike
  • 3,339
  • 6
  • 30
  • 34
77
votes
8 answers

When to use recursive mutex?

I understand recursive mutex allows mutex to be locked more than once without getting to a deadlock and should be unlocked the same number of times. But in what specific situations do you need to use a recursive mutex? I'm looking for…
jasonline
  • 8,646
  • 19
  • 59
  • 80
73
votes
17 answers

What in layman's terms is a Recursive Function using PHP

Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci totally lost me! Thank you in advance ;-) Also how often do you use them in…
Imran
  • 11,350
  • 20
  • 68
  • 78
71
votes
25 answers

Implement recursive lambda function using Java 8

Java 8 introduced lambda functions and I want to implement something like factorial: IntToDoubleFunction fact = x -> x == 0 ? 1 : x * fact.applyAsDouble(x-1); Compilation returns error: variable fact might not have been initialized How can I…
user2678835
  • 797
  • 1
  • 5
  • 5
70
votes
15 answers

Recursion vs loops

I'm facing a problem where both recursion and using a loop seem like natural solutions. Is there a convention or "preferred method" for cases like this? (Obviously it is not quite as simple as below) Recursion Item Search(string desired, Scope…
zildjohn01
  • 11,339
  • 6
  • 52
  • 58
70
votes
6 answers

Does C++ limit recursion depth?

In Python there is a maximum recursion depth. Seems it is because Python is interpreted rather than compiled. Does C++ have the same concept? Or it is connected only with RAM limit?
Narek
  • 38,779
  • 79
  • 233
  • 389
70
votes
6 answers

Hitting Maximum Recursion Depth Using Pickle / cPickle

The background: I'm building a trie to represent a dictionary, using a minimal construction algorithm. The input list is 4.3M utf-8 strings, sorted lexicographically. The resulting graph is acyclic and has a maximum depth of 638 nodes. The first…
danben
  • 80,905
  • 18
  • 123
  • 145
70
votes
5 answers

How can I make recursive templates in AngularJS when using nested objects?

I'm trying to build a form dynamically from a JSON object, which contains nested groups of form elements: $scope.formData = [ {label:'First Name', type:'text', required:'true'}, {label:'Last Name', type:'text', required:'true'}, …
Hairgami_Master
  • 5,429
  • 10
  • 45
  • 66
70
votes
5 answers

What's the difference between recursion, memoization & dynamic programming?

Related question: Dynamic programming and memoization: top-down vs bottom-up approaches I have gone through a lot of articles on this but can't seem to make sense of it. At times recursion and dynamic programming looks the same and at others…
Sakibul Alam
  • 1,731
  • 2
  • 21
  • 40
68
votes
6 answers

How to recursively list directories in C on Linux?

I need to recursively list all directories and files in C programming. I have looked into FTW but that is not included with the 2 operating systems that I am using (Fedora and Minix). I am starting to get a big headache from all the different things…
Charlie
  • 1,308
  • 5
  • 14
  • 24
68
votes
6 answers

Tail recursion in C++

Can someone show me a simple tail-recursive function in C++? Why is tail recursion better, if it even is? What other kinds of recursion are there besides tail recursion?
neuromancer
  • 53,769
  • 78
  • 166
  • 223
68
votes
29 answers

Tower of Hanoi: Recursive Algorithm

Although I have no problem whatsoever understanding recursion, I can't seem to wrap my head around the recursive solution to the Tower of Hanoi problem. Here is the code from Wikipedia: procedure Hanoi(n: integer; source, dest, by: char); Begin …
titaniumdecoy
  • 18,900
  • 17
  • 96
  • 133
67
votes
4 answers

Defining and calling function in one step

Is there a way in Javascript to define a function and immediately call it, in a way that allows it to be reused? I know you can do one-off anonymous functions: (function(i) { var product = i * i; console.log(product); // Can't recurse…
quis
  • 1,120
  • 2
  • 8
  • 15