30.07.2013 Views

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

SHOW MORE
SHOW LESS

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

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

Chapter 6 Procedures 219<br />

The fac<strong>to</strong>rial of an integer number greater than or equal <strong>to</strong> 0 can be calculated iteratively<br />

(nonrecursively) using a For repetition structure, as follows:<br />

Dim counter, fac<strong>to</strong>rial As Integer = 1<br />

For counter = number To 1 Step -1<br />

fac<strong>to</strong>rial *= counter<br />

Next<br />

We arrive at a recursive definition of the fac<strong>to</strong>rial procedure with the following relationship:<br />

n! = n · ( n - 1 )!<br />

For example, 5! is clearly equal <strong>to</strong> 5 · 4!, as is shown by the following:<br />

5! = 5 · 4 · 3 · 2 · 1<br />

5! = 5 · ( 4 · 3 · 2 · 1 )<br />

5! = 5 · ( 4! )<br />

A recursive evaluation of 5! would proceed as in Fig. 6.18. Figure 6.18a shows how<br />

the succession of recursive calls proceeds until 1! is evaluated <strong>to</strong> be 1, which terminates the<br />

recursion. Figure 6.18b depicts the values that are returned from each recursive call <strong>to</strong> its<br />

caller until the final value is calculated and returned.<br />

The program of Fig. 6.19 recursively calculates and prints fac<strong>to</strong>rials. (The choice of<br />

the data type Long will be explained soon). The recursive method Fac<strong>to</strong>rial (lines 33–<br />

41) first tests (line 35) <strong>to</strong> determine whether its terminating condition is true (i.e., number<br />

is less than or equal <strong>to</strong> 1). If number is less than or equal <strong>to</strong> 1, Fac<strong>to</strong>rial returns 1, no<br />

further recursion is necessary, and the method returns. If number is greater than 1, line 38<br />

expresses the problem as the product of number and a recursive call <strong>to</strong> Fac<strong>to</strong>rial, evaluating<br />

the fac<strong>to</strong>rial of number - 1. Note that Fac<strong>to</strong>rial(number - 1) is a slightly<br />

simpler problem than the original calculation, Fac<strong>to</strong>rial(number).<br />

5!<br />

5 * 4!<br />

4 * 3!<br />

3 * 2!<br />

2 * 1!<br />

Fig. Fig. Fig. 6.18 6.18 Recursive evaluation of 5!.<br />

1<br />

5!<br />

5 * 4!<br />

Final value = 120<br />

4 * 3!<br />

5! = 5 * 24 = 120 is returned<br />

3 * 2!<br />

4! = 4 * 6 = 24 is returned<br />

2 * 1!<br />

3! = 3 * 2 = 6 is returned<br />

(a) Procession of recursive calls (b) Values returned from each recursive call<br />

1<br />

2! = 2 * 1 = 2 is returned<br />

1 returned

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

Saved successfully!

Ooh no, something went wrong!