Creating an Array: Difference between revisions

From Rosetta Code
Content added Content deleted
(Ol code moved to arrays)
(Blanked page since people can't / don't read)
 
Line 6: Line 6:
In this task, the goal is to create an [[array]]. Mention if the [[array base]] begins at a number other than zero.
In this task, the goal is to create an [[array]]. Mention if the [[array base]] begins at a number other than zero.
In addition, demonstrate how to initialize an array variable with data.
In addition, demonstrate how to initialize an array variable with data.

==[[ALGOL 68]]==
As with all ALGOL 68 declarations the programmer has the choice of using the full declaration syntax, or using [[wp:syntactic sugar|syntactic sugar]] - c.f. "sugared" variables below.

Example of array of 10 integer types:
<lang algol68>REF []INT numbers = HEAP [1:10] INT;
HEAP [1:10]INT sugared hnumbers; # from global memory #
LOC [1:10]INT sugared lnumbers1; # from the stack #
[10]INT sugared lnumbers2; # from the stack - LOC scope is implied #</lang>
Note that the array can be taken from the heap, or stack.

Example of array of 3 string types:
<lang algol68>[]STRING cwords = ( "these", "are", "arrays" ); # array is a constant and read-only (=) #
[3]STRING vwords := ( "these", "are", "arrays" ); # array is a variable and modifiable (:=) #</lang>
The coder can also declare the size of the array and initialize the values at the same time:
<lang algol68>REF []INT more numbers = LOC [3]INT := ( 21, 14 ,63 );
[]INT sugared more cnumbers = ( 21, 14 ,63 );
[3]INT sugared more vnumbers := ( 21, 14 ,63 );</lang>
For Multi-Dimensional arrays the coder declare them the same except for a comma in the type declaration.
The following creates a 3x2 int matrix
<lang algol68>REF [][]INT number matrix = LOC [3][2] INT;
[3,2]INT sugared number matrix1; # an matrix of integers #
[3][2]INT sugared number matrix2; # an array of arrays of integers #</lang>
As with the previous examples the coder can also initialize the values of the array, the only
difference being each row in the matrix must be enclosed in its own braces.
<lang algol68>[][]STRING string matrix = ( ("I","swam"), ("in","the"), ("freezing","water") );</lang>
or
<lang algol68>REF [][] STRING funny matrix = LOC [2][2]STRING := ( ("clowns", "are") , ("not", "funny") );
[2][2] STRING sugared funny matrix := ( ("clowns", "are") , ("not", "funny") );</lang>
Further, the arrays can start at any number:
<lang algol68>[-10:10] INT balanced; # for example -10 #</lang>
If the array is expected to change size in future, then the programmer can also declare it FLEX.
<lang algol68>FLEX [-10:10] INT flex balanced;</lang>
This next piece of code creates an array of references to integers. The value of
each integer "pointed at" is the square of it's index in the array.
<lang algol68>[-10:10] REF INT array of pointers to ints;
FOR index FROM LWB array of pointers to ints TO UPB array of pointers to ints DO
array of pointers to ints[index] := HEAP INT := i*i # allocate global memory #
OD</lang>

{{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}}
<lang algol68>MODE VEC = FLEX[0]REAL; # VECTOR is builtin in ALGOL 68R #
MODE MAT = FLEX[0,0]REAL;
# MODE STRING = FLEX[0]CHAR; builtin #
MODE BOOLS = FLEX[0]BOOL; # BITS is builtin in the standard #</lang>
Initialization by an aggregate using positional and keyed notations:
<lang algol68>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);
BITS byte := (TRUE, TRUE);
SKIP</lang>

==[[AutoHotkey]]==
AutoHotkey does not have arrays yet.
However, variables can be set to arbitrary size and pointer operations can be used, simulating arrays. Just without the syntactic sugar of '[]'.
<lang AutoHotkey>
size = 1000
value = 0
VarSetCapacity(arrayVar, size, value)
</lang>

==[[BASIC]]==

==[[C++]]==
<nowiki>{{libheader|Qt}}</nowiki>

