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

Method to get all files within folder and subfolders that will return a list

I have a method that will iterate through a folder and all of its subfolders and get a list of the file paths. However, I could only figure out how to create it and add the files to a public List, but not how to return the list. Here's the…
Wilson
  • 8,570
  • 20
  • 66
  • 101
66
votes
6 answers

Python: maximum recursion depth exceeded while calling a Python object

I've built a crawler that had to run on about 5M pages (by increasing the url ID) and then parses the pages which contain the info' I need. after using an algorithm which run on the urls (200K) and saved the good and bad results I found that the I'm…
YSY
  • 1,226
  • 3
  • 13
  • 19
66
votes
4 answers

Recursive lambda expression to traverse a tree in C#

Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.
Joel Cunningham
  • 13,620
  • 8
  • 43
  • 49
66
votes
12 answers

getattr and setattr on nested subobjects / chained properties?

I have an object (Person) that has multiple subobjects (Pet, Residence) as properties. I want to be able to dynamically set the properties of these subobjects like so: class Person(object): def __init__(self): self.pet = Pet() …
TPB
  • 737
  • 1
  • 6
  • 8
64
votes
9 answers

Keep track of how many times a recursive function was called

function singleDigit(num) { let counter = 0 let number = [...num + ''].map(Number).reduce((x, y) => {return x * y}) if(number <= 9){ console.log(number) }else{ console.log(number) …
Edward S
  • 820
  • 1
  • 7
  • 12
63
votes
5 answers

How do I replace while loops with a functional programming alternative without tail call optimization?

I am experimenting with a more functional style in my JavaScript; therefore, I have replaced for loops with utility functions such as map and reduce. However, I have not found a functional replacement for while loops since tail call optimization is…
62
votes
9 answers

git add -A is not adding all modified files in directories

I want to add all files no matter what: whether it is deleted, created, modified, untracked, etc? I just don't want to git add ALL my files EVERY TIME. I tried git add -A but it is NOT adding modified files inside folders. Here is my initial git…
Rakib
  • 12,376
  • 16
  • 77
  • 113
62
votes
4 answers

C# Recursion Depth - How Deep can you go

Is there any control how much you can Recursively call something? From a basic test program I get a recursion depth of just over 18k which depends on the stacksize.... is there a way to set up a chunk of memory (perhaps a thread) with a massive…
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
62
votes
1 answer

List files recursively in Kotlin

to list files in a directory with kotlin, i used list() and listFiles() functions: File("/tmp").list().forEach { println(it) } File("/tmp").listFiles().forEach { println(it) } but, how can i list files recursively?
matteo
  • 2,121
  • 4
  • 20
  • 33
62
votes
18 answers

Why should recursion be preferred over iteration?

Iteration is more performant than recursion, right? Then why do some people opine that recursion is better (more elegant, in their words) than iteration? I really don't see why some languages like Haskell do not allow iteration and encourage…
Debashish12
  • 1
  • 1
  • 3
  • 6
62
votes
6 answers

Can an anonymous method in C# call itself?

I have the following code: class myClass { private delegate string myDelegate(Object bj); protected void method() { myDelegate build = delegate(Object bj) { var letters= string.Empty; if…
Matt
  • 25,943
  • 66
  • 198
  • 303
61
votes
2 answers

ES6 Tail Recursion Optimisation Stack Overflow

Having read Dr Rauschmayer's description of recursive tail call optimisation in es6, I've since been trying to recreate the 'zero-stack' execution of the recursive factorial function he details. Using the Chrome debugger to step between stack…
61
votes
12 answers

Does CUDA support recursion?

Does CUDA support recursion?
JuanPablo
  • 23,792
  • 39
  • 118
  • 164
61
votes
4 answers

Infinite loop in constructor without for or while

I did a test here, but the output is a loop without ending, I don't know why. Actually, I am doing another test, but when I wrote this, I don't understand how the loop occurred. It is output "ABC" repeatedly. #include #include…
CJAN.LEE
  • 1,108
  • 1
  • 11
  • 20
61
votes
3 answers

Return in Recursive Function

I have just started learning python (v3.2.3) and have encountered an odd problem about the return in this function: def test(x): if x > 9 : test(x - 10) else: print('real value',x) return x x = int(input()) y =…
Alex Key
  • 611
  • 1
  • 5
  • 3