15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

228<br />

Repeating a Subprogram with Recursion<br />

To calculate a factorial, you could use a BASIC program like this:<br />

FUNCTION Factorial (N as INTEGER) as REAL<br />

IF N > 1 THEN<br />

Factorial = N * Factorial (N– 1)<br />

ELSE<br />

Factorial = 1<br />

END FUNCTION<br />

This function uses recursion to run another copy of itself, as shown in<br />

Figure 6-8.<br />

Figure 6-8:<br />

Recursion<br />

makes<br />

multiple<br />

copies of<br />

the same<br />

subprogram.<br />

Factorial (4) = 4 * Factorial (3)<br />

Factorial (3) = 3 * Factorial (2)<br />

To calculate the factorial of N!, you<br />

need to calculate the factorial of (N – 1).<br />

Factorial (2) = 2 * Factorial (1)<br />

Factorial (1) = 1<br />

Factorial (2) = 2 * 1 = 2<br />

Factorial (3) = 3 * 2 = 6<br />

Factorial (4) = 4 * 6 = 24<br />

Eventually a recursive subprogram must calculate a<br />

single value, which then gets used in previous recursive<br />

subprograms until they calculate a single value.<br />

Ultimately, every subprogram that calls itself needs to end. (Otherwise, it can<br />

get trapped in an endless loop, which hangs or freezes your computer.) When<br />

a subprogram finally ends, it returns a value to the preceding subprogram,<br />

which returns its value to the preceding subprogram, and so on until a value<br />

is finally calculated by the first copy of the subprogram that initially ran.<br />

The advantage of recursion is that it’s much simpler to write. If you didn’t<br />

use recursion, this is how you could calculate factorials using an ordinary<br />

FOR-NEXT loop:<br />

FUNCTION Factorial (N as INTEGER) as REAL<br />

DIM Total as REAL<br />

DIM M as INTEGER<br />

Total = 1<br />

FOR M = N DOWNTO 1<br />

Total = Total * M<br />

Factorial = Total<br />

END FUNCTION<br />

Compared to the much smaller and simpler recursive subprogram, this subprogram<br />

is harder to understand although it calculates the exact same<br />

results.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!