Basic Pascal Tutorial/Chapter 4/Recursion
English · Français · Български · 中文(中国) · 日本語
4E - Recursion (author: Tao Yue, state: unchanged)
Recursion means allowing a function or procedure to call itself until some limit is reached.
The summation function, designated by an uppercase letter sigma (Σ) in mathematics, can be written recursively:
function Summation (num : integer) : integer;
begin
if num = 1
then Summation := 1
else Summation := Summation(num-1) + num
end;Suppose you call Summation for 3.
a := Summation(3);Summation(3)becomesSummation(2) + 3.Summation(2)becomesSummation(1) + 2.- At
1, the recursion stops and becomes1. Summation(2)becomes1 + 2 = 3.Summation(3)becomes3 + 3 = 6.abecomes6.
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.
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.
In the example above, the base condition was if num = 1.
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.
Talk about this page
Nobody has opened a bench for this page yet. Sign in to open one.
