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
60
votes
7 answers

Headers Including Each Other in C++

I'm a C++ newbie, but I wasn't able to find the answer to this (most likely trivial) question online. I am having some trouble compiling some code where two classes include each other. To begin, should my #include statements go inside or outside…
Scott
  • 2,551
  • 5
  • 25
  • 25
60
votes
7 answers

Recursive Promise in javascript

I'm writing a Javascript Promise that finds the final redirect URL of a link. What I'm doing is making a HEAD request in a Promise using an XMLHttpRequest. Then, on load, check the HTTP Status for something in the 300 range, or if it has a…
dx_over_dt
  • 13,240
  • 17
  • 54
  • 102
59
votes
2 answers

Jquery Ajax beforeSend and success,error & complete

I have a problem with multiple ajax functions where the beforeSend of the second ajax post is executed before the complete function of the first ajax. The loading class I am adding to the placeholder before sending is working for the first ajax…
Rehan Anis
  • 788
  • 1
  • 5
  • 7
57
votes
3 answers

Java program runs slower when code that is never executed is commented out

I observed some strange behaviour in one of my Java programs. I have tried to strip the code down as much as possible while still being able to replicate the behaviour. Code in full below. public class StrangeBehaviour { static boolean…
J3D1
  • 759
  • 6
  • 10
57
votes
5 answers

Building a promise chain recursively in javascript - memory considerations

In this answer, a promise chain is built recursively. Simplified slightly, we have : function foo() { function doo() { // always return a promise if (/* more to do */) { return doSomethingAsync().then(doo); }…
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
55
votes
7 answers

Recursively List all directories and files

I would like to receive the following output. Suppose the directory structure on the file system is like this: -dir1 -dir2 -file1 -file2 -dir3 -file3 -file4 -dir4 …
Christopher
55
votes
8 answers

Finding a key recursively in a dictionary

I'm trying to write a very simple function to recursively search through a possibly nested (in the most extreme cases ten levels deep) Python dictionary and return the first value it finds from the given key. I cannot understand why my code doesn't…
Fredrick Brennan
  • 7,079
  • 2
  • 30
  • 61
54
votes
6 answers

Windows Batch File Looping Through Directories to Process Files?

I need to write/use a batch file that processes some imagery for me. I have one folder full of nested folders, inside each of these nested folders is one more folder that contains a number of TIF images, the number of images vary in each folder. I…
Tyler
  • 1,291
  • 1
  • 13
  • 20
54
votes
4 answers

How does the C++ compiler evaluate recursive constexpr functions so quickly?

I've been learning about C++ constexpr functions, and I implemented a constexpr recursive function to find the nth fibonacci number. #include #include #include #include #include constexpr long long…
ahskdjfk
  • 919
  • 5
  • 8
54
votes
2 answers

When is tail recursion guaranteed in Rust?

C language In the C programming language, it's easy to have tail recursion: int foo(...) { return foo(...); } Just return as is the return value of the recursive call. It is especially important when this recursion may repeat a thousand or even…
uben
  • 1,221
  • 2
  • 11
  • 20
54
votes
9 answers

create array tree from array list

i have a list like this: array( array(id=>100, parentid=>0, name=>'a'), array(id=>101, parentid=>100, name=>'a'), array(id=>102, parentid=>101, name=>'a'), array(id=>103, parentid=>101, name=>'a'), ) but way bigger so i need a efficient way…
Thunderstriker
  • 1,279
  • 1
  • 11
  • 11
54
votes
6 answers

What is the easiest way to get the property value from a passed lambda expression in an extension method for HtmlHelper?

I am writing a dirty little extension method for HtmlHelper so that I can say something like HtmlHelper.WysiwygFor(lambda) and display the CKEditor. I have this working currently but it seems a bit more cumbersome than I would prefer. I am hoping…
Andrew Siemer
  • 10,166
  • 3
  • 41
  • 61
54
votes
5 answers

Are there problems that cannot be written using tail recursion?

Tail recursion is an important performance optimisation stragegy in functional languages because it allows recursive calls to consume constant stack (rather than O(n)). Are there any problems that simply cannot be written in a tail-recursive style,…
ctford
  • 7,189
  • 4
  • 34
  • 51
54
votes
5 answers

How can I upload an entire folder, that contains other folders, using sftp on linux?

I have tried put -r directory/*, which only uploaded the files and not folders. Gave me the error, cannot Couldn't canonicalise. Any help would be greatly appreciated.
Chris
  • 651
  • 2
  • 10
  • 16
53
votes
6 answers

Understanding Recursion to generate permutations

I find recursion, apart from very straight forward ones like factorial, very difficult to understand. The following snippet prints all permutations of a string. Can anyone help me understand it. What is the way to go about to understand recursion…
Nemo
  • 4,601
  • 11
  • 43
  • 46