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
157
votes
9 answers

self referential struct definition?

I haven't been writing C for very long, and so I'm not sure about how I should go about doing these sorts of recursive things... I would like each cell to contain another cell, but I get an error along the lines of "field 'child' has incomplete…
Ziggy
  • 21,845
  • 28
  • 75
  • 104
147
votes
23 answers

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

I have made a function that finds all the URLs within an html file and repeats the same process for each html content linked to the discovered URLs. The function is recursive and can go on endlessly. However, I have put a limit on the recursion by…
Rafay
  • 6,108
  • 11
  • 51
  • 71
141
votes
21 answers

javascript: recursive anonymous function?

Let's say I have a basic recursive function: function recur(data) { data = data+1; var nothing = function() { recur(data); } nothing(); } How could I do this if I have an anonymous function such as... (function(data){ …
Incognito
  • 20,537
  • 15
  • 80
  • 120
130
votes
10 answers

recursion versus iteration

Is it correct to say that everywhere recursion is used a for loop could be used? And if recursion is usually slower what is the technical reason for ever using it over for loop iteration? And if it is always possible to convert an recursion into a…
Breako Breako
  • 6,353
  • 14
  • 40
  • 59
129
votes
6 answers

GDB corrupted stack frame - How to debug?

I have the following stack trace. Is it possible to make out anything useful from this for debugging? Program received signal SIGSEGV, Segmentation fault. 0x00000002 in ?? () (gdb) bt #0 0x00000002 in ?? () #1 0x00000001 in ?? () #2 0xbffff284 in…
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98
126
votes
8 answers

How exactly does tail recursion work?

I almost understand how tail recursion works and the difference between it and a normal recursion. I only don't understand why it doesn't require stack to remember its return address. // tail recursion int fac_times (int n, int acc) { if (n ==…
Alan Coromano
  • 24,958
  • 53
  • 135
  • 205
125
votes
12 answers

How to [recursively] Zip a directory in PHP?

Directory is something like: home/ file1.html file2.html Another_Dir/ file8.html Sub_Dir/ file19.html I am using the same PHP Zip class used in PHPMyAdmin…
ed209
  • 11,075
  • 19
  • 66
  • 82
121
votes
40 answers

What is recursion and when should I use it?

One of the topics that seems to come up regularly on mailing lists and online discussions is the merits (or lack thereof) of doing a Computer Science Degree. An argument that seems to come up time and again for the negative party is that they have…
Mike Minutillo
  • 54,079
  • 14
  • 47
  • 41
120
votes
13 answers

Find all occurrences of a key in nested dictionaries and lists

I have a dictionary like this: { "id": "abcde", "key1": "blah", "key2": "blah blah", "nestedlist": [ { "id": "qwerty", "nestednestedlist": [ { "id": "xyz", …
Matt Swain
  • 3,827
  • 4
  • 25
  • 36
119
votes
18 answers

Understanding how recursive functions work

As the title explains I have a very fundamental programming question which I have just not been able to grok yet. Filtering out all of the (extremely clever) "In order to understand recursion, you must first understand recursion." replies from…
Jason Elwood
  • 1,315
  • 2
  • 10
  • 12
119
votes
20 answers

List all the files and folders in a Directory with PHP recursive function

I'm trying to go through all of the files in a directory, and if there is a directory, go through all of its files and so on until there are no more directories to go to. Each and every processed item will be added to a results array in the function…
user3412869
  • 1,395
  • 2
  • 10
  • 11
119
votes
7 answers

Simplest way to do a recursive self-join?

What is the simplest way of doing a recursive self-join in SQL Server? PersonID | Initials | ParentID 1 CJ NULL 2 EB 1 3 MB 1 4 SW 2 5 YT NULL 6 IS …
Chris
  • 3,081
  • 3
  • 32
  • 37
117
votes
37 answers

How to find all combinations of coins when given some dollar value

I found a piece of code that I was writing for interview prep few months ago. According to the comment I had, it was trying to solve this problem: Given some dollar value in cents (e.g. 200 = 2 dollars, 1000 = 10 dollars), find all the combinations…
codingbear
  • 14,773
  • 20
  • 48
  • 64
116
votes
6 answers

Why are functions in OCaml/F# not recursive by default?

Why is it that functions in F# and OCaml (and possibly other languages) are not by default recursive? In other words, why did the language designers decide it was a good idea to explicitly make you type rec in a declaration like: let rec foo ... =…
nsantorello
  • 1,709
  • 3
  • 16
  • 18
116
votes
9 answers

Is recursion a feature in and of itself?

...or is it just a practice? I'm asking this because of an argument with my professor: I lost credit for calling a function recursively on the basis that we did not cover recursion in class, and my argument is that we learned it implicitly by…
user1948076