Arrays: Difference between revisions

Content added Content deleted
No edit summary
Line 5,032: Line 5,032:


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>VAR a: ARRAY [1..10] OF INTEGER;</lang>
<lang modula3>VAR staticArray: ARRAY [1..10] OF INTEGER;</lang>
Defines an array of 10 elements, indexed 1 through 10.
Defines a static array of 10 elements, indexed 1 through 10.


Arrays can also be given initial values:
Static arrays can also be given initial values:
<lang modula3>VAR a := ARRAY [1..10] OF INTEGER {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
<lang modula3>VAR staticArray := ARRAY [1..10] OF INTEGER {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
VAR arr1 := ARRAY [1..10] OF INTEGER {1, ..} (* Initialize all elements to 1. *)</lang>
VAR staticArray2 := ARRAY [1..10] OF INTEGER {1, ..} (* Initialize all elements to 1. *)</lang>


Open (dynamic) arrays can be be defined by creating a reference to an array of an unspecified size:
To retrieve an element:
<lang modula3>VAR arr := ARRAY [1..3] OF INTEGER {1, 2, 3};
<lang modula3>TYPE TOpenIntArray = REF ARRAY OF INTEGER;
VAR myVar := a[2];</lang>
VAR openArray: TOpenIntArray;</lang>
Defines an open array of a currently unknown size.
To assign a value to an element:

<lang modula3>VAR arr := ARRAY [1..3] OF INTEGER;
Open arrays must first be initialized via a call to the built-in function NEW, passing in the type and the size of the array.
arr[1] := 10;</lang>
The allocation is performed on the heap and all elements are initialized to 0:
<lang modula3>openArray := NEW(TOpenIntArray, 10);</lang>
Initializes the open array to hold 10 elements, indexed 0 through 9. Modula-3 uses garbage collection for heap allocated data by default, so once all references to the open array go out of scope, the memory it occupied is de-allocated automatically.

Retrieval or insertion of elements and determining array bounds is performed using the same built-in functions regardless of the array kind. Though open arrays must first be de-referenced when passing them to such functions. Assuming we have made the declarations above, we can do the following:
<lang modula3> VAR
staticArraySize := NUMBER(staticArray);
staticArrayElement := staticArray[4];

openArraySize := NUMBER(openArray^); (* Note the dereference. *)
openArrayElement := openArray[9];</lang>

<lang modula3>staticArray[4] := 100;
openArray[1] := 200;</lang>


=={{header|Monte}}==
=={{header|Monte}}==