==[[C sharp|C#]]==



==[[Common Lisp]]==

==[[D]]==
{{works with|DMD}}

{{works with|GDC}}
<lang d> // dynamic array
int[] numbers = new int[5];
// static array
int[5] numbers = [0,1,2,3,4];</lang>

==[[Fortran]]==
In ANSI FORTRAN 77 or later, this is a default-indexing array declaration:

<lang fortran>integer a(10)</lang>

This array will have ten elements. Counting starts at 1.

If a zero-based array is needed, declare like this:

<lang fortran>integer a(0:9)</lang>

This mechanism can be extended to any numerical indices, and any of the up-to-seven-allowed number of dimensions (and of course to other data types than integers). For example:

<lang fortran>real a(25:29,12)</lang>

will be an two-dimensional, 5x12-array of type REAL, where the first dimension can be addressed numerically as 25, 26, 27, 28 or 29 (and the second dimension as 1 .. 12).

Fortran 90 and later can use also the syntax

<lang fortran>real, dimension(20) :: array</lang>

Dynamic array (in Fortran 90 and later) can be declared as:

<lang fortran>integer, dimension(:), allocatable :: array
real, dimension(:,:), allocatable :: multidim_array</lang>

and then the space can be allocated/deallocated with:

<lang fortran>allocate(array(array_dimension))
allocate(multidim_array(20,20))
!...
deallocate(array)
deallocate(multidim_array)</lang>

where <tt>array_dimension</tt> is an integer.

Dimension of array can be inspected with <tt>size</tt> intrinsic, and bounds with <tt>ubound</tt> and <tt>lbound</tt>:

<lang fortran> real :: array(20:30), another(10,0:19)

print *, size(another) ! 10 elements for the first "column", 20 for the second,
! we obtain 200
print *, size(array) ! from 20 to 30, we can hold 11 values
print *, size(another, 1) ! "column" 1 has 10 elements, from 1 to 10
print *, size(another, 2) ! "column" 2 has 20 elements, from 0 to 19
print *, lbound(array) ! lower bound is 20
print *, ubound(array) ! upper bound is 30
print *, lbound(another,1) ! is 1
print *, lbound(another,2) ! is 0
print *, lbound(another) ! return an array, (/ 1, 0 /)
print *, ubound(another,1) ! is 10
print *, ubound(another,2) ! is 19
print *, ubound(another) ! return an array, (/ 10, 19 /) </lang>

Outputs

<pre> 200
11
10
20
20
30
1
0
1 0
10
19
10 19</pre>

Array can be initialized also using "implied do loop"

<lang fortran> real :: b(9) = (/ 1,2,3,4,5,6,7,8,9 /) ! array constructor
real :: c(10) = (/ (2**i, i=1, 10) /) ! array constructor with "implied do loop"</lang>

There's no way to initialize a matrix, but reshaping it properly:

<lang fortran> real :: d(2, 5) = reshape( (/ (2**i,i=1,10) /), (/ 2, 5 /) )
! ^^^^^^^^^^^^^^^^^^^source array ^^^^^^^^^^ dimension shape
! Fills the array in COLUMN MAJOR order. That is, traverse the first dimension first,
! second dimension second, etc.
! In order to fill a matrix in ROW MAJOR order, merely specify as before,
! but TRANSPOSE the result
real :: e(4, 4) = transpose( reshape( &
(/ 1, 2, 3, 4, &
5, 6, 7, 8, &
9, 10, 11, 12, &
13, 14, 15, 16 /), (/ 4, 4 /) ) )</lang>

=={{header|FunL}}==
FunL supports single and multidimensional arrays, which can be initialized from any sequence type. Arrays are always zero based.
<lang funl>println( array(5) ) // one dimensional 5 element array (uninitialized)
println( array(3, 2) ) // two dimensional 3 by 2 element array (uninitialized)
println( array([1, 2, 3, 4, 5]) ) // one dimensional 5 element array (initialized from a list)
println( array(((1, 2), (3, 4), (5, 6))) ) // two dimensional 3 by 2 element array (initialized from a tuple containing row tuples)</lang>

{{out}}

<pre>
ArraySeq(null, null, null, null, null)
ArraySeq(ArraySeq(null, null), ArraySeq(null, null), ArraySeq(null, null))
ArraySeq(1, 2, 3, 4, 5)
ArraySeq(ArraySeq(1, 2), ArraySeq(3, 4), ArraySeq(5, 6))
</pre>

==[[Haskell]]==

Arrays are initialized either by a list of index-value-pairs or by a list of values:

<lang haskell>import Data.Array

a = array (1,3) [(1,42),(2,87),(3,95)]
a' = listArray (1,3) [42,87,95]
</lang>

Lower and upper bounds (here ''1'' and ''3'') are arbitrary values of any type that is an instance of ''Ix''. If not all initial values are given, the corresponding index is left ''undefined''.

There are several flavours of arrays in Haskell, but creation looks very similar for the others.

==[[IDL]]==
IDL doesn't really distinguish between scalars and arrays - the same operations that can create the one can ''usually'' create the other as well.

<lang idl> a = 3
help,a
A INT = 3
print,a^2
9</lang>

<lang idl> a = [3,5,8,7]
help,a
A INT = Array[4]
print,a^2
9 25 64 49</lang>
==[[J]]==
"Creating an array" is topic seldom discussed in J as all data in J is an array, and every verb takes array argument(s) and returns an array result. For example, in J, the value '''3''' is an array with zero dimensions where the value '''4 5''' is an array with one dimension (this list has 2 elements), as is the empty string '''<nowiki>''</nowiki>''' (this list has 0 elements).

Here are some additional examples:

<lang j> a=: 3 4 $ 3 1 4 1 5 9 2 6 5 3 5 8 NB. make a 3-by-4 table
a NB. display a
3 1 4 1
5 9 2 6
5 3 5 8
b=: 10 20 30 NB. make a 3-element list
a + b NB. add corresponding items of a and b
13 11 14 11
25 29 22 26
35 33 35 38

] c=: 3 4 $ 'eleemosynary' NB. make a 3-by-4 character table and display it
elee
mosy
nary
|."1 c NB. reverse each item of c
eele
ysom
yran</lang>

Both the <tt>a+b</tt>and the <tt>|."1 c</tt> expressions create arrays.

==[[Mathematica]]==
Creating an array is simply done with Set (=). An array can contain anything, and can have different Heads. A formule like 2+3x+x^2 is an array: Plus[2,Times[3,x],Times[2,Power[x,2]]]. Each list has different heads (Plus,Times, Power). Arrays are made as follows:
<lang Mathematica>
a={3,1,4,1,5,9,2,6,5};
b={"This","is","a","list","of","strings"};
c={"text can",3,"be","mixed","with",4,"numbers"};
d={Pi,{1,"list in list"},4,a,True};
</lang>
Note that arrays can have any dimensions, and don't have to be rectangular (every (sub)element can have different length).

==[[MAXScript]]==
{{works with|3D Studio Max|8}}

Direct assignment method:
<lang maxscript> myArray = #()
myArray2 = #("Item1", "Item2")</lang>
Collect method:
<pre>arr = for i in 1 to 100 collect 0</pre>
Append method:
<pre>arr = #()
for i in 1 to 100 do append arr 0</pre>
Assign and dynamically grow method:
<pre>arr = #()
for i in 1 to 100 do arr[i] = 0</pre>

==[[mIRC Scripting Language]]==
{{works with|mIRC Script Editor}}

{{works with|mArray Snippet}}
<lang mirc>alias creatmearray { .echo -a $array_create(MyArray, 5, 10) }</lang>

==[[Modula-3]]==
Modula-3 arrays include their range in the declaration.
<lang modula3>VAR a: ARRAY [1..10] OF INTEGER;</lang>
Defines an array of 10 elements, indexed 1 through 10.

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};
VAR arr1 := ARRAY [1..10] OF INTEGER {1, ..} (* Initialize all elements to 1. *)</lang>

Modula-3 also offers "open arrays" just like Oberon-2.

Multi-dimensional arrays can be defined as:
<lang modula3>VAR a: ARRAY [1..10], [1..10] OF INTEGER;</lang>
Which creates a 2 dimensional array of 10 integers each.

==[[Nial]]==
To create an array of 5 elements with values from 1 to 5
<lang nial>| count 5
1 2 3 4 5</lang>
Assign it to a variable
<lang nial>| myarr := count 5</lang>

Use an array literal instead
<lang nial>| newarr := [2 4 6]</lang>

==[[Oberon-2]]==
Create an array of 10 integers. Initial values are undefined. All arrays are zero-indexed.
<lang oberon2>VAR a: ARRAY 10 OF INTEGER;</lang>

Oberon-2 has no array constructor syntax.
<lang oberon2>FOR i := 0 TO LEN(a) - 1 DO
a[i] := i + 1;
END;</lang>

Oberon-2 also has dynamically allocated arrays, called "open arrays". It's size is based on how it is initialized.
<lang oberon2>VAR a: ARRAY OF INTEGER;</lang>

Multi-dimensional arrays can be defined as:
<lang oberon2>VAR a: ARRAY 10, 10, 10 OF INTEGER;</lang>
creates a 3 dimensional array of 10 integers each.

==[[OCaml]]==
Using an array literal:

