Recursion is a difficult topic to grasp. However, it's very easy to apply once you understand it. The programming assignment for this chapter will involve recursion.
Recursion means allowing a function or procedure to call itself. It keeps calling itself until some limit is reached.
The summation function, designated by an uppercase Sigma in mathematics, is a popular example of recursion:
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);
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.
Very important! All recursive procedures/functions must have some sort of test so stop the recursion. Under one condition, called the base condition, the recursion should stop. Under all other conditions, the recursion should go deeper. In the example above, the base condition was if num = 1. If you don't build in a base condition, the recursion will either not take place at all, or become infinite.
![]() Previous lesson |
![]() Next lesson |
![]() Contents |
![]() Index |
![]() e-mail me |