Arrays

From Rosetta Code

Jump to: navigation, search
Task
Arrays
You are encouraged to solve this task according to the task description, using any language you may know.

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

In this task, the goal is to show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element. (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it.)

Please discuss at Village Pump: Arrays. Please merge code in from obsolete tasks Creating an Array, Assigning Values to an Array, and Retrieving an Element of an Array.

See also

Contents

[edit] ActionScript

//creates an array of length 10
var array1:Array = new Array(10);
//creates an array with the values 1, 2
var array2:Array = new Array(1,2);
//arrays can also be set using array literals
var array3:Array = ["foo", "bar"];
//to resize an array, modify the length property
array2.length = 3;
//arrays can contain objects of multiple types.
array2[2] = "Hello";
//get a value from an array
trace(array2[2]);
//append a value to an array
array2.push(4);
//get and remove the last element of an array
trace(array2.pop());

[edit] Ada

procedure Array_Test is
A : array (1..20) of Integer;
begin
A := (others => 0); -- Assign whole array
A (1) := -1; -- Assign individual element
A (3..5) := (2, 4, -1); -- Assign a slice
A (3..5) := A (4..6); -- It is OK to overlap slices when assigned
end Array_Test;

Arrays are first-class objects in Ada. They can be allocated statically or dynamically as any other object. The number of elements in an array object is always constrained. Variable size arrays are provided by the standard container library. They also can be implemented as user-defined types.

[edit] Aikido

Aikido arrays (or vectors) are dynamic and not fixed in size. They can hold a set of any defined value.

 
var arr1 = [1,2,3,4] // initialize with array literal
var arr2 = new [10] // empty array of 10 elements (each element has value none)
var arr3 = new int [40] // array of 40 integers
var arr4 = new Object (1,2) [10] // array of 10 instances of Object
 
arr1.append (5) // add to array
var b = 4 in arr1 // check for inclusion
arr1 <<= 2 // remove first 2 elements from array
var arrx = arr1[1:3] // get slice of array
var s = arr1.size() // or sizeof(arr1)
delete arr4[2] // remove an element from an array
 
var arr5 = arr1 + arr2 // append arrays
var arr6 = arr1 | arr2 // union
var arr7 = arr1 & arr2 // intersection
 
 

[edit] ALGOL 68

PROC array_test = VOID:
(
[1:20]INT a;
a := others; # assign whole array #
a[1] := -1; # assign individual element #
a[3:5] := (2, 4, -1); # assign a slice #
[1:3]INT slice = a[3:5]; # copy a slice #
 
REF []INT rslice = a[3:5]; # create a reference to a slice #
print((LWB rslice, UPB slice)); # query the bounds of the slice #
rslice := (2, 4, -1); # assign to the slice, modifying original array #
 
[1:3, 1:3]INT matrix; # create a two dimensional array #
REF []INT hvector = matrix[2,]; # create a reference to a row #
REF []INT vvector = matrix[,2]; # create a reference to a column #
REF [,]INT block = matrix[1:2, 1:2]; # create a reference to an area of the array #
 
FLEX []CHAR string := "Hello, world!"; # create an array with variable bounds #
string := "shorter" # flexible arrays automatically resize themselves on assignment #
)

Arrays in ALGOL 68 are first class objects. Slices to any portion of the array can be created and then treated equivalently to arrays, even sections of a multidimensional array; the bounds are queried at run time. References may be made to portions of an array. Flexible arrays are supported, which resize themselves on assignment, but they can't be resized without destroying the data.

[edit] Argile

Works with: Argile version 1.0.0

use std, array
 
(:::::::::::::::::
 : Static arrays :
 :::::::::::::::::)
let the array of 2 text aabbArray be Cdata{"aa";"bb"}
let raw array of real :my array: = Cdata {1.0 ; 2.0 ; 3.0} (: auto sized :)
let another_array be an array of 256 byte (: not initialised :)
let (raw array of (array of 3 real)) foobar = Cdata {
{1.0; 2.0; 0.0}
{5.0; 1.0; 3.0}
}
 
(: macro to get size of static arrays :)
=: <array>.length := -> nat {size of array / (size of array[0])}
printf "%lu, %lu\n" foobar.length (another_array.length) (: 2, 256 :)
 
(: access :)
another_array[255] = '&'
printf "`%c'\n" another_array[255]
 
 
(::::::::::::::::::
 : Dynamic arrays :
 ::::::::::::::::::)
let DynArray = new array of 5 int
DynArray[0] = -42
DynArray = (realloc DynArray (6 * size of DynArray[0])) as (type of DynArray)
DynArray[5] = 243
prints DynArray[0] DynArray[5]
del DynArray

Works with: Argile version 1.1.0

use std, array
let x = @["foo" "bar" "123"]
print x[2]
x[2] = "abc"


[edit] AutoHotkey

AutoHotkey does not have typical arrays. However, variable names can be concatenated, simulating associative arrays. Just without the syntactic sugar of '[]'. By convention, based on built-in function stringsplit, indexes are 1-based and "0" index is the length.

arrayX0 = 4      ; length
arrayX1 = first
arrayX2 = second
arrayX3 = foo
arrayX4 = bar
Loop, %arrayX0%
Msgbox % arrayX%A_Index%
source = apple bear cat dog egg fish
StringSplit arrayX, source, %A_Space%
Loop, %arrayX0%
Msgbox % arrayX%A_Index%

[edit] Batch File

Arrays can be approximated, in a style similar to REXX

::arrays.cmd
@echo off
setlocal ENABLEDELAYEDEXPANSION
set array.1=1
set array.2=2
set array.3=3
set array.4=4
for /L %%i in (1,1,4) do call :showit array.%%i !array.%% class="re2">i!
set c=-27
call :mkarray marry 5 6 7 8
for /L %%i in (-27,1,-24) do call :showit "marry^&%%i" !marry^&%%i!
endlocal
goto :eof
 
:mkarray
set %1^&%c%=%2
set /a c += 1
shift /2
if "%2" neq "" goto :mkarray
goto :eof
 
:showit
echo %1 = %2
goto :eof
 

Output:

array.1 = 1
array.2 = 2
array.3 = 3
array.4 = 4
"marry&-27" = 5
"marry&-26" = 6
"marry&-25" = 7
"marry&-24" = 8

[edit] BASIC

Static:

 
DIM staticArray(10) AS INTEGER
 
