23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

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.

3.5 Recursion<br />

We have seen that repetition can be achieved by writ<strong>in</strong>g loops, such as for loops <strong>and</strong><br />

while loops. Another way to achieve repetition is through recursion, which occurs<br />

when a function calls itself. We have seen examples of methods call<strong>in</strong>g other<br />

methods, so it should come as no surprise that most modern programm<strong>in</strong>g languages,<br />

<strong>in</strong>clud<strong>in</strong>g <strong>Java</strong>, allow a method to call itself. In this section, we will see why this<br />

capability provides an elegant <strong>and</strong> powerful alternative for perform<strong>in</strong>g repetitive<br />

tasks.<br />

The Factorial function<br />

To illustrate recursion, let us beg<strong>in</strong> with a simple example of comput<strong>in</strong>g the value<br />

of the factorial function. The factorial of a positive <strong>in</strong>teger n, denoted n!, is def<strong>in</strong>ed<br />

as the product of the <strong>in</strong>tegers from 1 to n. If n = 0, then n! is def<strong>in</strong>ed as 1 by<br />

convention. More formally, for any <strong>in</strong>teger n ≥ 0,<br />

For example, 5! = 5·4·3·2·1 = 120. To make the connection with methods clearer,<br />

we use the notation factorial(n) to denote n!.<br />

188

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

Saved successfully!

Ooh no, something went wrong!