Jump to content

Arrays: Difference between revisions

1,162 bytes added ,  2 years ago
m
No edit summary
Line 5,032:
 
=={{header|Modula-3}}==
<lang modula3>VAR astaticArray: ARRAY [1..10] OF INTEGER;</lang>
Defines ana static array of 10 elements, indexed 1 through 10.
 
ArraysStatic arrays can also be given initial values:
<lang modula3>VAR astaticArray := ARRAY [1..10] OF INTEGER {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
VAR arr1staticArray2 := 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>VARTYPE arrTOpenIntArray := REF ARRAY [1..3] OF INTEGER {1, 2, 3};
VAR myVar openArray:= a[2]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;
arropenArray[1] := 10200;</lang>
 
=={{header|Monte}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.