staticArray(0) = -1
staticArray(10) = 1
 
PRINT staticArray(0), staticArray(10)
 

Dynamic (Note that BASIC dynamic arrays are not stack-based; instead, their size must be changed in the same manner as their initial declaration -- the only difference between static and dynamic arrays is the keyword used to declare them (DIM vs. REDIM). QBasic lacks the PRESERVE keyword found in some modern BASICs; resizing an array without PRESERVE zeros the values):

 
REDIM dynamicArray(10) AS INTEGER
 
dynamicArray(0) = -1
PRINT dynamicArray(0)
 
REDIM dynamicArray(20)
 
dynamicArray(20) = 1
PRINT dynamicArray(0), dynamicArray(20)
 

[edit] C

Fixed size static array of integers with initialization:

int myArray2[10] = { 1, 2, 0 }; /* the rest of elements get the value 0 */
float myFloats[] ={1.2, 2.5, 3.333, 4.92, 11.2, 22.0 }; /* automatically sizes */

When no size is given, the array is automatically sized. Typically this is how initialized arrays are defined. When this is done, you'll often see a definition that produces the number of elements in the array, as follows.

#define MYFLOAT_SIZE (sizeof(myFloats)/sizeof(myFloats[0]))

When defining autosized multidimensional arrays, all the dimensions except the first (leftmost) need to be defined. This is required in order for the compiler to generate the proper indexing for the array.

long a2D_Array[3][5];    /* 3 rows, 5 columns. */
float my2Dfloats[][3] = {
1.0, 2.0, 0.0,
5.0, 1.0, 3.0 };
#define FLOAT_ROWS (sizeof(my2Dfloats)/sizeof(my2dFloats[0])) /* OR */
#define FLOAT_ROWS (sizeof(my2Dfloats)/sizeof(float))

When the size of the array is not known at compile time, arrays may be dynamically allocated to the proper size. The malloc(), calloc() and free() functions require the header stdlib.h.

int numElements = 10;
int *myArray = malloc(sizeof(int) * numElements); /* array of 10 integers */
if ( myArray != NULL ) /* check to ensure allocation suceeded. */
{
/* allocation succeeded */
/* at the end, we need to free the allocated memory */
free(myArray);
}
/* calloc() additionally pre-initializes to all zeros */
short *myShorts = calloc( numElements, sizeof(short)); /* array of 10 */
if (myShorts != NULL)....

Once allocated, myArray can be used as a normal array.

The first element of a C array is indexed with 0. To set a value:

myArray[0] = 1;
myArray[1] = 3;

And to retrieve it (e.g. for printing, provided that the stdio.h header was included for the printf function)

printf("%d\n", myArray[1]);

The array[index] syntax can be considered as a shortcut for *(index + array) and thus the square brackets are a commutative binary operator:

*(array + index) = 1;
printf("%d\n", *(array + index));
3[array] = 5;

There's no bounds check on the indexes. Negative indexing can be implemented as in the following.

#define XSIZE 20
double *kernel = malloc(sizeof(double)*2*XSIZE+1);
if (kernel) {
kernel += XSIZE;
for (ix=-XSIZE; ix<=XSIZE; ix++) {
kernel[ix] = f(ix);
....
free(kernel-XSIZE);
}
}

C natively has no variable length arrays. Typically dynamic allocation is used and the allocated array is sized to the maximum that might be needed. A additional variable is declared and used to maintain the current number of elements used.

[edit] C++

Stack allocated fixed-size (C-style) array:

int myArray[2];
 
myArray[0] = 1;
myArray[1] = 3;
 
cout << myArray[1] << endl;

Heap allocated fixed-size array:

int* myArray = new int[10];
 
myArray[0] = 1;
myArray[1] = 3;
 
cout << myArray[1] << endl;
delete [] myArray;

Heap allocated variable-size array (std::vector) capable of bounds checks:

vector<int> myArray2;
 
myArray2.push_back(1);
myArray2.push_back(3);
 
myArray2[0] = 2;
 
cout << myArray2[0] << endl;

[edit] C#

int[] array = new int[10];
 
array[0] = 1;
array[1] = 3;
 
Console.WriteLine(array[0]);

Dynamic

using System;
using System.Collections;
 
ArrayList<int> array = new ArrayList<int>();
 
array.Add(1);
array.Add(3);
 
array[0] = 2;
 
Console.WriteLine(array[0]);

[edit] Common Lisp

(let ((array (make-array 10)))
(setf (aref array 0) 1
(aref array 1) 3)
(print array))

Dynamic

(let ((array (make-array 0 :adjustable t :fill-pointer 0)))
(vector-push-extend 1 array)
(vector-push-extend 3 array)
(setf (aref array 0) 2)
(print array))

[edit] D

Stack allocated fixed-size array:

import std.stdio;
int main() {
int[5]myArray;
myArray[0] = 1;
myArray[1] = 3;
writefln("Element 0: %d",myArray[0]);
writefln("Element 1: %d",myArray[1]);
return 0;
}

Heap allocated dynamic array capable of bounds checks (note that ~ is the array concat operator):

import std.stdio;
int main() {
int[]myArray;
myArray ~= 1;
myArray ~= 3;
writefln("Element 0: %d",myArray[0]);
writefln("Element 1: %d",myArray[1]);
return 0;
}

[edit] Dao

# use [] to create numeric arrays of int, float, double or complex types:
a = [ 1, 2, 3 ] # a vector
b = [ 1, 2; 3, 4 ] # a 2X2 matrix
 
# use {} to create normal arrays of any types:
c = { 1, 2, 'abc' }
 
d = a[1]
e = b[0,1] # first row, second column
f = c[1]

[edit] E

E's collection library emphasizes providing both mutable and immutable collections. The relevant array-like types are ConstList and FlexList.

Literal lists are ConstLists.

? def empty := []
# value: []
 
? def numbers := [1,2,3,4,5]
# value: [1, 2, 3, 4, 5]
 
? numbers.with(6)
# value: [1, 2, 3, 4, 5, 6]
 
? numbers + [4,3,2,1]
# value: [1, 2, 3, 4, 5, 4, 3, 2, 1]

Note that each of these operations returns a different list object rather than modifying the original. You can, for example, collect values:

? var numbers := []
# value: []
 
? numbers := numbers.with(1)
# value: [1]
 
? numbers with= 2 # shorthand for same
# value: [1, 2]

