18.10.2014 Views

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

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.

66 Procedures and functions<br />

5.5.3 Summary of access to formal parameters<br />

Formal parameter specified by:<br />

(us<strong>in</strong>g as an example an<br />

Integer formal parameter)<br />

Write to<br />

formal<br />

parameter<br />

allowed<br />

Read from<br />

formal<br />

parameter<br />

Can be used as a<br />

parameter to<br />

item: Integer r √ procedure or function<br />

item: <strong>in</strong> Integer r √ procedure or function<br />

item: <strong>in</strong> out Integer √ √ procedure only<br />

item: out Integer √ √ procedure only<br />

5.6 Recursion<br />

Recursion is the ability of a procedure or function to make a call on itself from with<strong>in</strong> its own code body. Whilst<br />

this <strong>in</strong>itially may seem a strange idea, it can lead to very elegant code sequences that otherwise would require<br />

many more l<strong>in</strong>es of code. In certa<strong>in</strong> exceptional cases recursion is the only way to implement a problem.<br />

An example of a recursive procedure to write a natural number us<strong>in</strong>g only character based output is sketched<br />

<strong>in</strong> outl<strong>in</strong>e below:<br />

Write a natural number: (write_natural)<br />

• Split the natural number <strong>in</strong>to two components<br />

(a) The first digit (rema<strong>in</strong>der when number divided by 10)<br />

(b) The other digits (number divided by 10).<br />

For example:<br />

123 would be split <strong>in</strong>to:<br />

3 (first digit)<br />

12 (other digits).<br />

• If the other digits are greater than or equal to 10 then write the other digits by recursively<br />

call<strong>in</strong>g the code to write a decimal number.<br />

• Output the first digit as a character.<br />

The sequence of calls made is<br />

Call<br />

Implemented as<br />

write_natural( 123 ) write_natural(12); output first digit 3<br />

write_natural( 12 ) write_natural(1); output first digit 2<br />

write_natural( 1 ) output first digit 1<br />

This process is diagrammatically expressed <strong>in</strong> Figure 5.4.<br />

Initial call<br />

Split<br />

recursive call on 12<br />

Split<br />

recursive call on 1<br />

123<br />

Split<br />

but no recursive call required<br />

12 3<br />

1<br />

2<br />

1<br />

Unw<strong>in</strong>d<br />

Figure 5.4 Illustration of recursive calls to pr<strong>in</strong>t the natural number 123.<br />

© M A Smith - May not be reproduced without permission

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

Saved successfully!

Ooh no, something went wrong!