Section 3.8
Programming In QuickBASIC
3.8 Recursion
The process whereby a function or subprogram calls itself is an example of recursion.
To understand recursion in programming we shall look at a mathematical example of
recursion.
f factorial (f!)
7 factorial (7!)
6 factorial (6!)
n factorial (n!) = n × (n - 1) × (n - 2) × (n - 3)...
n! factorial = n × (n - 1)!
This is a recursive definition because the factorial function is defined in terms of
itself.
In programming we write a called factorial#(n%) which calls itself.
3.8.1 The Three Golden Rules Of Recursion
- A stopping condition must be included which when met results in the function
not calling itself again.
- For input values other than the stopping conditionm the function must call
itself.
- The stopping condition must be reached after a finite number of calls.
3.8.2 Advantages And Disadvantages
In general a non-recursive solution is more efficient in terms of both processor time and
memory.
However, sometimes recursive solutions are easier and more natural for the programmer to
write.