15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Repeating a Subprogram with Recursion 227<br />

This same function as seen in the Python language might look like this:<br />

def convertc2f(temperature):<br />

new = ((9.0/5.0) * temperature) + 32<br />

return new<br />

To run this function, you could use the following program:<br />

temp = 12<br />

print “Temperature in Celsius = “, temp<br />

print “Temperature in Fahrenheit = “, convertc2f(temp)<br />

Repeating a Subprogram with Recursion<br />

In Chapter 5 of this mini-book, you can read about loops that can repeat one<br />

or more commands multiple times. If you want to repeat the commands<br />

stored in a subprogram, you can just call that subprogram from within a<br />

loop, such as<br />

FOR I = 1 TO 4<br />

Subprogram name<br />

NEXT I<br />

Book II<br />

Chapter 6<br />

Breaking a Large<br />

Program into<br />

Subprograms<br />

This example would run all the commands in a subprogram four times.<br />

However, here’s another way to run a subprogram multiple times: recursion.<br />

The idea behind recursion is that instead of defining how many times to run<br />

a subprogram, you let the subprogram call itself multiple times, such as<br />

SUB MySubprogram<br />

MySubprogram<br />

END SUB<br />

When this subprogram runs, it calls itself, essentially making a second copy<br />

of itself, which then makes a third copy of itself, and so on. A common problem<br />

used to demonstrate recursion is calculating a factorial (which multiples<br />

a number by a gradually decreasing series of numbers).<br />

Not every <strong>programming</strong> language supports recursion, such as some versions<br />

of BASIC.<br />

A factorial is often written like this:<br />

4!<br />

To calculate a factorial, you multiply a number (4, in this case) by a number<br />

that’s one less (3) and keep repeating this until you get the value of 1, such as<br />

4! = 4 * 3 * 2 * 1<br />

= 24

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

Saved successfully!

Ooh no, something went wrong!