Section 6.5 - Arrays
An array type in Ada can contain many components with the same subtype.
An Ada array is quite similar to arrays in many other languages,
but here are some important things to know about them:
-
Ada array indices are not required to start at zero or one.
Array indices can begin (and end) with any discrete value - whatever
makes the most sense for the data.
This means that you can start arrays at -5 (if that makes sense),
and you can use enumerated values as indices as well.
Ada programs usually use a starting index of 1 if there's
no particularly natural starting point; this reduces the
probability of so-called ``one-off'' errors
(people normally count from one, not zero, and
can sometimes get confused when starting from zero).
-
Like many other things in Ada, array accesses (both read and write)
are normally checked at run-time.
Thus, if the array index is out-of-bounds,
instead of quietly doing the wrong thing,
an exception will be raised.
This catches a surprisingly large number of errors.
-
Multi-dimensional arrays are handled in an intuitive way.
-
A directive can be used to pack arrays, which requests
the compiler to store the array in a memory-efficient way.
This is particularly handy for arrays of Boolean and Character values.
-
Using a value from an array intentionally looks like a function call.
That way, if you change an array into a function, code that uses
the values often needs relatively few changes.
-
You can define array types without completely fixing their
minimum and maximum size.
These are called `unconstrained' arrays.
While they are very useful, we will discuss them further later.
Here are a few examples:
-- Sample array type definitions:
type Table is array(1 .. 100) of Integer; -- 100 Integers.
type Schedule is array(Day) of Boolean; -- Seven Booleans, one per Day
type Grid is array(-100 .. 100, -100 .. 100) of Float; -- 40401 Floats.
-- Sample variable declarations:
Products_On_Hand : Table; -- This variable has 100 Integers.
Work_Schedule : Schedule;
Temperature : Grid;
-- And sample uses:
Products_On_Hand(1) := 20; -- We have 20 of Product number 1
Work_Schedule(Sunday) := False; -- We don't work on Sunday.
Temperature(0,0) := 100.0; -- Set temperature to 100.0 at grid point (0,0).
Put(Products_On_Hand(1)); -- Print out the number 20.
There is no quiz question for this section.
You may go to the next section.
You may also:
David A. Wheeler (dwheeler@ida.org)
The master copy of this file is at
"http://www.adahome.com/Tutorials/Lovelace/s6s5.htm".