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
recursion 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
- http://en.wikipedia.org/wiki/Recursion_(computer_science)
- http://introcs.cs.princeton.edu/java/23recursion/
- http://mathworld.wolfram.com/Recursion.html
Further information
- See recursion