Recursion
From Coderwiki
More actions
Recursion is the process of repeating code by calling a subroutine from within that same subroutine.
Pseudocode example
edit edit sourcefunction factorial(n: int) -> int
if n <= 1 then
return n
endif
return n * factorial(n - 1)
endfunction
C example
edit edit sourceThe same code in the C programming language would look like this:
int factorial(int n) {
if (n == 1) {
return n;
}
return n * factorial(n - 1);
}
The same C code with iteration
edit edit sourceThe alternative to using recursion would be to use iteration. This isn't always the best option, so sometimes iteration is a better choice:
int factorial(int n) {
int result = n;
for (int i = n-1; i > 1; i--) {
result *= i;
}
return result;
}