<lang ocaml> let array = [| 1; 2; 3; 4; 5 |];;</lang>

Converting from a list:

<lang ocaml> let array = Array.of_list some_list</lang>

To create an array of five elements with the value 0:

<lang ocaml> let num_items = 5 and initial_value = 0;;
let array = Array.make num_items initial_value</lang>

To create an array with contents defined by passing each index to a callback (in this example, the array is set to the squares of the numbers 0 through 4):

<lang ocaml> let callback index = index * index;;
let array = Array.init 5 callback</lang>

==[[Ol]]==

Code moved to [http://rosettacode.org/wiki/Arrays#Ol Arrays].

==[[Pascal]]==
'''Using a fixed length array as global or stack variable'''
<lang pascal>var
a: array[2..10] of integer;</lang>
The array base is the first number given in the square brackets, the second number gives the largest valid index. Actually the part between the square brackets is a type, therefore also the following works:
<lang pascal>type
byte: 0..255;
var
a: array[byte] of integer; { same as array[0..255] of integer }</lang>

'''Dynamically allocating a fixed length array on the heap'''
<lang pascal>type
arraytype = array[1..25] of char;
arrayptr = ^arraytype;
var
a: arrayptr;
begin
new(a); { allocate the array }
a^[1] := 'c'; { use it }
dispose(a) { get rid of it }
end</lang>

'''Defining a variable-length array'''

{{works with|Extended Pascal}}

<lang pascal>type
arraytype(size: integer) = array [1 .. size] of real;
arrayptr = ^arraytype;
var
i: integer;
a: arraytype;
begin
readln(i); { get size from user }
new(a, i); { create array }
a^[1] := 3.14; { use it }
if a^.size = i { access the size }
then
writeln('I expected that.');
else
writeln('Get a better compiler!');
dispose(a) { get rid of it }
end</lang>
Note that also the lower index may be given as dynamic argument.

==[[Perl]]==
{{works with|Perl|5}}
<lang perl> my @empty;
my @empty_too = ();

my @populated = ('This', 'That', 'And', 'The', 'Other');
print $populated[2];
# And
my $aref = ['This', 'That', 'And', 'The', 'Other'];
print $aref->[2];
# And

# having to quote like that really sucks, and that's why we got syntactic sugar
my @wakey_wakey = qw(coffee sugar cream);
push @wakey_wakey, 'spoon';
# add spoon to right-hand side
my $cutlery = pop @wakey_wakey;
# remove spoon
unshift @wakey_wakey, 'cup';
# add cup to left-hand side
my $container = shift @wakey_wakey;
# remove cup

my @multi_dimensional = (
[0, 1, 2, 3],
[qw(a b c d e f g)],
[qw(! $ % & *)],
);
print $mdref->[1][3];
# d
</lang>

==[[Pike]]==
For a single dimension int array:
<lang pike> array(int) x = ({ 1, 2, 3 });</lang>

For a single dimension of any type you declare array(mixed) instead of array(int), or just array:
<lang pike> array x = ({ "a", 1, 5.2 });</lang>

For a multi-dimension array, you build an array of arrays:
<lang pike> mixed x = ({ ({ 5 }),({ 3, 2 }), ({ 1, 8 }) });</lang>

Note that inner arrays can be of different sizes, as are simply values of the outer array.

==[[Pop11]]==
Pop11 distinguishes between vectors and arrays. Vectors are one dimensional and the lowest index is 1. There is special shorthand syntax to create vectors:

<lang pop11>;;; General creation of vectors, create initialized vector.
lvars v1 = consvector(1, 'a', "b", 3);
;;; Shorthand notation
lvars v2 = {1 'a' b};
;;; Create vector filled with word undef (to signal that elements
;;; are uninitialized)
lvars v3 = initv(3)</lang>

Pop11 arrays may have arbitrary lower and upper bounds:

<lang pop11>;;; Create array with first index ranging from 2 to 5 and second
;;; index from -1 to 1, initialized with 0
vars a1 = newarray([2 5 -1 1], 0);</lang>

==[[Python]]==
List are mutable arrays. You can put anything into a list, including other lists.

<lang python> empty = []
numbers = [1, 2, 3, 4, 5]
zeros = [0] * 10
anything = [1, 'foo', 2.57, None, zeros]
digits = range(10) # 0, 1 ... 9
evens = range(0,10,2) # 0, 2, 4 ... 8
evens = [x for x in range(10) if not x % 2] # same using list comprehension
words = 'perl style'.split()</lang>

Tuples are immutable arrays. Note that tuples are defined by the "," - the parenthesis are optional (except to disambiguate when creating an empty or single-element tuple):

<lang python> empty = ()
numbers = (1, 2, 3, 4, 5)
numbers2 = 1,2,3,4,5 # same as previous
zeros = (0,) * 10
anything = (1, 'foo', 2.57, None, zeros)</lang>

Both lists and tuples can be created from other iterateables:

<pre>
>>> list('abc')
['a', 'b', 'c']
>>> tuple('abc')
('a', 'b', 'c')
>>> list({'a': 1, 'b': 2, 'c': 3})
['a', 'c', 'b']
>>> open('file', 'w').write('1\n2\n3\n')
>>> list(open('file'))
['1\n', '2\n', '3\n']
</pre>

Note: In Python 2.6 the ''collections.namedtuple'' factory was added to the standard libraries. This can be used to create classes of lightweight objects (c.f. the Flyweight design pattern) which are tuples that can additionally support named fields.


The [http://docs.python.org/library/ctypes.html#arrays ctypes module] can construct specialised arrays for interfacing with external C functions. The [http://docs.python.org/library/struct.html struct module] allows a string of characters to be interpreted as an array of values of C types such as 32 bit ints, float, etc.

==[[R]]==
<lang R>a <- vector("numeric", 10) # a is a vector (array) of 10 numbers
b <- vector("logical", 10) # b is an array of logical (boolean) values
s <- vector("character", 10) # s is an array of strings (characters)</lang>

Indexes start from 1
<lang R>a[1] <- 100
print(a[1]) # [1] 100</lang>

Let's initialize an array with some values
<lang R>a[1:3] <- c(1,2,3)
print(a) # [1] 1 2 3 0 0 0 0 0 0 0
# but this creates a brand new vector made of 3 elements:
a <- c(1,2,3)
# and the following fills b of TRUE FALSE, repeating them
b[] <- c(TRUE, FALSE)
print(b) # [1] TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE</lang>


==[[Raven]]==
<lang raven>[ 1 2 3.14 'a' 'b' 'c' ] as a_list
a_list print</lang>

list (6 items)
0 => 1
1 => 2
2 => 3.14
3 => "a"
4 => "b"
5 => "c"

==[[Ruby]]==
This is the most basic way to create an empty one-dimensional array in Ruby:
<lang ruby> my_array = Array.new
another_array = []</lang>
Arrays of strings:
<lang>x = ['an', 'array', 'of', 'strings']
y = %w{another array of strings without the punctuation}</lang>

Ruby treats comma separated values on the right hand side of assignment as array. You could optionally surround the list with square brackets
<lang ruby> my_array = 1, 2, 3, 4, 5
my_array = [ 1, 2, 3, 4, 5 ]

array = [
[0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2],
[3, 3, 3, 3, 3, 3]
]</lang>
You would call the array by this code. As arrays are zero-indexed, this will call the 4th element on the second list
<lang ruby>array[1][3]</lang>

We have to be careful when creating multidimensional arrays:
<lang ruby>a = [[0] * 3] * 2] # [[0, 0, 0], [0, 0, 0]]
a[0][0] = 1
p a # [[1, 0, 0], [1, 0, 0]]</lang>
So both inner arrays refer to the same object
<lang ruby>a[0].equal? a[1] # true</lang>
The better way to create a multidimensional array is to use the form of <tt>Array.new</tt> that takes a block:
<lang ruby>a = Array.new(2) {Array.new(3) {0}}
p a # [[0, 0, 0], [0, 0, 0]]
a[1][1] = 1
p a # [[0, 0, 0], [0, 1, 0]]</lang>

You can also create a sequential array from a range using the 'splat' operator:
<lang ruby> array = [*0..3]
# or use the .to_a method for Ranges
array = (0..3).to_a #=> [0,1,2,3]</lang>
This lets us create [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]] programmatically:
<lang ruby> array = [*0..3].map {|i| [i] * 6}
array = 4.times.map {|i| Array.new(6,i)}
array = Array.new(4) {|i| Array.new(6,i)}</lang>