FlexLists can be created explicitly, but are typically created by diverging another list. A ConstList can be gotten from a FlexList by snapshot.

? def flex := numbers.diverge()
# value: [1, 2].diverge()
 
? flex.push(-3)
? flex
# value: [1, 2, -3].diverge()
 
? numbers
# value: [1, 2]
 
? flex.snapshot()
# value: [1, 2, -3]

Creating a FlexList with a specific size, generic initial data, and a type restriction:

([0] * 100).diverge(int)    # contains 100 zeroes, can only contain integers

Note that this puts the same value in every element; if you want a collection of some distinct mutable objects, see N distinct objects#E.

In accordance with its guarantees of determinism, you can never have an uninitialized FlexList in E.


[edit] Erlang

 
%% Create a fixed-size array with entries 0-9 set to 'undefined'
A0 = array:new(10).
10 = array:size(A0).
 
%% Create an extendible array and set entry 17 to 'true',
%% causing the array to grow automatically
A1 = array:set(17, true, array:new()).
18 = array:size(A1).
 
%% Read back a stored value
true = array:get(17, A1).
 
%% Accessing an unset entry returns the default value
undefined = array:get(3, A1).
 
%% Accessing an entry beyond the last set entry also returns the
%% default value, if the array does not have fixed size
undefined = array:get(18, A1).
 
%% "sparse" functions ignore default-valued entries
A2 = array:set(4, false, A1).
[{4, false}, {17, true}] = array:sparse_to_orddict(A2).
 
%% An extendible array can be made fixed-size later
A3 = array:fix(A2).
 
%% A fixed-size array does not grow automatically and does not
%% allow accesses beyond the last set entry
{'EXIT',{badarg,_}} = (catch array:set(18, true, A3)).
{'EXIT',{badarg,_}} = (catch array:get(18, A3)).
 

[edit] F#

Fixed-length arrays:

> Array.create 6 'A';;
val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
> Array.init 8 (fun i -> i * 10) ;;
val it : int [] = [|0; 10; 20; 30; 40; 50; 60; 70|]
> let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;;
val arr : int [] = [|0; 1; 2; 3; 4; 5; 6|]
> arr.[4];;
val it : int = 4
> arr.[4] <- 65 ;;
val it : unit = ()
> arr;;
val it : int [] = [|0; 1; 2; 3; 65; 5; 6|]

Dynamic arrays:

If dynamic arrays are needed, it is possible to use the .NET class System.Collections.Generic.List<'T> which is aliased as Microsoft.FSharp.Collections.ResizeArray<'T>:

> let arr = new ResizeArray<int>();;
val arr : ResizeArray<int>
> arr.Add(42);;
val it : unit = ()
> arr.[0];;
val it : int = 42
> arr.[0] <- 13;;
val it : unit = ()
> arr.[0];;
val it : int = 13
> arr.[1];;
> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index ...
> arr;;
val it : ResizeArray<int> = seq [13]

[edit] Factor

(cleave applies all the quotations to the initial argument (the array)) This demonstrates array litterals and writing/reading to the array

Directly in the listener :

{ 1 2 3 }
{
[ "The initial array: " write . ]
[ [ 42 1 ] dip set-nth ]
[ "Modified array: " write . ]
[ "The element we modified: " write [ 1 ] dip nth . ]
} cleave
   The initial array: { 1 2 3 }
   Modified array: { 1 42 3 }
   The element we modified: 42

Arrays of arbitrary length can be created with the <array> word :

   ( scratchpad - auto ) 10 42 <array> .
   { 42 42 42 42 42 42 42 42 42 42 }

Arrays can contain different types :

   { 1 "coucou" f [ ] }

Arrays of growable length are called Vectors.

V{ 1 2 3 }
{
[ "The initial vector: " write . ]
[ [ 42 ] dip push ]
[ "Modified vector: " write . ]
} cleave
   The initial vector: V{ 1 2 3 }
   Modified vector: V{ 1 2 3 42 }

Vectors can also be used with set-nth and nth.

   ( scratchpad - auto ) V{ } [ [ 5 5 ] dip set-nth ] [ . ] bi
   V{ 0 0 0 0 0 5 }

[edit] Forth

Forth has a variety of ways to allocate arrays of data as contiguous blocks of memory, though it has no built-in array handling words, favoring pointer arithmetic.

For example, a static array of 10 cells in the dictionary, 5 initialized and 5 uninitialized:

create MyArray 1 , 2 , 3 , 4 , 5 ,  5 cells allot
here constant MyArrayEnd
 
30 array 7 cells + !
array 7 cells + @ . \ 30
 
: .array MyArrayEnd MyArray do I @ . cell +loop ;

[edit] Fortran

Works with: Fortran version 90 and later

Basic array declaration:

integer a (10)
integer :: a (10)
integer, dimension (10) :: a

Arrays are one-based. These declarations are equivalent:

integer, dimension (10) :: a
integer, dimension (1 : 10) :: a

Other bases can be used:

integer, dimension (0 : 9) :: a

Arrays can have any type (intrinsic or user-defined), e.g.:

real, dimension (10) :: a
type (my_type), dimension (10) :: a

Multidimensional array declaration:

integer, dimension (10, 10) :: a
integer, dimension (10, 10, 10) :: a

Allocatable array declaration:

integer, dimension (:), allocatable :: a
integer, dimension (:, :), allocatable :: a

Array allocation:

allocate (a (10))
allocate (a (10, 10))

Array deallocation:

deallocate (a)

Array initialisation:

integer, dimension (10) :: a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)
integer :: i
integer, dimension (10) :: a = (/(i * i, i = 1, 10)/)
integer, dimension (10) :: a = 0
integer :: i
integer, dimension (10, 10) :: a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))

Constant array declaration:

integer :: i
integer, dimension (10), parameter :: a = (/(i * i, i = 1, 10)/)

Element assignment:

a (1) = 1
a (1, 1) = 1

Array assignment:

a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)
a = (/(i * i, i = 1, 10)/)
a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))
a = 0

Array section assignment:

a (:) = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)
a (1 : 5) = (/1, 2, 3, 4, 5/)
a (: 5) = (/1, 2, 3, 4, 5/)
a (6 :) = (/1, 2, 3, 4, 5/)
a (1 : 5) = (/(i * i, i = 1, 10)/)
a (1 : 5)= 0
a (1, :)= (/(i * i, i = 1, 10)/)
a (1 : 5, 1)= (/(i * i, i = 1, 5)/)

