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
2033
votes
29 answers

What is tail recursion?

Whilst starting to learn lisp, I've come across the term tail-recursive. What does it mean exactly?
1076
votes
10 answers

What is tail call optimization?

Very simply, what is tail-call optimization? More specifically, what are some small code snippets where it could be applied, and where not, with an explanation of why?
685
votes
19 answers

What is the maximum recursion depth, and how to increase it?

I have this tail recursive function here: def recursive_function(n, sum): if n < 1: return sum else: return recursive_function(n-1, sum+n) c = 998 print(recursive_function(c, 0)) It works up to n=997, then it just breaks…
quantumSoup
  • 27,197
  • 9
  • 43
  • 57
573
votes
10 answers

Recursively look for files with a specific extension

I'm trying to find all files with a specific extension in a directory and its subdirectories with my Bash (Ubuntu 10.04 LTS (Lucid Lynx) release). This is what's written in a script…
flip
  • 5,739
  • 3
  • 15
  • 3
571
votes
15 answers

What is the most efficient/elegant way to parse a flat table into a tree?

Assume you have a flat table that stores an ordered tree hierarchy: Id Name ParentId Order 1 'Node 1' 0 10 2 'Node 1.1' 1 10 3 'Node 2' 0 20 4 'Node 1.1.1' 2 10 5 …
Tomalak
  • 332,285
  • 67
  • 532
  • 628
553
votes
22 answers

How to recursively find and list the latest modified files in a directory with subdirectories and times

Operating system: Linux Filesystem type: ext3 Preferred solution: Bash (script/one-liner), Ruby, or Python I have several directories with several subdirectories and files in them. I need to make a list of all these directories that is…
fredrik
  • 5,655
  • 3
  • 15
  • 7
444
votes
21 answers

Way to go from recursion to iteration

I've used recursion quite a lot on my many years of programming to solve simple problems, but I'm fully aware that sometimes you need iteration due to memory/speed problems. So, sometime in the very far past I went to try and find if there existed…
432
votes
12 answers

How to search a string in multiple files and return the names of files in Powershell?

I have started learning powershell a couple of days ago, and I couldn't find anything on google that does what I need so please bear with my question. I have been asked to replace some text strings into multiple files. I do not necessarily know the…
Bluz
  • 5,980
  • 11
  • 32
  • 40
415
votes
7 answers

Determining complexity for recursive functions (Big O notation)

I have a Computer Science Midterm tomorrow and I need help determining the complexity of these recursive functions. I know how to solve simple cases, but I am still trying to learn how to solve these harder cases. These were just a few of the…
Michael_19
  • 4,799
  • 6
  • 24
  • 20
374
votes
13 answers

Is recursion ever faster than looping?

I know that recursion is sometimes a lot cleaner than looping, and I'm not asking anything about when I should use recursion over iteration, I know there are lots of questions about that already. What I'm asking is, is recursion ever faster than a…
Carson Myers
  • 37,678
  • 39
  • 126
  • 176
337
votes
30 answers

Recursively list files in Java

How do I recursively list all files under a directory in Java? Does the framework provide any utility? I saw a lot of hacky implementations. But none from the framework or nio
Quintin Par
  • 15,862
  • 27
  • 93
  • 146
334
votes
6 answers

Try-finally block prevents StackOverflowError

Take a look at the following two methods: public static void foo() { try { foo(); } finally { foo(); } } public static void bar() { bar(); } Running bar() clearly results in a StackOverflowError, but running foo()…
arshajii
  • 127,459
  • 24
  • 238
  • 287
288
votes
8 answers

Does Python optimize tail recursion?

I have the following piece of code which fails with the following error: RuntimeError: maximum recursion depth exceeded I attempted to rewrite this to allow for tail recursion optimization (TCO). I believe that this code should have been…
Jordan Mack
  • 8,223
  • 7
  • 30
  • 29
271
votes
31 answers

Recursion or Iteration?

Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palindrome. I have seen many programmers using recursion as a means to show off…
Omnipotent
  • 27,619
  • 12
  • 30
  • 34
270
votes
10 answers

Is log(n!) = Θ(n·log(n))?

I am to show that log(n!) = Θ(n·log(n)). A hint was given that I should show the upper bound with nn and show the lower bound with (n/2)(n/2). This does not seem all that intuitive to me. Why would that be the case? I can definitely see how to…
Mark
  • 6,123
  • 13
  • 41
  • 52
1
2 3
99 100