==[[Scala]]==
<lang scala> val array = new Array[int](10) // a 10 element array
val stringArray = new Array[String](20) // a 20 element string array
List("Elwood", "Madeline", "Archer").toArray
(List(1,2,3) ::: List(4,5,6)).toArray
(1 :: 2 :: 3 :: 4 :: 5 :: Nil).toArray</lang>

==[[Script3D]]==
Script3D has dynamic arrays allowing to store any datatype and a special type for storing vectors of floating point values, typically used in 3D applications.

<lang s3d> var myArray = { "a string" , 1, true, "mixed", Void, 1.5}; // array from list
var myArray = Array(10); // 10 elements array

var myVector = [1,2,3,4];
var myVector = Vector(2000); // 2000 elements vector of floats</lang>

==[[Slate]]==
<lang slate>
define: #array -> (Array newSize: 20).
print: array first.
array at: 1 put: 100.
define: #array -> {'an'. 'apple'. 'a'. 'day'. 'keeps'. 'the'. 'doctor'. 'away'}.
array at: 1 put: 'orange'.
</lang>

==[[Standard ML]]==
Converting from a list:

<lang sml> val array = Array.fromList [1,2,3,4,5]</lang>

To create an array of five elements with the value 0:

<lang sml> val num_items = 5 and initial_value = 0;
val array = Array.array (num_items, initial_value)</lang>