Element retrieval:

i = a (1)

Array section retrieval:

a = b (1 : 10)

Size retrieval:

i = size (a)

Size along a single dimension retrieval:

i = size (a, 1)

Bounds retrieval:

i_min = lbound (a)
i_max = ubound (a)

Bounds of a multidimensional array retrieval:

a = ubound (b)

[edit] Golfscript

In Golfscript, arrays are created writing their elements between []. Arrays can contain any kind of object. Once created, they are pushed on the stack, as any other object.

[1 2 3]:a; # numeric only array, assigned to a and then dropped
10,:a; # assign to a [0 1 2 3 4 5 6 7 8 9]
a 0= puts # pick element at index 0 (stack: 0)
a 10+ puts # append 10 to the end of a
10a+puts # prepend 10 to a

Append and prepend works for integers or arrays only, since only in these cases the result is coerced to an array.

[edit] Groovy

Arrays and lists are synonymous in Groovy. They can be initialized with a wide range of operations and Groovy enhancements to the Collection and List classes.

def aa = [ 1, 25, 31, -3 ]           // list
def a = [0] * 100 // list of 100 zeroes
def b = 1..9 // range notation
def c = (1..10).collect { 2.0**it } // each output element is 2**(corresponding invoking list element)
 
// There are no true "multi-dimensional" arrays in Groovy (as in most C-derived languages).
// Use lists of lists in natural ("row major") order as a stand in.
def d = (0..1).collect { i -> (1..5).collect { j -> 2**(5*i+j) as double } }
def e = [ [ 1.0, 2.0, 3.0, 4.0 ],
[ 5.0, 6.0, 7.0, 8.0 ],
[ 9.0, 10.0, 11.0, 12.0 ],
[ 13.0, 14.0, 15.0, 16.0 ] ]
 
println aa
println b
println c
println()
d.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }
println()
e.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }

Output:

[1, 25, 31, -3]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]

[    2.0     4.0     8.0    16.0    32.0 ]
[   64.0   128.0   256.0   512.0  1024.0 ]

[    1.0     2.0     3.0     4.0 ]
[    5.0     6.0     7.0     8.0 ]
[    9.0    10.0    11.0    12.0 ]
[   13.0    14.0    15.0    16.0 ]

Here is a more interesting example showing a function that creates and returns a square identity matrix of order N:

def identity = { n ->
(1..n).collect { i -> (1..n).collect { j -> i==j ? 1.0 : 0.0 } }
}

Test program:

def i2 = identity(2)
def i15 = identity(15)
 
 
i2.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }
println()
i15.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }

Output:

[ 1.0  0.0 ]
[ 0.0  1.0 ]

[ 1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0 ]
[ 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0 ]

Groovy, like every other C-derived language in the known universe, uses ZERO-based array/list indexing.

def strings = ['Mary', 'had', 'a', 'little', 'lamb', ". It's", 'fleece', 'was', 'white', 'as', 'snow']
 
println strings
 
strings[0] = 'Arthur'
strings[4] = 'towel'
strings[6] = 'stain'
strings[8] = 'ripe'
strings[10] = 'strawberries'
 
println strings

Output:

["Mary", "had", "a", "little", "lamb", ". It's", "fleece", "was", "white", "as", "snow"]
["Arthur", "had", "a", "little", "towel", ". It's", "stain", "was", "ripe", "as", "strawberries"]

Negative indices are valid. They indicate indexing from the end of the list towards the start.

println strings[-1]

Output:

strawberries

Groovy lists can be resequenced and subsequenced by providing lists or ranges of indices in place of a single index.

println strings[0, 7, 2, 3, 8]
println strings[0..4]
println strings[0..3, -5]

Output:

["Arthur", "was", "a", "little", "ripe"]
["Arthur", "had", "a", "little", "towel"]
["Arthur", "had", "a", "little", "stain"]

[edit] Haskell

You can read all about Haskell arrays here. The following example is taken from that page:

import Data.Array.IO
 
main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)
a <- readArray arr 1
writeArray arr 1 64
b <- readArray arr 1
print (a,b)

[edit] HicEst

REAL :: n = 3, Astat(n), Bdyn(1, 1)
 
Astat(2) = 2.22222222
WRITE(Messagebox, Name) Astat(2)
 
ALLOCATE(Bdyn, 2*n, 3*n)
Bdyn(n-1, n) = -123
WRITE(Row=27) Bdyn(n-1, n)
 
ALIAS(Astat, n-1, last2ofAstat, 2)
WRITE(ClipBoard) last2ofAstat ! 2.22222222 0

[edit] Icon and Unicon

[edit] Icon

record aThing(a, b, c)       # arbitrary object (record or class) for illustration
 
procedure main()
A0 := [] # empty list
A0 := list() # empty list (default size 0)
A0 := list(0) # empty list (literal size 0)
 
A1 := list(10) # 10 elements, default initializer &null
A2 := list(10, 1) # 10 elements, initialized to 1
 
# literal array construction - arbitrary dynamically typed members
A3 := [1, 2, 3, ["foo", "bar", "baz"], aThing(1, 2, 3), "the end"]
 
# left-end workers
# NOTE: get() is a synonym for pop() which allows nicely-worded use of put() and get() to implement queues
#
Q := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x := pop(A0) # x is 1
x := get(A0) # x is 2
push(Q,0)
# Q is now [0,3, 4, 5, 6, 7, 8, 9, 10]
 
# right-end workers
x := pull(Q) # x is 10
put(Q, 100) # Q is now [0, 3, 4, 5, 6, 7, 8, 9, 100]
 
# push and put return the list they are building
# they also can have multiple arguments which work like repeated calls
 
Q2 := put([],1,2,3) # Q2 is [1,2,3]
Q3 := push([],1,2,3) # Q3 is [3,2,1]
Q4 := push(put(Q2),4),0] # Q4 is [0,1,2,3,4] and so is Q2
 
