Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 4/Recursion: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Basic Pascal Tutorial/Chapter 4/Recursion

OldNewLine
1+4E - Recursion (author: Tao Yue, state: unchanged)
2+
3+**Recursion** means allowing a function or procedure to call itself until some limit is reached.
4+
5+The summation function, designated by an uppercase letter *sigma* (Σ) in mathematics, can be written recursively:
6+
7+``` pascal
8+function Summation (num : integer) : integer;
9+begin
10+ if num = 1
11+ then Summation := 1
12+ else Summation := Summation(num-1) + num
13+end;
14+```
15+
16+Suppose you call `Summation` for `3`.
17+
18+``` pascal
19+a := Summation(3);
20+```
21+
22+- `Summation(3)` becomes `Summation(2) + 3`.
23+- `Summation(2)` becomes `Summation(1) + 2`.
24+- At `1`, the recursion stops and becomes `1`.
25+- `Summation(2)` becomes `1 + 2 = 3`.
26+- `Summation(3)` becomes `3 + 3 = 6`.
27+- `a` becomes `6`.
28+
29+Recursion works backward until a given point is reached at which an answer is defined, and then works forward with that definition, solving the other definitions which rely upon that one.
30+
31+All recursive procedures/functions should have a test to stop the recursion, the base condition. Under all other conditions, the recursion should go deeper. If there is no base condition, the recursion will either not take place at all, or become infinite.
32+
33+In the example above, the base condition was `if num = 1`.
34+
35+---
36+*From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 4/Recursion", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history