Array Initialization

From Rosetta Code
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.

ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
MODE VEC = FLEX[0]INT; # VECTOR is builtin in ALGOL 68R #
MODE MAT = FLEX[0,0]INT;
# MODE STRING = FLEX[0]CHAR; builtin #
MODE BOOLS = FLEX[0]BOOL; # BITS is builtin in the standard #

Initialization by an aggregate using positional and keyed notations:

VEC x := (1, 4, 5);
[100]INT y; FOR i TO UPB y DO y[i]:=0 OD; FOR i FROM 5 TO 20 DO y[i]:= 2 OD; y[2]:=y[3]:= 1;
MAT e := ((1, 0), (0, 1));
[20,30]INT z; FOR i TO UPB z DO FOR j TO 2 UPB z DO z[i,j]:=0 OD OD;
STRING s := "abcd";
STRING l := " "*80;
[2]BOOL b := (TRUE, TRUE);
SKIP

C++

Simple arrays in C++ have no bounds-checking. In order to safely modify the array's contents, you must know in advance both the number of dimensions in the array and the range for each dimension. In C++, all arrays are zero-indexed, meaning the first element in the array is at index 0.

To assign a single value to an array, one uses the [] operator.

 // Assign the value 7 to the first element of myArray.
 myArray[0] = 7;

If myArray has ten elements, one can use a loop to fill it.

 // Assign the sequence 1..10 to myArray
 for(int i = 0; i < 10; ++i)
   myArray[i] = i + 1;

If myArray has two dimensions, you can use nested loops.

 // Create a multiplication table
 for(int y = 0; y < 10; ++y)
   for(int x = 0; x < 10; ++x)
     myArray[x][y] = (x+1) * (y+1);

STL

Library: STL

STL provides std::vector, which behaves as a dynamically-resizable array. When an element is added, its value must be set immediately.

 myVector.push_back(value);

Like simple arrays, std::vector allows the use of the [] operator, and once an element has been added, it can be changed the same way a simple array can.

 myVector[0] = value;

Unlike simple arrays, std::vector allows you to determing the size of the array. You can use this set all of the values in the array:

 // Create a list of numbers from 1 to the size of the vector.
 size_t size = myVector.size();
 for(int i = 0; i < size; ++i)
   myVector[i] = i + 1;

std::vector also provides iterators, allowing you to iterate through a vector's elements the same way you might any other STL container class.

 // Create a list of numbers from 1 to the size of the vector.
 std::vector<int> myVector;
 int val = 0;
 for(std::vector<int>::iterator it = myVector.begin();
     it != myVector.end();
     ++it)
   *it = ++val;

Python

Python lists are dynamically resizeable. A simple, single dimensional, array can be initialized thus:

<python> myArray = [0] * size </python>

However this will not work as intended if one tries to generalize from the syntax:

<python> myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!! </python>

This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of mutables (strings, numbers) and immutables (dictionaries, lists), a change to any one of the "rows" will affect the values in all of them. Thus we need to ensure that we initialize each row with a newly generated list.

To initialize a list of lists one could use a pair of nested list comprehensions like so:

<python> myArray = [[0 for x in range(width)] for y in range(height)] </python>

That is equivalent to:

<python> myArray = list() for x in range(height):

  myArray.append([0] * width)

</python>