To create an array with contents defined by passing each index to a callback (in this example, the array is set to the squares of the numbers 0 through 4):

<lang sml> fun callback index = index * index;
val array = Array.tabulate (5, callback)</lang>

In addition to arrays, the Standard ML library also has "vectors", which are immutable arrays. Most implementations support the following syntax for a vector literal, although it is not standard:

<lang sml> val vector = #[1,2,3,4,5]</lang>

==[[Tcl]]==

Tcl uses the <tt>list</tt> for what many other languages call "array". A list is an ordered, numerically indexable (zero based) collection of values in a single variable. Each list entry itself can be a list.

<lang tcl>set a [list 5 hello {} [expr 3*5]]</lang>

this creates a list with the name <tt>a</tt> and four elements - the number 5, the word "hello", an empty list, and the result of the expression "3*5".

The <tt>lrepeat</tt> command builds a list by repeating elements
<lang tcl>set a [lrepeat 5 foo] ;# {foo foo foo foo foo}</lang>

lrepeat can be used to create multidimensional lists
<lang tcl>set a [lrepeat 4 [lrepeat 2 0]] ;# {{0 0} {0 0} {0 0} {0 0}}</lang>

Tcl does have an "<tt>array</tt>", though, which is really an "associative array":

<lang tcl>array set b {foo 12 bar hello}</lang>

this creates an array with the name <tt>b</tt> with two elements. The keys of the elements are "foo" and "bar" and the values are <tt>b(foo) == 12</tt> and <tt>b(bar) == hello</tt>.

==[[Toka]]==
Toka allows creation of an array using is-array. Access to the elements is done using get-element, put-element, get-char-element, and put-char-element functions. You can not initialize the values automatically using the core array functions.

<lang toka> 100 cells is-array foo
100 chars is-array bar</lang>

==[[Visual Basic .NET]]==

Implicit Size
<lang vbnet>' An empty array of integers.
Dim empty() AS Integer = {}
' An array of integers.
Dim numbers() AS Integer = {1, 2, 3, 4, 5}
' An array of strings
Dim string() AS String = {"String","foo","etc."}</lang>

Explicit Size
<lang vbnet>' An empty array of integers.
Dim empty(0) AS Integer = {}
' An array of integers.
Dim numbers(4) AS Integer = {1, 2, 3, 4, 5}
' An array of strings
Dim String(2) AS String = {"String","foo","etc."}</lang>

Resize An Array
<lang vbnet>' An empty array of integers.
Dim empty() As Integer = {}
Private Sub ReDimension()
' Resize (And keep all elements intact)
ReDim Preserve empty(1)
' Resize (Erase all elements)
ReDim empty(1)
End Sub</lang>

Splitting strings into arrays
<lang vbnet>Dim words() AS String = 'perl style'.split(" "c) ' You must tell VB that the space is a character by denoting c after the " "</lang>

==[[VBScript]]==

<lang vbscript>Dim myArray(2)
myArray(0) = "Hello"
myArray(1) = "World"
myArray(2) = "!"</lang>

Latest revision as of 15:07, 29 November 2019

Creating an Array was a programming task. It has been deprecated for reasons that are discussed in its talk page.

Please do not add new code, and merge existing code to the Arrays task.

This task is about numerically-indexed arrays. For hashes or associative arrays, please see Creating an Associative Array.

In this task, the goal is to create an array. Mention if the array base begins at a number other than zero. In addition, demonstrate how to initialize an array variable with data.