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.

8 Arrays<br />

This chapter <strong>in</strong>troduces arrays that implement a collection facility for objects. With this facility, objects<br />

are stored and retrieved us<strong>in</strong>g an <strong>in</strong>dex of a discrete type.<br />

8.1 Arrays as conta<strong>in</strong>er objects<br />

An array is a collection of objects that can be accessed us<strong>in</strong>g an <strong>in</strong>stance of a discrete type. For example, the<br />

number of computer term<strong>in</strong>als <strong>in</strong> five rooms could be described with the follow<strong>in</strong>g declaration:<br />

Computers_In_Room : array ( 1 .. 5 ) of Natural;<br />

Note: Computers_In_Room is a collection of Natural numbers and the <strong>in</strong>teger numbers 1 through 5<br />

are used to select a particular object <strong>in</strong> this collection.<br />

The compiler will check that the subscript is valid. If it cannot be checked directly, code should be<br />

<strong>in</strong>serted which will perform the check at run-time. The exception Constra<strong>in</strong>t_error is raised if<br />

the <strong>in</strong>dex is out of bounds.<br />

The number of term<strong>in</strong>als <strong>in</strong> each room can be recorded <strong>in</strong> the collection Computers_In_Room by us<strong>in</strong>g an<br />

array <strong>in</strong>dex to select a particular computer room. For example, to set the number of computers <strong>in</strong> room 1 to 20, 2<br />

to 30, 3 to 25, 4 to 10 and 5 to 15, the follow<strong>in</strong>g code can be used:<br />

Computers_In_Room(1) := 20;<br />

Computers_In_Room(2) := 30;<br />

Computers_In_Room(3) := 25;<br />

Computers_In_Room(4) := 10;<br />

Computers_In_Room(5) := 15;<br />

This can be visualized diagrammatically as shown <strong>in</strong> Figure 8.1.<br />

1 2 3 4 5<br />

20 30 25 10 15<br />

Index used to access contents of collection<br />

computers_In_Room<br />

Figure 8.1 Diagrammatic representation of an array.<br />

Once <strong>in</strong>formation about the number of computers <strong>in</strong> each room has been set up, it can be pr<strong>in</strong>ted with the<br />

follow<strong>in</strong>g code:<br />

for I <strong>in</strong> 1 .. 5 loop<br />

Put("Computers <strong>in</strong> room "); Put( I, Width=>1 ); Put(" is ");<br />

Put( Computers_In_Room(I), Width=>2 ); New_L<strong>in</strong>e;<br />

end loop;<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!