Array Initialization

From Rosetta Code

Jump to: navigation, search

Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.

Code examples should be formatted along the lines of one of the existing prototypes.

Demonstrate how to initialize an array variable with data.

See Creating_an_Array for this topic.

[edit] Ada

The array value obtained directly from data is called array aggregate. Considering these array declarations:

 
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;
 

Initialization by an aggregate using positional and keyed notations:

 
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)
 

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.

Personal tools