This commit is contained in:
Miloslav Ciz 2025-05-25 18:16:38 +02:00
parent 35c0f438a4
commit 23f4bd88fc
20 changed files with 2028 additions and 1990 deletions

View file

@ -6,6 +6,8 @@ Recursion (from Latin recursio, "running back") in general is a situation in whi
{ Perhaps an analogy to this kind of recursion may be an "Inception"-style multi level dreams: imagine having a dream in a dream in a dream ... and so on -- and then at one point you start waking up, always getting back to where you were in each of the dreams, and so on until you completely wake up. --drummyfish }
[Fun](fun.md) piece of trivia: geography knows the phenomenon of "recursive islands and lakes" -- islands that appear in lakes that appear on islands that appear in lakes etc. [Wikipedia](wikipedia.md) currently lists Lake Yathkyed in Canada as the "deepest" recursion of this type, having an island in lake on island in lake on island in lake.
We subdivide recursion to a **direct** and **indirect**. In direct recursion the function calls itself directly, in indirect function *A* calls a function *B* which ends up (even possibly by calling some more functions) calling *A* again. Indirect recursion is tricky because it may appear by mistake and cause a [bug](bug.md) (which is nevertheless easily noticed as the program will mostly run out of memory and crash).
When a function calls itself, it starts "diving" deeper and deeper and in most situations we want this to stop at some point, so in most cases **a recursion has to contain a terminating condition**. Without this condition the recursion will keep recurring and end up in an equivalent of an infinite loop (which in case of recursion will however crash the program with a [stack overflow](stack_overflow.md) exception). Let's see this on perhaps the most typical example of using recursion, a [factorial](factorial.md) function: