Array Initialization: Difference between revisions

 
(46 intermediate revisions by 18 users not shown)
Line 1:
{{DeprecatedTask}}
{{task|Basic language learning}}
'''Examples here should be migrated to [[Arrays]] or [[Creating an Associative Array]] and removed from here. If similar code already exists there, simply remove it from here.'''
 
 
Demonstrate how to initialize an array variable with data.
Line 5 ⟶ 7:
See [[Creating_an_Array]] for this topic.
 
=={{header|[[Ada}}]]==
The array value obtained directly from data is called array aggregate. Considering these array declarations:
<lang ada>
Line 24 ⟶ 26:
</lang>
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'''.
==[[C++]]==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Standard - no extensions to language used}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<pre>
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 #
</pre>
Initialization by an aggregate using positional and keyed notations:
<pre>
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
</pre>
 
=={{header|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.
<lang cpp>
// Assign the value 7 to the first element of myArray.
myArray[0] = 7;
</lang>
If '''myArray''' has ten elements, one can use a loop to fill it.
<lang cpp>
// Assign the sequence 1..10 to myArray
for(int i = 0; i < 10; ++i)
myArray[i] = i + 1;
</lang>
If '''myArray''' has two dimensions, you can use nested loops.
<lang cpp>
// 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);
</lang>
 
 
 
=={{header|Haskell}}==
To create any new Array of the various array types, you can use this to initialise it with all elements filled with x, and indexes ranging from n to m
<lang haskell>
newArr :: (Ix i) => i -> i -> e -> Array i e
newArr n m x = listArray (n,m) (repeat x)
 
-----
 
Prelude Data.Array> newArr 0 10 0
array (0,10) [(0,0),(1,0),(2,0),(3,0),(4,0),(5,0),(6,0),(7,0),(8,0),(9,0),(10,0)]
 
Prelude Data.Array> newArr (0,0) (5,5) 0
array ((0,0),(5,5)) [((0,0),0),((0,1),0),((0,2),0),((0,3),0),((0,4),0),((0,5),0),((1,0),0),((1,1),0),((1,2),0),((1,3),0),((1,4),0),((1,5),0),((2,0),0),((2,1),0),((2,2),0),((2,3),0),((2,4),0),((2,5),0),((3,0),0),((3,1),0),((3,2),0),((3,3),0),((3,4),0),((3,5),0),((4,0),0),((4,1),0),((4,2),0),((4,3),0),((4,4),0),((4,5),0),((5,0),0),((5,1),0),((5,2),0),((5,3),0),((5,4),0),((5,5),0)]
</lang>
 
=={{header|Modula-3}}==
The usual module and import code is omitted.
<lang modula3>VAR arr := 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>
Array initialization doesn't have to be used in the array declaration.
<lang modula3>TYPE Vector: ARRAY OF INTEGER;
VAR arr: Vector;
arr := Vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};</lang>
 
== {{header|Python}} ==
 
Python lists are dynamically resizeable. A simple, single dimensional, array can be initialized thus:
 
<lang python>
myArray = [0] * size
</lang>
 
However this will not work as intended if one tries to generalize from the syntax:
 
<lang python>
myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!
</lang>
 
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:
 
<lang python>
myArray = [[0 for x in range(width)] for y in range(height)]
</lang>
 
That is equivalent to:
 
<lang python>
myArray = list()
for x in range(height):
myArray.append([0] * width)
</lang>
 
===STL===
{{libheader|STL}}STL provides '''std::vector''', which behaves as a dynamically-resizable array. When an element is added, its value must be set immediately.
Line 166 ⟶ 68:
std::vector v4 = v3; // v4 is a copy of v3
</lang>
 
==[[F_Sharp|F#]]==
let a = [| 1; 3; 5; 7; 9 |] // array of integers
let b = [| 1 .. 10 |] // initialize with range of integers
let c = [| for n = 1 to 10 do yield n |] // lazy array
let d = [| "hello"; "world" |] // array of strings
 
==[[Haskell]]==
To create any new Array of the various array types, you can use this to initialise it with all elements filled with x, and indexes ranging from n to m
<lang haskell>
newArr :: (Ix i) => i -> i -> e -> Array i e
newArr n m x = listArray (n,m) (repeat x)
 
-----
 
Prelude Data.Array> newArr 0 10 0
array (0,10) [(0,0),(1,0),(2,0),(3,0),(4,0),(5,0),(6,0),(7,0),(8,0),(9,0),(10,0)]
 
Prelude Data.Array> newArr (0,0) (5,5) 0
array ((0,0),(5,5)) [((0,0),0),((0,1),0),((0,2),0),((0,3),0),((0,4),0),((0,5),0),((1,0),0),((1,1),0),((1,2),0),((1,3),0),((1,4),0),((1,5),0),((2,0),0),((2,1),0),((2,2),0),((2,3),0),((2,4),0),((2,5),0),((3,0),0),((3,1),0),((3,2),0),((3,3),0),((3,4),0),((3,5),0),((4,0),0),((4,1),0),((4,2),0),((4,3),0),((4,4),0),((4,5),0),((5,0),0),((5,1),0),((5,2),0),((5,3),0),((5,4),0),((5,5),0)]
</lang>
=={{header|Scala}}==
<lang Scala>// immutable maps
var map = Map(1 -> 2, 3 -> 4, 5 -> 6)
map(3) // 4
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements
map.isDefinedAt(33) // false
map.isDefinedAt(44) // true</lang>
 
<lang scala>// mutable maps (HashSets)
import scala.collection.mutable.HashMap
val hash = new HashMap[Int, Int]
hash(1) = 2
hash += (1 -> 2) // same as hash(1) = 2
hash += (3 -> 4, 5 -> 6, 44 -> 99)
hash(44) // 99
hash.contains(33) // false
hash.isDefinedAt(33) // same as contains
hash.contains(44) // true</lang>
 
<lang scala>// iterate over key/value
hash.foreach {e => println("key "+e._1+" value "+e._2)} // e is a 2 element Tuple
// same with for syntax
for((k,v) <- hash) println("key " + k + " value " + v)</lang>
 
<lang scala>// items in map where the key is greater than 3
map.filter {k => k._1 > 3} // Map(5 -> 6, 44 -> 99)
// same with for syntax
for((k, v) <- map; if k > 3) yield (k,v)</lang>
Anonymous user