Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Recursion: Difference between revisions

From Coderwiki
new: info, examples (pseudocode, c recursion, c iteration)
 
(No difference)

Latest revision as of 11:53, 12 August 2025

Recursion is the process of repeating code by calling a subroutine from within that same subroutine.

Pseudocode example

edit edit source
function factorial(n: int) -> int
    if n <= 1 then
        return n
    endif
    return n * factorial(n - 1)
endfunction

The 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 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;
}