# array access follows with A as the sample array
A := [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
 
# get element indexed from left
x := A[1] # x is 10
x := A[2] # x is 20
x := A[10] # x is 100
 
# get element indexed from right
x := A[-1] # x is 100
x := A[-2] # x is 90
x := A[-10] # x is 10
 
# copy array to show assignment to elements
B := copy(A)
 
# assign element indexed from left
B[1] := 11
B[2] := 21
B[10] := 101
# B is now [11, 21, 30, 50, 60, 60, 70, 80, 90, 101]
 
# assign element indexed from right - see below
B[-1] := 102
B[-2] := 92
B[-10] := 12
# B is now [12, 21, 30, 50, 60, 60, 70, 80, 92, 102]
 
# list slicing
# the unusual nature of the slice - returning 1 less element than might be expected
# in many languages - is best understood if you imagine indexes as pointing to BEFORE
# the item of interest. When a slice is made, the elements between the two points are
# collected. eg in the A[3 : 6] sample, it will get the elements between the [ ] marks
#
# sample list: 10 20 [30 40 50] 60 70 80 90 100
# positive indexes: 1 2 3 4 5 6 7 8 9 10 11
# non-positive indexes: -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
#
# I have deliberately drawn the indexes between the positions of the values.
# The nature of this indexing brings simplicity to string operations
#
# list slicing can also use non-positive indexes to access values from the right.
# The final index of 0 shown above shows how the end of the list can be nominated
# without having to know it's length
#
# NOTE: list slices are distinct lists, so assigning to the slice
# or a member of the slice does not change the values in A
#
# Another key fact to understand: once the non-positive indexes and length-offsets are
# resolved to a simple positive index, the index pair (if two are given) are swapped
# if necessary to yield the elements between the two.
#
S := A[3 : 6] # S is [30, 40, 50]
S := A[6 : 3] # S is [30, 40, 50] not illegal or erroneous
S := A[-5 : -8] # S is [30, 40, 50]
S := A[-8 : -5] # S is [30, 40, 50] also legal and meaningful
 
# list slicing with length request
S := A[3 +: 3] # S is [30, 40, 50]
S := A[6 -: 3] # S is [30, 40, 50]
S := A[-8 +: 3] # S is [30, 40, 50]
S := A[-5 -: 3] # S is [30, 40, 50]
S := A[-8 -: -3] # S is [30, 40, 50]
S := A[-5 +: -3] # S is [30, 40, 50]
end

[edit] Unicon

This Icon solution works in Unicon.

# Unicon provides a number of extensions
# insert and delete work on lists allowing changes in the middle
# possibly others
 
This example is in need of improvement:
Need code examples for these extensions

[edit] Io

foo := list("foo", "bar", "baz")
foo at(1) println // bar
foo append("Foobarbaz")
foo println
foo atPut(2, "barbaz") // baz becomes barbaz
Io> foo := list("foo", "bar", "baz")
==> list(foo, bar, baz)
Io> foo at(1) println // bar
bar
==> bar
Io> foo append("Foobarbaz")
==> list(foo, bar, baz, Foobarbaz)
Io> foo println
list(foo, bar, baz, Foobarbaz)
==> list(foo, bar, baz, Foobarbaz)
Io> foo atPut(2, "barbaz") // baz becomes barbaz
==> list(foo, bar, barbaz, Foobarbaz)
Io> 

[edit] J

In J, all data occurs in the form of rectangular (or generally orthotopic) arrays. This is true for both named and anonymous data.

   1                          NB. a stand-alone scalar value is an array without any axis
1
NB. invoking any array produces that array as the result
{. array=: 1 3, 6#0 NB. create, name, then get head item of the array: 1 3 0 0 0 0 0 0
1
0 { array NB. another way to get the head item
1
aword=: 'there' NB. a literal array
0 1 3 2 2 { aword NB. multiple items can be drawn in a single action
three
]twoD=: 3 5 $ 'abcdefghijklmnopqrstuvwxyz'
abcde
fghij
klmno
1 { twoD NB. item 1 from twoD - a list of three items
fghij
(<2 2){ twoD NB. bracket indexing is not used in J
m
'X' (0 0;1 1;2 2) } twoD NB. amend specified items
Xbcde
fXhij
klXno

Because arrays are so important in J, a large portion of the language applies to this topic.

[edit] Java

int[] array = new int[10]; //optionally, replace "new int[10]" with a braced list of ints like "{1, 2, 3}"
array[0] = 42;
System.out.println(array[3]);

Dynamic arrays can be made using Lists. Leave generics out for Java versions under 1.5:

ArrayList <Integer> list = new ArrayList <Integer>();//optionally add an initial size as an argument
list.add(5);//appends to the end of the list
list.add(1, 6);//assigns the element at index 1
System.out.println(list.get(0));

[edit] JavaScript

JavaScript arrays use the Array prototype, an Object that uses numerical indexes starting from 0 and knows its length.

var myArray = new Array();
var myArray1 = new Array(5); // gotcha: preallocated array with five empty elements, not [ 5 ].
var myArray2 = new Array("Item1","Item2");
var myArray3 = ["Item1", "Item2"]; // array literal
 
myArray[2] = 5;
var x = myArray[2] + myArray.length; // 8

[edit] Lisaac

+ a : ARRAY(INTEGER);
a := ARRAY(INTEGER).create 0 to 9;
a.put 1 to 0;
a.put 3 to 1;
a.item(1).print;

[edit] Logo

array 5      ; default origin is 1, every item is empty
(array 5 0)  ; custom origin
make "a {1 2 3 4 5}  ; array literal
setitem 1 :a "ten  ; Logo is dynamic; arrays can contain different types
print item 1 :a  ; ten

[edit] LSE64

10 myArray :array
0 array 5 [] ! # store 0 at the sixth cell in the array
array 5 [] @ # contents of sixth cell in array

[edit] Lua

Lua does not differentiate between arrays, lists, sets, dictionaries, maps, etc. It supports only one container: Table. Using Lua's simple yet powerful syntax, any of these containers can be emulated. All tables are dynamic. If a static array is necessary, that behavior can be created.

l = {}
l[1] = 1 -- Index starts with 1, not 0.
l[0] = 'zero' -- But you can use 0 if you want
l[10] = 2 -- Indexes need not be continuous
l.a = 3 -- Treated as l['a']. Any object can be used as index
l[l] = l -- Again, any object can be used as an index. Even other tables
for i,v in next,l do print (i,v) end

[edit] MATLAB

Variables are not typed until they are initialized. So, if you want to create an array you simply assign a variable name the value of an array. Also, memory is managed by MATLAB so an array can be expanded, resized, and have elements deleted without the user dealing with memory. Array elements can be retrieved in two ways. The first way is to input the row and column indicies of the desired elements. The second way is to input the subscript of the array elements.

>> a = [1 2 35] %Declaring an array
 
a =
 
1 2 35
 
>> a = [1 2 35;5 7 9] %Declaring a multidimensional array
 
a =
 
1 2 35
5 7 9
 
>> a(2,3) %Retrieving value using row and column indicies
 
ans =
 
9
 
>> a(6) %Retrieving value using array subscript
 
ans =
 
9
 
>> a = [a [10;42]] %Added a column vector to the array
 
a =
 
1 2 35 10
5 7 9 42
 
>> a(:,1) = [] %Deleting array elements
 
a =
 
2 35 10
7 9 42

[edit] Modula-3

VAR a: ARRAY [1..10] OF INTEGER;

Defines an array of 10 elements, indexed 1 through 10.

Arrays can also be given initial values:

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. *)

To retrieve an element:

VAR arr := ARRAY [1..3] OF INTEGER {1, 2, 3};
VAR myVar := a[2];

To assign a value to an element:

VAR arr := ARRAY [1..3] OF INTEGER;
arr[1] := 10;

[edit] NewLISP

This creates an array of 5 elements, initialized to nil:

(array 5)
(nil nil nil nil nil)

The example below creates a multi-dimensional array (a 3-element array of 4-element arrays), initialized using the values returned by the function sequence (a list containing whole numbers from 1 to 12) and stores the newly created array in a variable called myarray. The return value of the set function is the array.

(set 'myarray (array 3 4 (sequence 1 12)))
((1 2 3 4) (5 6 7 8) (9 10 11 12))

[edit] NSIS

Library: NSISArray

NSIS does not have native support for arrays. Array support is provided by the NSISArray plugin.

 
!include NSISArray.nsh
Function ArrayTest
Push $0
; Declaring an array
NSISArray::New TestArray 1 2
NSISArray::Push TestArray "Hello"
; NSISArray arrays are dynamic by default.
NSISArray::Push TestArray "World"
NSISArray::Read TestArray 1
Pop $0
DetailPrint $0
Pop $0
FunctionEnd
 

[edit] Objeck

 
bundle Default {
class Arithmetic {
function : Main(args : System.String[]), Nil {
array := Int->New[2];
array[0] := 13;
array[1] := 7;
(array[0] + array[1])->PrintLine();
}
}
}
 

[edit] OCaml

in the toplevel:

# Array.make 6 'A' ;;
- : char array = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
 
# Array.init 8 (fun i -> i * 10) ;;
- : int array = [|0; 10; 20; 30; 40; 50; 60; 70|]
 
# let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;;
val arr : int array = [|0; 1; 2; 3; 4; 5; 6|]
 
# arr.(4) ;;
- : int = 4
 
# arr.(4) <- 65 ;;
- : unit = ()
 
# arr ;;
- : int array = [|0; 1; 2; 3; 65; 5; 6|]

[edit] Oz

declare
Arr = {Array.new 1 %% lowest index
10 %% highest index
37} %% all 10 fields initialized to 37
in
{Show Arr.1}
Arr.1 := 64
{Show Arr.1}

[edit] Perl

Dynamic

my @arr;
 
push @arr, 1;
push @arr, 3;
 
$arr[0] = 2;
 
print $arr[0];

[edit] Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

my @arr;
 
push @arr, 1;
push @arr, 3;
 
@arr[0] = 2;
 
say @arr[0];

[edit] PHP

[edit] Writing To An Array

[edit] Single Dimension

$NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");

[edit] Multi-Dimensional

$MultiArray = array(
array(0, 0, 0, 0, 0, 0),
array(1, 1, 1, 1, 1, 1),
array(2, 2, 2, 2, 2, 2),
array(3, 3, 3, 3, 3, 3)
);

[edit] Reading From An Array

[edit] Single Dimension

Read the 5th value in the array:

echo $NumberArray[5]; // Returns 5
echo $LetterArray[5]; // Returns f

[edit] Multi-Dimensional

Read the 2nd line, column 5

echo $MultiArray[1][5]; // 2

[edit] Print a whole array

This is useful while developing to view the contents of an array:

print_r($MultiArray);

Which would give us:

Array(
0 => array(
0 => 0
1 => 0
2 => 0
3 => 0
4 => 0
5 => 0
)
1 => array(
0 => 1
1 => 1
2 => 1
3 => 1
4 => 1
5 => 1
)
2 => array(
0 => 2
1 => 2
2 => 2
3 => 2
4 => 2
5 => 2
)
3 => array(
0 => 3
1 => 3
2 => 3
3 => 3
4 => 3
5 => 3
)
)

[edit] Set custom keys for values

This example starts the indexing from 1 instead of 0

$StartIndexAtOne = array(1 => "A", "B", "C", "D");

This example shows how you can apply any key you want

$CustomKeyArray = array("d" => "A", "c" => "B", "b" =>"C", "a" =>"D");

To read the 3rd value of the second array:

echo $CustomKeyArray["b"]; // Returns C

[edit] Other Examples

Create a blank array:

$BlankArray = array();

Set a value for the next key in the array:

$BlankArray[] = "Not Blank Anymore";

Assign a value to a certain key:

$AssignArray["CertainKey"] = "Value";

[edit] PicoLisp

PicoLisp has no built-in array data type. Lists are used instead.

(setq A '((1 2 3) (a b c) ((d e) NIL 777)))  # Create a 3x3 structure
(mapc println A) # Show it

Output:

(1 2 3)
(a b c)
((d e) NIL 777)

Replace 'b' with 'B' in middle row:

(set (nth A 2 2) 'B)
(mapc println A)

Output:

(1 2 3)
(a B c)
((d e) NIL 777)

Insert '1' in front of the middle row:

(push (cdr A) 1)
(mapc println A)

Output:

(1 2 3)
(1 a B c)
((d e) NIL 777)

Append '9' to the middle row:

(queue (cdr A) 9)
(mapc println A)

Output:

(1 2 3)
(1 a B c 9)
((d e) NIL 777)

[edit] Pike

int main(){
// Initial array, few random elements.
array arr = ({3,"hi",84.2});
 
arr += ({"adding","to","the","array"}); // Lets add some elements.
 
write(arr[5] + "\n"); // And finally print element 5.
}

[edit] PL/I

 
/* Example of an array having fixed dimensions */
declare A(10) float initial (1, 9, 4, 6, 7, 2, 5, 8, 3, 10);
 
A(6) = -45;
 
/* Example of an array having dynamic bounds. */
get list (N);
 
begin;
declare B(N) float initial (9, 4, 7, 3, 8, 11, 0, 5, 15, 6);
B(3) = -11;
end;
 
/* Example of a dynamic array. */
declare C(N) float controlled;
get list (N);
allocate C;
C = 0;
c(7) = 12;
 

[edit] PostScript

 
%Declaring array
 
/x [0 1] def
 
%Assigning value to an element, PostScript arrays are 0 based.
 
x 0 3 put
 
%Print array
 
x pstack
[3 1]
 
%Get an element
 
x 1 get
 

[edit] PowerShell

Empty array:

$a = @()

Array initialized with only one member:

$a = ,2
$a = @(2) # alternative

Longer arrays can simply be created by separating the values with commas:

$a = 1,2,3

A value can be appended to an array using the += operator:

$a += 5

Since arrays are immutable this simply creates a new array containing one more member.

Values can be retrieved using a fairly standard indexing syntax:

$a[1]

Similarly, those values can also be replaced:

$a[1] = 42

The range operator .. can be used to create contiguous ranges of integers as arrays:

$r = 1..100

Indexing for retrieval allows for arrays as well, the following shows a fairly complex example combining two ranges and an arbitrary array in the indexer:

$r[0..9+25..27+80,85,90]

Indexing from the end of the array can be done with negative numbers:

$r[-1]  # last index

[edit] Prolog

Works with: SWI Prolog

Prolog Terms can be abused as array structure. Using functor/3 to create arrays and arg/3 to nondestructively retrieve and set elements.

 
singleassignment:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
% index of arguments start at 1
arg(1 ,Array,a), % put an a at position 1
arg(12,Array,b), % put an b at position 12
arg(1 ,Array,Value1), % get the value at position 1
print(Value1),nl, % will print Value1 and therefore a followed by a newline
arg(4 ,Array,Value2), % get the value at position 4 which is a free Variable
print(Value2),nl. % will print that it is a free Variable followed by a newline
 

To destructively set an array element, which is the "normal" way to set an element in most other programming languages, setarg/3 can be used.

 
destructive:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
% index of arguments start at 1
setarg(1 ,Array,a), % put an a at position 1
setarg(12,Array,b), % put an b at position 12
setarg(1, Array,c), % overwrite value at position 1 with c
arg(1 ,Array,Value1), % get the value at position 1
print(Value1),nl. % will print Value1 and therefore c followed by a newline
 

Lists can be used as arrays.

 
listvariant:-
length(List,100), % create a list of length 100
nth1(1 ,List,a), % put an a at position 1 , nth1/3 uses indexing from 1, nth0/3 from 0
nth1(12,List,b), % put an b at position 3
append(List,[d],List2), % append an d at the end , List2 has 101 elements
length(Add,10), % create a new list of length 10
append(List2,Add,List3), % append 10 free variables to List2 , List3 now has 111 elements
nth1(1 ,List3,Value), % get the value at position 1
print(Value),nl. % will print out a
 

[edit] PureBasic

Dim is used to create new arrays and initiate each element will be zero. An array in PureBasic can be of any types, including structured, and user defined types. Once an array is defined it can be resized with ReDim. Arrays are dynamically allocated which means than a variable or an expression can be used to size them.

  ;Set up an Array of 23 cells, e.g. 0-22
Dim MyArray.i(22)
MyArray(0) = 7
MyArray(1) = 11
MyArray(7) = 23

ReDim is used to 'resize' an already declared array while preserving its content. The new size can be both larger or smaller, but the number of dimension of the array can not be changed after initial creation.

  ;Extend the Array above to 56 items without affecting the already stored data
ReDim MyArray(55)
MyArray(22) = 7
MyArray(33) = 11
MyArray(44) = 23
  ;Find all 6 non-zero cells from the Array above
For i=0 To ArraySize(MyArray())
If MyArray(i)
PrintN(Str(i)+" differs from zero.")
EndIf
Next
  ; Now, set up a multi dimensional Array 
Dim MultiArray.i(800, 600)
MultiArray(100, 200) = 640
MultiArray(130, 40) = 120
Dim MultiArray2.i(64, 128, 32)
PrintN( Str(ArraySize(MultiArray2(), 2)) ; Will tell that second dimension size is '128'

[edit] Python

Python lists are dynamically resizeable.

array = []
 
array.append(1)
array.append(3)
 
array[0] = 2
 
print array[0]

A simple, single-dimensional array can also be initialized thus:

myArray = [0] * size

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

myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!

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:

myArray = [[0 for x in range(width)] for y in range(height)]

That is equivalent to:

myArray = list()
for x in range(height):
myArray.append([0] * width)

[edit] R

Dynamic

arr <- array(1)
 
arr <- append(arr,3)
 
arr[1] <- 2
 
print(arr[1])

[edit] REBOL

 
a: [] ; Empty.
b: ["foo"] ; Pre-initialized.
 

Inserting and appending.

 
append a ["up" "down"] ; -> ["up" "down"]
insert a [left right] ; -> [left right "up" "down"]
 

Getting specific values.

 
first a ; -> left
third a ; -> "up"
last a ; -> "down"
a/2 ; -> right (Note: REBOL is 1-based.)
 

Getting subsequences. REBOL allows relative motion through a block (list). The list variable returns the current position to the end of the list, you can even assign to it without destroying the list.

 
a ; -> [left right "up" "down"]
next a ; -> [right "up" "down"]
skip a 2 ; -> ["up" "down"]
 
a: next a ; -> [right "up" "down"]
head a ; -> [left right "up" "down"]
 
copy a ; -> [left right "up" "down"]
copy/part a 2 ; -> [left right]
copy/part skip a 2 2 ; -> ["up" "down"]
 

[edit] RLaB

 
// 1-D (row- or column-vectors)
// Static:
// row-vector
x = [1:3];
x = zeros(1,3); x[1]=1; x[2]=2; x[3]=3;
// column-vector
x = [1:3]'; // or
x = [1;2;3]; // or
x = zeros(3,1); x[1]=1; x[2]=2; x[3]=3;
// Dynamic:
x = []; // create an empty array
x = [x; 1, 2]; // add a row to 'x' containing [1, 2], or
x = [x, [1; 2]]; // add a column to 'x' containing [1; 2]
 
// 2-D array
// Static:
x = zeros(3,5); // create an zero-filed matrix of size 3x5
x[1;1] = 1; // set the x(1,1) element to 1
x[2;] = [1,2,3,4,5]; // set the second row x(2,) to a row vector
x[3;4:5] = [2,3]; // set x(3,4) to 2 and x(3,5) to 3
// Dynamic
x = [1:5]; // create an row-vector x(1,1)=1, x(1,2)=2, ... x(1,5)=5
x = [x; 2, 3, 4, 6, 7]; // add to 'x' a row.
 
// Accessing an element of arrays:
// to retrieve/print element of matrix 'x' just put this in a single line in the script
i=1;
j=2;
x[i;j]
 
 
 

[edit] Ruby

Dynamic

# create an array with one object in it
a = ['foo']
 
# the Array#new method allows several additional ways to create arrays
 
# push objects into the array
a << 1 # ["foo", 1]
a.push(3,4,5) # ["foo", 1, 3, 4, 5]
 
# set the value at a specific index in the array
a[0] = 2 # [2, 1, 3, 4, 5]
 
# a couple of ways to set a slice of the array
a[0,3] = 'bar' # ["bar", 4, 5]
a[1..-1] = 'baz' # ["bar", "baz"]
a[0] = nil # [nil, "baz"]
a[0,1] = nil # ["baz"]
 
# retrieve an element
puts a[0]

[edit] Sather

-- a is an array of INTs
a :ARRAY{INT};
-- create an array of five "void" elements
a := #ARRAY{INT}(5);
-- static creation of an array with three elements
b :ARRAY{FLT} := |1.2, 1.3, 1.4|;
-- accessing an array element
c ::= b[0]; -- syntactic sugar for b.aget(0)
-- set an array element
b[1] := c; -- syntactic sugar for b.aset(1, c)
-- append another array
b := b.append(|5.5|);

[edit] Scala

val array = new Array[Int](10) //optionally, replace "new Array[Int](10)" with an initializing form such as "Array(1, 2, 3, 4)"
array(0) = 42
println(array(3))

Dynamic arrays can be made using ArrayBuffers:

val arraybuffer = new scala.collection.mutable.ArrayBuffer[Int] 
arraybuffer += 5 //appends to the end of the list
arraybuffer.update(0, 6);//assigns the element at index 0
println(arraybuffer)

[edit] JavaScript

JavaScript arrays use the Array prototype, an Object that uses numerical indexes starting from 0 and knows its length.

var myArray = new Array();
var myArray1 = new Array(5); // gotcha: preallocated array with five empty elements, not [ 5 ].
var myArray2 = new Array("Item1","Item2");
var myArray3 = ["Item1", "Item2"]; // array literal
 
myArray[2] = 5;
var x = myArray[2] + myArray.length; // 8


[edit] Scheme

Lists are more often used in Scheme than vectors.

(let ((array #(1 2 3 4 5))     ; vector literal
(array2 (make-vector 5)) ; default nil
(array3 (make-vector 5 0))) ; default 0
(vector-set! array 0 3)
(vector-ref array 0)) ; 3

[edit] Slate

slate[1]> define: #x -> #(1 2 3). 
{1. 2. 3}
slate[2]> x
{1. 2. 3}
slate[3]> define: #y -> {1 + 2. 3 + 4. 5}.
{3. 7. 5}
slate[4]> y at: 2 put: 99.
99
slate[5]> y
{3. 7. 99}
slate[6]> x first
1
slate[7]> x at: 0.
1

[edit] Suneido

array = Object('zero', 'one', 'two')
array.Add('three')
array.Add('five', at: 5)
array[4] = 'four'
Print(array[3]) --> 'three'

[edit] Tcl

Tcl's lists are really dynamic array values behind the scenes. (Note that Tcl uses the term “array” to refer to an associative collection of variables.)

set ary {}
 
lappend ary 1
lappend ary 3
 
lset ary 0 2
 
puts [lindex $ary 0]

Note also that serialization is automatic on treating as a string:

puts $ary; # Print the whole array

[edit] UNIX Shell

Bash ("sh" or "bash" on most Unix systems) supports one-dimensional arrays, which are zero-indexed. Zero-indexing means that if the array has five items in it, the first item is at index 0, and the last item is at index 4.

Two-dimensional arrays can be accomplished using shell functions applied to arrays of array names. Basically, hiding the indirection within the shell function invocation.

You can read detailed explanations on everything concerning arrays in Bash.

To create an array:

alist=( item1 item2 item3 )  # creates a 3 item array called "alist"
declare -a list2 # declare an empty list called "list2"
declare -a list3[0] # empty list called "list3"; the subscript is ignored
 
# create a 4 item list, with a specific order
list5=([3]=apple [2]=cherry [1]=banana [0]=strawberry)

To obtain the number of items in an array:

count=${#alist[*]}
echo "The number of items in alist is ${#alist[*]}"

To iterate up over the items in the array:

x=0
while [[ $x < ${#alist[*]} ]]; do
echo "Item $x = ${alist[$x]}"
 : $((x++))
done

To iterate down over theitems in an array:

x=${#alist[*]}       # start with the number of items in the array
while [[ $x > 0 ]]; do # while there are items left
 : $((x--)) # decrement first, because indexing is zero-based
echo "Item $x = ${alist[$x]}" # show the current item
done

To append to an array, use the current number of items in the array as the next index:

alist[${#alist[*]}]=new_item

To make appending easier, use a little shell function, let's call it "push", and design it to allow appending multiple values, while also preserving quoted values:

# shell function to append values to an array
# push LIST VALUES ...
push() {
local var=${1:?'Missing variable name!'}
shift
eval "\$$var=( \"\${$var[@]}\" \"$@\" )"
}
 
push alist "one thing to add"
push alist many words to add

To delete a single array item, the first item:

unset alist[0]

To delete and return the last item in an array (e.g., "pop" function):

# pop ARRAY -- pop the last item on ARRAY and output it
 
pop() {
local var=${1:?'Missing array name'}
local x ; eval "x=\${#$var[*]}"
if [[ $x > 0 ]]; then
local val ; eval "val=\"\${$var[$((--x))]}\""
unset $var[$x]
else
echo 1>&2 "No items in $var" ; exit 1
fi
echo "$val"
}
 
alist=(a b c)
pop alist
a
pop alist
b
pop alist
c
pop alist
No items in alist

To delete all the items in an array:

unset alist[*]

To delete the array itself (and all items in it, of course):

unset alist
Personal tools
Support