Array Initialization: Difference between revisions

From Rosetta Code
Content added Content deleted
(Ada solution added)
m (Moved to Basic learning cat)
Line 1: Line 1:
{{task}}
{{task|Basic language learning}}


Demonstrate how to initialize an array variable with data.
Demonstrate how to initialize an array variable with data.

Revision as of 23:25, 22 August 2008

Task
Array Initialization
You are encouraged to solve this task according to the task description, using any language you may know.

Demonstrate how to initialize an array variable with data.

See Creating_an_Array for this topic.

Ada

The array value obtained directly from data is called array aggregate. Considering these array declarations: <Ada> type Vector is array (Integer range <>) of Integer; type Matrix is array (Integer range <>, Integer range <>) of Integer; type String is array (Integer range <>) of Character; type Bits is array (Integer range <>) of Boolean; </Ada> Initialization by an aggregate using positional and keyed notations: <Ada> X : Vector := (1, 4, 5); Y : Vector (1..100) := (2|3 => 1, 5..20 => 2, others => 0); E : Matrix := ((1, 0), (0, 1)); Z : Matrix (1..20, 1..30) := (others => (others => 0)); S : String := "ABCD"; L : String (1..80) := (others => ' '); B : Bits := not (1..2 => False); -- Same as (1..2 => True) </Ada> Note that the array bounds, when unconstrained as in these examples can be either determined by the aggregate, like the initialization of X shows. Or else they can be specified as a constraint, like for example in the initialization of Y. In this case others choice can be used to specify all unmentioned elements. But in any case, the compiler verifies that all array elements are initialized by the aggregate. Single dimensional arrays of characters can be initialized by character strings, as the variable S shows. Of course, array aggregates can participate in array expressions and these expressions can be used to initialize arrays. The variable B is initialized by an aggregate inversed by the operation not.