Arrays: Difference between revisions

173,366 bytes added ,  1 month ago
m
(→‎{{header|Perl}}: Migrating from http://rosettacode.org/wiki/Creating_an_Array)
(218 intermediate revisions by 99 users not shown)
Line 1:
{{task|Basic language learning}} [[Category:Simple]]
{{task|Basic language learning}}
 
This task is about arrays.
Line 27:
*   [[Two-dimensional array (runtime)]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">[Int] array
array.append(1)
array.append(3)
array[0] = 2
print(array[0]) // retrieve first element in an array
print(array.last) // retrieve last element in an array
print(array.pop()) // pop last item in an array
print(array.pop(0)) // pop first item in an array
 
V size = 10
V myArray = [0] * size // create single-dimensional array
V width = 3
V height = 4
V myArray2 = [[0] * width] * height // create array of arrays</syntaxhighlight>
 
{{out}}
<pre>
2
3
3
2
</pre>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Arrays 04/09/2015
ARRAYS PROLOG
* we use TA array with 1 as origin. So TA(1) to TA(20)
Line 58 ⟶ 84:
J DC F'4'
YREGS
END ARRAYS</langsyntaxhighlight>
=={{header|6502 Assembly}}==
 
===One-Dimensional Arrays===
An array is little more than just a contiguous section of memory. Whether or not an array is mutable depends solely on whether it is defined in ROM or RAM. The syntax will be discussed in further detail in the Two-Dimensional Arrays section.
 
<syntaxhighlight lang="6502asm">Array:
db 5,10,15,20,25,30,35,40,45,50</syntaxhighlight>
 
 
Side note: Some systems, such as the Nintendo Entertainment System or other ROM cartridge-based computers, cannot use the above declaration to initialize an array in RAM at assemble time; only in ROM. While the label "Array" can be given to an arbitrary RAM location on any system, you won't be able to define a data block in RAM the same way you would on an assembly program meant to run on the Apple II or Commodore 64 for example. The examples below will still work on any system, you just won't be able to "see" the array before running the program, if that makes sense. Clearing the system ram will suffice to initialize the array to zero.
 
Looking up a value in an array is fairly straightforward. The best addressing modes for doing so are <code>LDA $????,x</code>,<code>LDA $????,y</code>, and <code>LDA ($??),y</code>. In this case, x or y represents the index into the array. To put it in terms of C:
 
<syntaxhighlight lang="c"> char foo()
{
char array[5] = {3,6,9,12,15};
return array[2];
}</syntaxhighlight>
 
would (theoretically) compile to the following in 6502 Assembly:
<syntaxhighlight lang="6502asm">
foo:
LDX #2 ;load the desired index
LDA array,x ;load the second (zero-indexed) entry in array, i.e. 9
RTS ;return. The return value is stored in A.
 
array: ;this is the array we're reading from.
db 3,6,9,12,15</syntaxhighlight>
===Arrays in the Zero Page - A Word of Warning===
One important thing to note is a hardware bug involving <code>LDA $??,x</code>. If the sum of $?? and x would exceed 255, instead of continuing past $100, the CPU will actually wrap around back to $00. This does not happen with absolute addressing modes or indexed indirect with Y. Here's an example:
 
<syntaxhighlight lang="6502asm">LDX #$80
LDA $80,x ;evaluates to LDA $00
LDA $0480,x ;evaluates to LDA $0500</syntaxhighlight>
 
If you really want to read from an array in the zero page like this (and chances are you won't since that array also starts to overlap with the hardware stack), you can use an absolute addressing mode in the zero page. Beware - some assemblers will forcibly optimize <code>LDA $00??</code> into <code>LDA $??</code> so you may have to inline the bytecode for it directly. If you stick to arrays outsize the zero page you don't need to worry about index wraparound.
 
===Arrays of 16-Bit Data===
You can have arrays of 16-bit data as well as 8-bit ones. There are a few ways to do this, and we'll go over the "naive" way first:
<syntaxhighlight lang="6502">wordArray:
dw $ABCD,$BEEF,$CAFE,$DADA</syntaxhighlight>
 
The 6502 is little-endian, so the above would be exactly the same as the following:
<syntaxhighlight lang="6502">wordArray:
db $CD,$AB,$EF,$BE,$FE,$CA,$DA,$DA</syntaxhighlight>
 
To properly index a 16-bit array that's formatted as in the above example, you'll need to double your index. In this example, we'll be loading the offset of <code>$BEEF</code>:
<syntaxhighlight lang="6502">LDX #2 ;load the 1st (zero-indexed) WORD from the array (which is why this is 2 not 1)
LDA wordArray,X ;evaluates to LDA #$EF
STA $00 ;store in a zero page temporary variable
INX ;point X to the high byte
LDA wordArray,X ;evaluates to LDA #$BE
STA $01 ;store in a different zero page temporary variable. If your word data is a pointer you want to dereference,
;you'll need to store the low byte in $nn and the high byte in $nn+1 like I did here.</syntaxhighlight>
 
There are a few downsides in 6502 assembly to storing word data in this format. A minor one is the need to double your index. This isn't a big deal, it doesn't take long to do that. The bigger problem is that the 6502 has a soft array length cap of 256 bytes. If your code is running in ROM and you're not able to use self-modifying code to adjust the base address, or you're not willing to use the slower <code>LDA ($??),y</code>, you're mostly limited to 256 bytes or 128 words.
 
However, if you split the word table into two byte tables, you can actually get more bang for your buck, and it takes the same amount of memory no matter which way you store the data.
<syntaxhighlight lang="6502asm">wordArray_Lo:
db $CD,$EF,$FE,$DA
 
wordArray_Hi:
db $AB,$BE,$CA,$DA ;both this version and the above versions are 8 bytes of memory.</syntaxhighlight>
 
If both wordArray_Lo and wordArray_Hi were 256 bytes each, you'd be able to index both of them no problem, where you wouldn't be able to do that if it were one array. Let's try loading <code>$BEEF</code> again:
 
<syntaxhighlight lang="6502">LDX #1 ;with split arrays we DON'T need to double our index.
LDA wordArray_Lo,x ;evaluates to LDA #$EF
STA $00
LDA wordArray_Hi,x ;evaluates to LDA #$BE
STA $01</syntaxhighlight>
 
Both tables share the same index, which means you can do the lookup without destroying your index (not that it was that difficult to retrieve the original index to begin with), but on 8-bit computers you want to be as efficient as possible, using the hardware's strengths to your advantage. Splitting your "wider" arrays into multiple 8-bit tables is often the best approach.
 
===Two-Dimensional Arrays===
I'll let you in on a little secret: two-dimensional arrays don't exist. This is just as true for modern computers as it is the 6502.
In the first section I had this example of an array:
<syntaxhighlight lang="6502asm">Array:
db 5,10,15,20,25,30,35,40,45,50</syntaxhighlight>
 
In the eyes of the CPU, this is the same as ANY of the following:
<syntaxhighlight lang="6502asm">Array:
db 5
db 10
db 15
db 20
db 25
db 30
db 35
db 40
db 45
db 50</syntaxhighlight>
 
<syntaxhighlight lang="6502asm">Array:
db 5,10
db 15,20
db 25,30
db 35,40
db 45,50</syntaxhighlight>
 
or any other way to write it you can imagine. All that matters is the order of the bytes in the array - as long as that is the same you can write it however you want. It's best to write it in the way it's meant to be interpreted, however. But in order to explain that to the computer you'll need a little bit of finesse. Let's pretend that the "correct" interpretation is this 5 by 2 array:
 
<syntaxhighlight lang="6502asm">Array:
db 5,10
db 15,20
db 25,30
db 35,40
db 45,50</syntaxhighlight>
 
For this example, we want row 3 and column 1 (zero-indexed for both) which means we want to load 40.
<syntaxhighlight lang="6502">
LDA #3 ;desired row
ASL A ;Times 2 bytes per row (if the array's row size wasn't a multiple of 2 we'd need to actually do multiplication)
;which the 6502 doesn't have in hardware but can be simulated by repeated adding.
CLC
ADC #1 ;desired column (since it's 1 byte per column, we can skip the part where we multiply desired column by bytes per column)
TAX ;move A to X so we can use it as the index
 
LDA Array,x ;evaluates to LDA #40</syntaxhighlight>
 
You may be wondering, why not just treat the array as though it were one-dimensional? Reason is, you won't always know in advance what you want from your array, it may depend on 2 variables in your program (such as X/Y coordinates, etc.), so you might need to use this method rather than just treating it as linear data.
 
 
=={{header|68000 Assembly}}==
Creating an array is as simple as declaring its base address. Note that all bounds checking must be done by the programmer and is not built in by default. You also will need to have some sort of knowledge about what is stored nearby, so that you don't clobber it.
 
<syntaxhighlight lang="68000devpac">MOVE.L #$00100000,A0 ;define an array at memory address $100000</syntaxhighlight>
 
Defining an array in ROM (or RAM if you're making a program that is loaded from disk) is very simple:
<syntaxhighlight lang="68000devpac">;8-bit data
MyArray:
DC.B 1,2,3,4,5
DC.B 6,7,8,9,10
DC.B 11,12,13,14,15
EVEN ;needed to ensure proper alignment after a byte array with an odd number of entries.
 
;16-bit data
MyArrayW:
DC.W 1,2,3,4,5
DC.W 6,7,8,9,10
DC.W 11,12,13,14,15
 
;32-bit data
MyArrayL:
DC.L 1,2,3,4,5
DC.L 6,7,8,9,10
DC.L 11,12,13,14,15
</syntaxhighlight>
 
Strings are also arrays and most assemblers accept single or double quotes. The following are equivalent:
<syntaxhighlight lang="68000devpac">MyString:
DC.B "Hello World",0
even
 
MyString2:
DC.B 'H','e','l','l','o',' ','W','o','r','l','d',0
even</syntaxhighlight>
 
The assembler will automatically substitute each letter with its ASCII equivalent. Notice the lack of quotes around the null terminator 0. If it had quotes, it would be assembled as 0x30 instead of 0. Not good if your printing routine expects a 0 as the terminator byte.
 
The above declarations are useful as compile-time constants or mutable pre-loaded values. Whether an array is mutable or not depends solely on whether it is stored in ROM or RAM.
 
<i>Side note: Some systems, such as the Sega Genesis or other ROM cartridge-based computers, cannot use the above declaration to initialize an array in RAM at assemble time; only in ROM. While an array can be declared at any arbitrary RAM location on any system, you won't be able to define a data block in RAM the same way you would on an assembly program meant to run on the Macintosh or Commodore Amiga for example. The examples below will still work on any system, you just won't be able to "see" the array before running the program, if that makes sense. A simple alternative can be to define the array in ROM then copy it to RAM and work with it there.</i>
 
 
 
The data type associated with the elements of an array is determined by the move operation used to assign elements to an array. The language does not prohibit you from storing 8-bit data into an array intended for 32-bit values.
 
The base address can be offset by the value in a data register, to allow for assigning values to an array. The offset is always measured in bytes, so if your array is intended to contain a larger data size you will need to adjust it accordingly.
 
<syntaxhighlight lang="68000devpac">myArray equ $240000
 
LEA myArray,A0 ;load the base address of the array into A0
MOVE.W #3,D0 ;load the desired offset into D0
LSL.W #2,D0 ;this array is intended for 32-bit values.
MOVE.L #23,D1 ;load decimal 23 into D1
MOVE.L D1,(A0,D0) ;store #23 into the 3rd slot of the array (arrays are zero-indexed in assembly)</syntaxhighlight>
 
This is the equivalent of the [[C]] code:
<syntaxhighlight lang="c">int myArray[];
myArray[3] = 23;</syntaxhighlight>
 
Loading an element is very similar to storing it.
 
<syntaxhighlight lang="68000devpac">myArray equ $240000
 
;load element 4
LEA myArray,A0 ;load the base address of the array into A0
MOVE.W #4,D0 ;load the desired offset into D0
LSL.W #2,D0 ;this array is intended for 32-bit values.
MOVE.L (A0,D0),D1 ;load the 4th element into D1.</syntaxhighlight>
 
 
Inserting an element at a desired position is a bit more tricky. First of all, an array has no "end" in hardware. So how do you know where to stop? For this example, assume this array is currently contains 6 total elements (0,1,2,3,4,5) and we want to extend it.
 
<syntaxhighlight lang="68000devpac">myArray equ $240000
 
;insert a new element into the 2nd slot and push everything behind it back.
 
LEA myArray,A0 ;load the base address of the array into A0
MOVE.W #2,D0 ;offset into 2nd slot
LSL.W #2,D0 ;this array is intended for 32-bit values.
MOVE.L #46,D1 ;this is our new element.
 
 
 
MOVE.L (A0,D0),(4,A0,D0) ;store the 2nd element into the 3rd slot
ADDA.L #4,A0 ;increment to next slot.
MOVE.L (A0,D0),(4,A0,D0) ;store the 3nd element into the 4th slot
ADDA.L #4,A0 ;increment to next slot.
MOVE.L (A0,D0),(4,A0,D0) ;store the 4th element into the 5th slot
ADDA.L #4,A0 ;increment to next slot.
MOVE.L (A0,D0),(4,A0,D0) ;store the 5th element into the 6th slot
 
LEA myArray,A0 ;restore the base address
MOVE.L D1,(A0,D0) ;store the new 2nd element over the 2nd slot.
 
;for a larger array we can use the following loop:
MOVE.W #3,D2 ;array length minus starting offset minus 1
 
LOOP:
MOVE.L (A0,D0),(4,A0,D0)
ADDA.L #4,A0
DBRA D2,LOOP</syntaxhighlight>
 
The use of the number 4 in <code>(4,A0,D0)</code> and <code>ADDA.L #4,A0</code> was because we were working with <code>MOVE.L</code> commands to store 32-bit values. If your data size was 16 bit you would replace the 4s with 2s, and if it was 8 bit you would use 1s.
 
=={{header|8051 Assembly}}==
Line 66 ⟶ 318:
<li>In external RAM - element retrieval/altering is most efficiently done sequentially, necessary for large arrays or peripherals</ul>
Dynamic (resizable) arrays are possible to implement, but are error-prone since bounds checking must be done by the programmer.
<langsyntaxhighlight lang="asm">; constant array (elements are unchangeable) - the array is stored in the CODE segment
myarray db 'Array' ; db = define bytes - initializes 5 bytes with values 41, 72, 72, etc. (the ascii characters A,r,r,a,y)
myarray2 dw 'A','r','r','a','y' ; dw = define words - initializes 5 words (1 word = 2 bytes) with values 41 00 , 72 00, 72 00, etc.
Line 157 ⟶ 409:
pop dph
 
</syntaxhighlight>
</lang>
 
=={{header|8th}}==
 
Arrays are declared using JSON syntax, and are dynamic (but not sparse)
<langsyntaxhighlight lang="forth">
[ 1 , 2 ,3 ] \ an array holding three numbers
1 a:@ \ this will be '2', the element at index 1
Line 177 ⟶ 429:
\ arrays don't have to be homogenous:
[1,"one", 2, "two"]
</syntaxhighlight>
</lang>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program areaString64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStringsch: .ascii "The string is at item : @ \n"
szCarriageReturn: .asciz "\n"
szMessStringNfound: .asciz "The string is not found in this area.\n"
/* areas strings */
szString1: .asciz "Apples"
szString2: .asciz "Oranges"
szString3: .asciz "Pommes"
szString4: .asciz "Raisins"
szString5: .asciz "Abricots"
/* pointer items area 1*/
tablesPoi1:
pt1_1: .quad szString1
pt1_2: .quad szString2
pt1_3: .quad szString3
pt1_4: .quad szString4
ptVoid_1: .quad 0
ptVoid_2: .quad 0
ptVoid_3: .quad 0
ptVoid_4: .quad 0
ptVoid_5: .quad 0
szStringSch: .asciz "Raisins"
szStringSch1: .asciz "Ananas"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
sZoneConv: .skip 30
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
// add string 5 to area
ldr x1,qAdrtablesPoi1 // begin pointer area 1
mov x0,0 // counter
1: // search first void pointer
ldr x2,[x1,x0,lsl 3] // read string pointer address item x0 (4 bytes by pointer)
cmp x2,0 // is null ?
cinc x0,x0,ne // no increment counter
bne 1b // and loop
// store pointer string 5 in area at position x0
ldr x2,qAdrszString5 // address string 5
str x2,[x1,x0,lsl 3] // store address
// display string at item 3
mov x2,2 // pointers begin in position 0
ldr x1,qAdrtablesPoi1 // begin pointer area 1
ldr x0,[x1,x2,lsl 3]
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
 
// search string in area
ldr x1,qAdrszStringSch
//ldr x1,qAdrszStringSch1 // uncomment for other search : not found !!
ldr x2,qAdrtablesPoi1 // begin pointer area 1
mov x3,0
2: // search
ldr x0,[x2,x3,lsl 3] // read string pointer address item x0 (4 bytes by pointer)
cbz x0,3f // is null ? end search
bl comparString
cmp x0,0 // string = ?
cinc x3,x3,ne // no increment counter
bne 2b // and loop
mov x0,x3 // position item string
ldr x1,qAdrsZoneConv // conversion decimal
bl conversion10S
ldr x0,qAdrszMessStringsch
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess
b 100f
3: // end search string not found
ldr x0,qAdrszMessStringNfound
bl affichageMess
100: // standard end of the program
mov x0, 0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrtablesPoi1: .quad tablesPoi1
qAdrszMessStringsch: .quad szMessStringsch
qAdrszString5: .quad szString5
qAdrszStringSch: .quad szStringSch
qAdrszStringSch1: .quad szStringSch1
qAdrsZoneConv: .quad sZoneConv
qAdrszMessStringNfound: .quad szMessStringNfound
qAdrszCarriageReturn: .quad szCarriageReturn
/************************************/
/* Strings comparaison */
/************************************/
/* x0 et x1 contains strings addresses */
/* x0 return 0 if equal */
/* return -1 if string x0 < string x1 */
/* return 1 if string x0 > string x1 */
comparString:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,#0 // indice
1:
ldrb w3,[x0,x2] // one byte string 1
ldrb w4,[x1,x2] // one byte string 2
cmp w3,w4
blt 2f // less
bgt 3f // greather
cmp w3,#0 // 0 final
beq 4f // equal and end
add x2,x2,#1 //
b 1b // else loop
2:
mov x0,#-1 // less
b 100f
3:
mov x0,#1 // greather
b 100f
4:
mov x0,#0 // equal
b 100f
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
 
=={{header|ABAP}}==
There are no real arrays in ABAP but a construct called internal tables.
<syntaxhighlight lang="abap">
<lang ABAP>
TYPES: tty_int TYPE STANDARD TABLE OF i
WITH NON-UNIQUE DEFAULT KEY.
Line 195 ⟶ 597:
cl_demo_output=>display( itab ).
cl_demo_output=>display( itab[ 2 ] ).
</syntaxhighlight>
</lang>
 
{{out}}
Line 208 ⟶ 610:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">;; Create an array and store it in array-example
(assign array-example
(compress1 'array-example
Line 222 ⟶ 624:
 
;; Get a[5]
(aref1 'array-example (@ array-example) 5)</langsyntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
BYTE i
 
;array storing 4 INT items with initialized values
;negative values must be written as 16-bit unsigned numbers
INT ARRAY a=[3 5 71 65535]
 
;array storing 4 CARD items whithout initialization of values
CARD ARRAY b(3)
 
;array of BYTE items without allocation,
;it may be used as an pointer for another array
BYTE ARRAY c
 
;array of 1+7 CHAR items or a string
;the first item stores length of the string
CHAR ARRAY s="abcde"
 
PrintE("Array with initialized values:")
FOR i=0 TO 3
DO
PrintF("a(%I)=%I ",i,a(i))
OD
PutE() PutE()
PrintE("Array before initialization of items:")
FOR i=0 TO 3
DO
PrintF("b(%I)=%B ",i,b(i))
OD
PutE() PutE()
 
FOR i=0 TO 3
DO
b(i)=100+i
OD
PrintE("After initialization:")
FOR i=0 TO 3
DO
PrintF("b(%I)=%B ",i,b(i))
OD
PutE() PutE()
 
PrintE("Array of chars. The first item stores the length of string:")
FOR i=0 TO s(0)
DO
PrintF("s(%B)='%C ",i,s(i))
OD
PutE() PutE()
 
PrintE("As the string:")
PrintF("s=""%S""%E%E",s)
 
c=s
PrintE("Unallocated array as a pointer to another array. In this case c=s:")
FOR i=0 TO s(0)
DO
PrintF("c(%B)=%B ",i,c(i))
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arrays.png Screenshot from Atari 8-bit computer]
<pre>
Array with initialized values:
a(0)=3 a(1)=5 a(2)=71 a(3)=-1
 
Array before initialization of items:
b(0)=0 b(1)=0 b(2)=0 b(3)=0
 
After initialization:
b(0)=100 b(1)=101 b(2)=102 b(3)=103
 
Array of chars. The first item stores the length of string:
s(0)='┐ s(1)='a s(2)='b s(3)='c s(4)='d s(5)='e
 
As the string:
s="abcde"
 
Unallocated array as a pointer to another array. In this case c=s:
c(0)=5 c(1)=97 c(2)=98 c(3)=99 c(4)=100 c(5)=101
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">//creates an array of length 10
var array1:Array = new Array(10);
//creates an array with the values 1, 2
Line 240 ⟶ 725:
array2.push(4);
//get and remove the last element of an array
trace(array2.pop());</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">procedure Array_Test is
 
A,type BExample_Array_Type :is array (1..20) of Integer;
A, B : Example_Array_Type;
 
-- Ada array indices may begin at any value, not just 0 or 1
C : array (-37..20) of integerInteger;
 
-- Ada arrays may be indexed by enumerated types, which are
Line 270 ⟶ 757:
Centered : Arr (-50..50) := (0 => 1, Others => 0);
 
Result : Integer;
begin
 
A := (others => 0); -- Assign whole array
B := (1 => 1, 2 => 1, 3 => 2, others => 0);
-- Assign whole array, different values
A (1) := -1; -- Assign individual element
Line 280 ⟶ 767:
A (3..5) := (2, 4, -1); -- Assign a constant slice
A (3..5) := A (4..6); -- It is OK to overlap slices when assigned
Fingers_Extended'First := False; -- Set first element of array
Fingers_Extended'Last := False; -- Set last element of array
 
Fingers_Extended(Fingers'First) := False; -- Set first element of array
end Array_Test;</lang>
Fingers_Extended(Fingers'Last) := False; -- Set last element of array
 
end Array_Test;</syntaxhighlight>
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.
 
=={{header|Aikido}}==
Aikido arrays (or vectors) are dynamic and not fixed in size. They can hold a set of any defined value.
<langsyntaxhighlight lang="aikido">
var arr1 = [1,2,3,4] // initialize with array literal
var arr2 = new [10] // empty array of 10 elements (each element has value none)
Line 306 ⟶ 793:
var arr7 = arr1 & arr2 // intersection
 
</syntaxhighlight>
</lang>
 
# retrieve an element
puts a[0]
 
=={{header|Aime}}==
The aime ''list'' is a heterogeneous, dynamic sequence. No special creation procedure, only declaration is needed:
<syntaxhighlight lang ="aime">list l;</langsyntaxhighlight>
Values (numbers, strings, collections, functions, etc) can be added in a type generic fashion:
<langsyntaxhighlight lang="aime">l_append(l, 3);
l_append(l, "arrays");
l_append(l, pow);</langsyntaxhighlight>
The insertion position can be specified:
<langsyntaxhighlight lang="aime">l_push(l, 3, .5);
l_push(l, 4, __type(l));</langsyntaxhighlight>
More aptly, values (of selected types) can be inserted in a type specific fashion:
<langsyntaxhighlight lang="aime">l_p_integer(l, 5, -1024);
l_p_real(l, 6, 88);</langsyntaxhighlight>
Similarly, values can be retrieved in a type generic fashion:
<syntaxhighlight lang ="aime">l_query(l, 5);</langsyntaxhighlight>
or is type specific fashion:
<langsyntaxhighlight lang="aime">l_q_real(l, 6);
l_q_text(l, 1);</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
{{trans|Simula}}
<syntaxhighlight lang="algol60">begin
comment arrays - Algol 60;
 
procedure static;
begin
integer array x[0:4];
x[0]:=10;
x[1]:=11;
x[2]:=12;
x[3]:=13;
x[4]:=x[0];
outstring(1,"static at 4: ");
outinteger(1,x[4]);
outstring(1,"\n")
end static;
 
procedure dynamic(n); value n; integer n;
begin
integer array x[0:n-1];
x[0]:=10;
x[1]:=11;
x[2]:=12;
x[3]:=13;
x[4]:=x[0];
outstring(1,"dynamic at 4: ");
outinteger(1,x[4]);
outstring(1,"\n")
end dynamic;
 
static;
dynamic(5)
 
end arrays </syntaxhighlight>
{{out}}
<pre>
static at 4: 10
dynamic at 4: 10
</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">PROC array_test = VOID:
(
[1:20]INT a;
Line 347 ⟶ 878:
FLEX []CHAR string := "Hello, world!"; # create an array with variable bounds #
string := "shorter" # flexible arrays automatically resize themselves on assignment #
)</langsyntaxhighlight>
 
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.
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% declare an array %
integer array a ( 1 :: 10 );
% set the values %
for i := 1 until 10 do a( i ) := i;
% change the 3rd element %
a( 3 ) := 27;
% display the 4th element %
write( a( 4 ) ); % would show 4 %
% arrays with sizes not known at compile-time must be created in inner-blocks or procedures %
begin
integer array b ( a( 3 ) - 2 :: a( 3 ) ); % b has bounds 25 :: 27 %
for i := a( 3 ) - 2 until a( 3 ) do b( i ) := i
end
% arrays cannot be part of records and cannot be returned by procecures though they can be passed %
% as parameters to procedures %
% multi-dimension arrays are supported %
end.</syntaxhighlight>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">DEF ai[100] : ARRAY OF CHAR, -> static
da: PTR TO CHAR,
la: PTR TO CHAR
Line 368 ⟶ 919:
-> "deallocating" the array
IF la <> NIL THEN END la[100]
ENDPROC</langsyntaxhighlight>
 
=={{header|AntLang}}==
<langsyntaxhighlight AntLanglang="antlang">/ Create an immutable sequence (array)
arr: <1;2;3>
 
Line 383 ⟶ 934:
 
/ Get the nth element (index origin = 0)
nth:arr[n]</langsyntaxhighlight>
 
=={{header|Apex}}==
<syntaxhighlight lang="apex">Integer[] array = new Integer[10]; // optionally, append a braced list of Integers like "{1, 2, 3}"
array[0] = 42;
System.debug(array[0]); // Prints 42</syntaxhighlight>
Dynamic arrays can be made using <code>List</code>s. <code>List</code>s and array can be used interchangeably in Apex, e.g. any method that accepts a <code>List<String></code> will also accept a <code>String[]</code>
<syntaxhighlight lang="apex">List <Integer> aList = new List <Integer>(); // optionally add an initial size as an argument
aList.add(5);// appends to the end of the list
aList.add(1, 6);// assigns the element at index 1
System.debug(list[0]); // Prints 5, alternatively you can use list.get(0)</syntaxhighlight>
 
=={{header|APL}}==
Arrays in APL are one dimensional matrices, defined by seperating variables with spaces. For example:
<syntaxhighlight lang ="apl">+/ 1 2 3</langsyntaxhighlight>
Is equivalent to <langsyntaxhighlight lang="apl">1 + 2 + 3</langsyntaxhighlight>We're folding function <syntaxhighlight lang ="apl">+</langsyntaxhighlight> over the array <langsyntaxhighlight lang="apl">1 2 3</langsyntaxhighlight>
 
=={{header|App Inventor}}==
Line 395 ⟶ 956:
All supported data types may be stored in a List.
[https://lh4.googleusercontent.com/-5y13nsUEj1U/UunGAhuqWEI/AAAAAAAAJ7U/i2IL5v6EQ5I/w631-h658-no/Capture.PNG Basic List blocks]
 
=={{header|Apex}}==
<lang apex>Integer[] array = new Integer[10]; // optionally, append a braced list of Integers like "{1, 2, 3}"
array[0] = 42;
System.debug(array[0]); // Prints 42</lang>
Dynamic arrays can be made using <code>List</code>s. <code>List</code>s and array can be used interchangeably in Apex, e.g. any method that accepts a <code>List<String></code> will also accept a <code>String[]</code>
<lang apex>List <Integer> aList = new List <Integer>(); // optionally add an initial size as an argument
aList.add(5);// appends to the end of the list
aList.add(1, 6);// assigns the element at index 1
System.debug(list[0]); // Prints 5, alternatively you can use list.get(0)</lang>
 
=={{header|AppleScript}}==
AppleScript arrays are called lists:
<langsyntaxhighlight lang="applescript"> set empty to {}
set ints to {1, 2, 3}</langsyntaxhighlight>
 
Lists can contain any objects including other lists:
<langsyntaxhighlight lang="applescript"> set any to {1, "foo", 2.57, missing value, ints}</langsyntaxhighlight>
 
Items can be appended to the beginning or end of a list:
 
<syntaxhighlight lang="applescript">set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
set beginning of any to false
set end of any to Wednesday
return any
--> {false, 1, "foo", 2.57, missing value, {1, 2, 3}, Wednesday}</syntaxhighlight>
 
Or a new list containing the items can be created through concatenation:
 
<syntaxhighlight lang="applescript">set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
set any to false & any & Wednesday
--> {false, 1, "foo", 2.57, missing value, {1, 2, 3}, Wednesday}</syntaxhighlight>
 
However, this isn't usually as efficient and it's important to be aware of the coercion rules associated with AppleScript concatenations, which may lead to unexpected results!
 
Items can't be removed from lists, but new lists can be created without them.
 
List indices are 1-based and negative numbers can be used to index items from the end of the list instead of from the beginning. Items can be indexed individually or by range:
 
<syntaxhighlight lang="applescript">set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
item -1 of any --> {1, 2, 3}
items 1 thru 3 of any --> {1, "foo", 2.57}</syntaxhighlight>
 
If required, items can be specified by class instead of the generic 'item' …
 
<syntaxhighlight lang="applescript">set any to {false, 1, "foo", 2.57, missing value, {1, 2, 3}, Wednesday}
number 2 of any -- 2.57 (ie. the second number in the list)</syntaxhighlight>
 
… and some fairly complex range specifiers are possible:
 
<syntaxhighlight lang="applescript">set any to {false, 1, "foo", 2.57, missing value, 5, 4, 12.0, 38, {1, 2, 3}, 7, Wednesday}
integers from text 1 to list 1 of any --> {5, 4, 38}</syntaxhighlight>
 
The length of a list can be determined in any of three ways, although only the first two below are now recommended:
 
<syntaxhighlight lang="applescript">count any -- Command.
length of any -- Property.
number of any -- Property.</syntaxhighlight>
 
The number of items of a specific class can also be obtained:
 
<syntaxhighlight lang="applescript">count any's reals
length of any's integers</syntaxhighlight>
 
A list's other properties are its <code>rest</code> (which is another list containing all the items except for the first) and its <code>reverse</code> (another list containing the items in reverse order).
 
Through AppleScriptObjC, AppleScript is also able to make use of Objective-C arrays and many of their methods, with bridging possible between lists and NSArrays:
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- Mac OS 10.10 (Yosemite) or later.
use framework "Foundation" -- Allows access to NSArrays and other Foundation classes.
 
set myList to {1, "foo", 2.57, missing value, {1, 2, 3}} -- AppleScript list.
set myNSArray to current application's NSArray's arrayWithArray:myList -- Bridge the list to an NSArray.
set arrayLength to myNSArray's |count|() -- Get the array's length using its 'count' property.
--> 5</syntaxhighlight>
 
=={{header|Arendelle}}==
Line 449 ⟶ 1,057:
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
<langsyntaxhighlight Argilelang="argile">use std, array
(:::::::::::::::::
Line 479 ⟶ 1,087:
DynArray[5] = 243
prints DynArray[0] DynArray[5]
del DynArray</langsyntaxhighlight>
 
{{works with|Argile|1.1.0}}
<langsyntaxhighlight Argilelang="argile">use std, array
let x = @["foo" "bar" "123"]
print x[2]
x[2] = "abc"</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program areaString.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessStringsch: .ascii "The string is at item : "
sZoneconv: .fill 12,1,' '
szCarriageReturn: .asciz "\n"
szMessStringNfound: .asciz "The string is not found in this area.\n"
 
/* areas strings */
szString1: .asciz "Apples"
szString2: .asciz "Oranges"
szString3: .asciz "Pommes"
szString4: .asciz "Raisins"
szString5: .asciz "Abricots"
 
/* pointer items area 1*/
tablesPoi1:
pt1_1: .int szString1
pt1_2: .int szString2
pt1_3: .int szString3
pt1_4: .int szString4
ptVoid_1: .int 0
ptVoid_2: .int 0
ptVoid_3: .int 0
ptVoid_4: .int 0
ptVoid_5: .int 0
 
szStringSch: .asciz "Raisins"
szStringSch1: .asciz "Ananas"
 
/* UnInitialized data */
.bss
 
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
@@@@@@@@@@@@@@@@@@@@@@@@
@ add string 5 to area
@@@@@@@@@@@@@@@@@@@@@@@@
ldr r1,iAdrtablesPoi1 @ begin pointer area 1
mov r0,#0 @ counter
1: @ search first void pointer
ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)
cmp r2,#0 @ is null ?
addne r0,#1 @ no increment counter
bne 1b @ and loop
@ store pointer string 5 in area at position r0
ldr r2,iAdrszString5 @ address string 5
str r2,[r1,r0,lsl #2] @ store address
@@@@@@@@@@@@@@@@@@@@@@@@
@ display string at item 3
@@@@@@@@@@@@@@@@@@@@@@@@
mov r2,#2 @ pointers begin in position 0
ldr r1,iAdrtablesPoi1 @ begin pointer area 1
ldr r0,[r1,r2,lsl #2]
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
@@@@@@@@@@@@@@@@@@@@@@@@
@ search string in area
@@@@@@@@@@@@@@@@@@@@@@@@
ldr r1,iAdrszStringSch
//ldr r1,iAdrszStringSch1 @ uncomment for other search : not found !!
ldr r2,iAdrtablesPoi1 @ begin pointer area 1
mov r3,#0
2: @ search
ldr r0,[r2,r3,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)
cmp r0,#0 @ is null ?
beq 3f @ end search
bl comparaison
cmp r0,#0 @ string = ?
addne r3,#1 @ no increment counter
bne 2b @ and loop
mov r0,r3 @ position item string
ldr r1,iAdrsZoneconv @ conversion decimal
bl conversion10S
ldr r0,iAdrszMessStringsch
bl affichageMess
b 100f
3: @ end search string not found
ldr r0,iAdrszMessStringNfound
bl affichageMess
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrtablesPoi1: .int tablesPoi1
iAdrszMessStringsch: .int szMessStringsch
iAdrszString5: .int szString5
iAdrszStringSch: .int szStringSch
iAdrszStringSch1: .int szStringSch1
iAdrsZoneconv: .int sZoneconv
iAdrszMessStringNfound: .int szMessStringNfound
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
/***************************************************/
/* conversion register signed décimal */
/***************************************************/
/* r0 contient le registre */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
push {r0-r5,lr} /* save des registres */
mov r2,r1 /* debut zone stockage */
mov r5,#'+' /* par defaut le signe est + */
cmp r0,#0 /* nombre négatif ? */
movlt r5,#'-' /* oui le signe est - */
mvnlt r0,r0 /* et inversion en valeur positive */
addlt r0,#1
mov r4,#10 /* longueur de la zone */
1: /* debut de boucle de conversion */
bl divisionpar10 /* division */
add r1,#48 /* ajout de 48 au reste pour conversion ascii */
strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */
sub r4,r4,#1 /* position précedente */
cmp r0,#0
bne 1b /* boucle si quotient different de zéro */
strb r5,[r2,r4] /* stockage du signe à la position courante */
subs r4,r4,#1 /* position précedente */
blt 100f /* si r4 < 0 fin */
/* sinon il faut completer le debut de la zone avec des blancs */
mov r3,#' ' /* caractere espace */
2:
strb r3,[r2,r4] /* stockage du byte */
subs r4,r4,#1 /* position précedente */
bge 2b /* boucle si r4 plus grand ou egal a zero */
100: /* fin standard de la fonction */
pop {r0-r5,lr} /*restaur desregistres */
bx lr
 
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 contient le dividende */
/* r0 retourne le quotient */
/* r1 retourne le reste */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
bx lr /* leave function */
.Ls_magic_number_10: .word 0x66666667
 
</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">; empty array
arrA: []
; array with initial values
arrB: ["one" "two" "three"]
; adding an element to an existing array
arrB: arrB ++ "four"
print arrB
; another way to add an element
append 'arrB "five"
print arrB
; retrieve an element at some index
print arrB\1</syntaxhighlight>
{{out}}
 
<pre>one two three four
one two three four five
two</pre>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
The current, official build of AutoHotkey is called AutoHotkey_L. In it, arrays are called Objects, and associative/index based work hand-in-hand.
<langsyntaxhighlight AHKlang="ahk">myArray := Object() ; could use JSON-syntax sugar like {key: value}
myArray[1] := "foo"
myArray[2] := "bar"
Line 497 ⟶ 1,320:
 
; Push a value onto the array
myArray.Insert("baz")</langsyntaxhighlight>
AutoHotkey Basic (deprecated) did not have typical arrays.
However, variable names could be concatenated, simulating associative arrays.
By convention, based on built-in function stringsplit, indexes are 1-based and "0" index is the length.
<langsyntaxhighlight AutoHotkeylang="autohotkey">arrayX0 = 4 ; length
arrayX1 = first
arrayX2 = second
Line 511 ⟶ 1,334:
StringSplit arrayX, source, %A_Space%
Loop, %arrayX0%
Msgbox % arrayX%A_Index%</langsyntaxhighlight>
 
=={{header|AutoIt}}==
Create an userdefined array.
<syntaxhighlight lang="autoit">
<lang AutoIt>
#include <Array.au3> ;Include extended Array functions (_ArrayDisplay)
 
Line 530 ⟶ 1,353:
 
_ArrayDisplay($aInputs) ;Display the Array
</syntaxhighlight>
</lang>
 
=={{header|Avail}}==
Avail supports tuples as its primary ordered collection.
<syntaxhighlight lang="avail">tup ::= <"aardvark", "cat", "dog">;</syntaxhighlight>
 
Tuple indices (officially referred to as "subscripts") are 1-based. One can provide an alternative if there is no element at a subscript using an else clause.
<syntaxhighlight lang="avail"><"pinch", "tsp", "tbsp", "cup">[4] \\ "cup"
<3, 2, 1>[100] else [0]</syntaxhighlight>
 
Tuples are immutable, however one can quickly create a new tuple with a specified element replaced.
<syntaxhighlight lang="avail"><"sheep", "wheat", "wood", "brick", "stone">[5] → "ore"</syntaxhighlight>
 
=={{header|AWK}}==
Line 537 ⟶ 1,371:
An ordered array just uses subscripts as integers. Array subscripts can start at 1, or any other integer. The built-in split() function makes arrays that start at 1.
 
<langsyntaxhighlight lang="awk">BEGIN {
# to make an array, assign elements to it
array[1] = "first"
Line 566 ⟶ 1,400:
print " " i ": " array[i]
}
}</langsyntaxhighlight>
 
{{out}}
Line 592 ⟶ 1,426:
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">1→{L₁}
2→{L₁+1}
3→{L₁+2}
Line 599 ⟶ 1,433:
Disp {L₁+1}►Dec,i
Disp {L₁+2}►Dec,i
Disp {L₁+3}►Dec,i</langsyntaxhighlight>
 
=={{header|Babel}}==
Line 607 ⟶ 1,441:
There are two kinds of array in Babel: value-arrays and pointer-arrays. A value-array is a flat array of data words. A pointer-array is an array of pointers to other things (including value-arrays). You can create a data-array with plain square-brackets. You can create a value-array with the [ptr ] list form:
 
<syntaxhighlight lang ="babel">[1 2 3]</langsyntaxhighlight>
 
<syntaxhighlight lang ="babel">[ptr 1 2 3]</langsyntaxhighlight>
 
 
===Get a single array element===
 
<langsyntaxhighlight lang="babel">[1 2 3] 1 th ;</langsyntaxhighlight>
 
{{Out}}
Line 623 ⟶ 1,457:
Changing a value-array element:
 
<langsyntaxhighlight lang="babel">[1 2 3] dup 1 7 set ;
</syntaxhighlight>
</lang>
 
{{Out}}
Line 631 ⟶ 1,465:
Changing a pointer-array element:
 
<langsyntaxhighlight lang="babel">[ptr 1 2 3] dup 1 [ptr 7] set ;</langsyntaxhighlight>
 
{{Out}}
Line 638 ⟶ 1,472:
===Select a range of an array===
 
<langsyntaxhighlight lang="babel">[ptr 1 2 3 4 5 6] 1 3 slice ;</langsyntaxhighlight>
 
{{Out}}
Line 647 ⟶ 1,481:
You can concatenate arrays of same type:
 
<langsyntaxhighlight lang="babel">[1 2 3] [4] cat</langsyntaxhighlight>
 
<langsyntaxhighlight lang="babel">[ptr 1 2 3] [ptr 4] cat</langsyntaxhighlight>
 
Concatenation creates a new array - it does not add to an array in-place. Instead, Babel provides operators and standard utilities for converting an array to a list in order to manipulate it, and then convert back.
Line 657 ⟶ 1,491:
Convert a value-array to a list of values:
 
<langsyntaxhighlight lang="babel">[1 2 3] ar2ls lsnum !</langsyntaxhighlight>
 
{{Out}}
Line 664 ⟶ 1,498:
Convert a list of values to a value-array:
 
<langsyntaxhighlight lang="babel">(1 2 3) ls2lf ;</langsyntaxhighlight>
 
{{Out}}
Line 671 ⟶ 1,505:
Convert a pointer-array to a list of pointers:
 
<langsyntaxhighlight lang="babel">[ptr 'foo' 'bar' 'baz'] ar2ls lsstr !</langsyntaxhighlight>
 
{{Out}}
Line 678 ⟶ 1,512:
Convert a list of pointers to a pointer-array:
 
<langsyntaxhighlight lang="babel">(1 2 3) bons ;</langsyntaxhighlight>
 
{{Out}}
Line 684 ⟶ 1,518:
 
To learn more about manipulating arrays and lists in Babel, type "help !" (no quotes) and follow the instructions to load the man.sp file.
 
=={{header|BaCon}}==
1.) Historical BASIC way to do arrays with BaCon
Note: We need to use quotes in DATA
 
<syntaxhighlight lang="qbasic">
DATA "January", "February", "March", "April", "May", "June", "July"
DATA "August", "September", "October", "November", "December"
 
LOCAL dat$[11]
FOR i = 0 TO 11
READ dat$[i]
PRINT dat$[i]
NEXT
</syntaxhighlight>
 
 
2.) A modern BaCon approach to do arrays using strings
<syntaxhighlight lang="qbasic">
DECLARE A$[11] = {"January", "February", "March", "April", "May", \
"June", "July", "August", "September", "October", "November", "December"} TYPE STRING
 
i = 0
'---dynamic index the end of an array is always null terminated
WHILE (A$[i] ISNOT NULL)
PRINT A$[i]
INCR i
WEND
</syntaxhighlight>
 
 
3.)Alternatively, using the command line to pass the input
name this '''split.bac'''
 
<syntaxhighlight lang="qbasic">
SPLIT ARGUMENT$ BY " " TO TOK$ SIZE len_array
 
FOR i = 1 TO len_array - 1
PRINT TOK$[i]
NEXT i
</syntaxhighlight>
 
in the terminal
<syntaxhighlight lang="bash">
./split January February March April May June July August September October November December
</syntaxhighlight>
 
Notes: if you want to take a string from the command line
and split it up into an array we use the built in SPLIT command
 
=={{header|BASIC}}==
Line 692 ⟶ 1,576:
 
The default array base (lower bound) can be set with OPTION BASE. If OPTION BASE is not set, the base may be either 0 or 1, depending on implementation. The value given in DIM statement is the upper bound. If the base is 0, then DIM a(100) will create an array containing 101 elements.
<langsyntaxhighlight lang="qbasic"> OPTION BASE 1
DIM myArray(100) AS INTEGER </langsyntaxhighlight>
 
Alternatively, the lower and upper bounds can be given while defining the array:
<langsyntaxhighlight lang="qbasic"> DIM myArray(-10 TO 10) AS INTEGER </langsyntaxhighlight>
 
Dynamic arrays:
<langsyntaxhighlight lang="qbasic"> 'Specify that the array is dynamic and not static:
'$DYNAMIC
DIM SHARED myArray(-10 TO 10, 10 TO 30) AS STRING
REDIM SHARED myArray(20, 20) AS STRING
myArray(1,1) = "Item1"
myArray(1,2) = "Item2" </langsyntaxhighlight>
 
'''Array Initialization'''
Line 711 ⟶ 1,595:
BASIC does not generally have option for initializing arrays to other values, so the initializing is usually done at run time.
DATA and READ statements are often used for this purpose:
<langsyntaxhighlight lang="qbasic"> DIM month$(12)
DATA January, February, March, April, May, June, July
DATA August, September, October, November, December
FOR m=1 TO 12
READ month$(m)
NEXT m </langsyntaxhighlight>
 
{{works with|FreeBASIC}}
 
FreeBASIC has an option to initialize array while declaring it.
<langsyntaxhighlight lang="freebasic"> Dim myArray(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}} </langsyntaxhighlight>
 
<langsyntaxhighlight lang="basic">10 REM TRANSLATION OF QBASIC STATIC VERSION
20 REM ELEMENT NUMBERS TRADITIONALLY START AT ONE
30 DIM A%(11): REM ARRAY OF ELEVEN INTEGER ELEMENTS
Line 729 ⟶ 1,613:
50 LET A%(11) = 1
60 PRINT A%(1), A%(11)
70 END</langsyntaxhighlight>
 
{{works with|qbasic}}
Line 735 ⟶ 1,619:
===Static===
 
<langsyntaxhighlight lang="qbasic">DIM staticArray(10) AS INTEGER
 
staticArray(0) = -1
staticArray(10) = 1
 
PRINT staticArray(0), staticArray(10)</langsyntaxhighlight>
 
===Dynamic===
Line 746 ⟶ 1,630:
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 (<code>DIM</code> vs. <code>REDIM</code>). [[QBasic]] lacks the <code>PRESERVE</code> keyword found in some modern BASICs; resizing an array without <code>PRESERVE</code> zeros the values.
 
<langsyntaxhighlight lang="qbasic">REDIM dynamicArray(10) AS INTEGER
 
dynamicArray(0) = -1
Line 754 ⟶ 1,638:
 
dynamicArray(20) = 1
PRINT dynamicArray(0), dynamicArray(20)</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="basic">10 DIM A%(11): REM ARRAY OF TWELVE INTEGER ELEMENTS
20 LET A%(0) = -1
30 LET A%(11) = 1
40 PRINT A%(0), A%(11)</syntaxhighlight>
 
==={{header|Commodore BASIC}}===
same as Applesoft BASIC
 
==={{header|Quite BASIC}}===
<syntaxhighlight lang="basic">10 ARRAY A
20 DIM B(10)
30 DIM C(3,2)
40 LET A[4711] = 17
50 LET B(3) = 5
60 LET B[7] = 3
70 LET C(3,2) = 1
80 PRINT C(3,2) + B(7) + B[3] + A(4711)</syntaxhighlight>
{{out}}
<pre>26</pre>
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256"># numeric array
dim numbers(10)
for t = 0 to 9
Line 785 ⟶ 1,690:
print numbers[t] + "=" + words$[t]
next t
return</langsyntaxhighlight>
 
=={{header|Batch File}}==
Arrays can be approximated, in a style similar to REXX
 
<langsyntaxhighlight lang="dos">::arrays.cmd
@echo off
setlocal ENABLEDELAYEDEXPANSION
Line 814 ⟶ 1,719:
echo %1 = %2
goto :eof
</syntaxhighlight>
</lang>
 
{{out}}
Line 827 ⟶ 1,732:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> REM Declare arrays, dimension is maximum index:
DIM array(6), array%(6), array$(6)
Line 843 ⟶ 1,748:
PRINT array(2) TAB(16) array(3) TAB(32) array(4)
PRINT array%(2) TAB(16) array%(3) TAB(32) array%(4)
PRINT array$(2) TAB(16) array$(3) TAB(32) array$(4)</langsyntaxhighlight>
 
=={{header|bc}}==
Line 850 ⟶ 1,755:
 
The following is a transcript of an interactive session:
<langsyntaxhighlight lang="bc">/* Put the value 42 into array g at index 3 */
g[3] = 42
/* Look at some other elements in g */
Line 867 ⟶ 1,772:
123
g[3]
42</langsyntaxhighlight>
 
=={{header|BML}}==
'''Note:''' Variables in BML can either be placed in a prefix group($, @, and &) or in the world. Placing variables in the world is not recommended since it can take large sums of memory when using said variable.
 
<langsyntaxhighlight lang="bml">
% Define an array(containing the numbers 1-3) named arr in the group $
in $ let arr hold 1 2 3
Line 884 ⟶ 1,789:
% There is no automatic garbage collection
delete $arr
</syntaxhighlight>
</lang>
 
=={{header|Boo}}==
<syntaxhighlight lang="boo">
myArray as (int) = (1, 2, 3) // Size based on initialization
fixedArray as (int) = array(int, 1) // Given size(1 in this case)
 
myArray[0] = 10
 
myArray = myArray + fixedArray // Append arrays
 
print myArray[0]
</syntaxhighlight>
 
=={{header|BQN}}==
Arrays are the central data type of BQN, since it is an array language.
 
All arrays are variable length, and can contain any types of values.
<syntaxhighlight lang="bqn"># Stranding:
arr ← 1‿2‿'a'‿+‿5
# General List Syntax:
arr1 ← ⟨1,2,'a',+,5⟩
•Show arr ≡ arr1 # both arrays are the same.
•Show arr
•Show arr1
 
# Taking nth element(⊑):
•Show 3⊑arr
 
# Modifying the array(↩):
arr ↩ "hello"⌾(4⊸⊑) arr</syntaxhighlight>
<syntaxhighlight lang="bqn">1
⟨ 1 2 'a' + 5 ⟩
⟨ 1 2 'a' + 5 ⟩
+
⟨ 1 2 'a' + "hello" ⟩</syntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=IyBTdHJhbmRpbmc6CmFyciDihpAgMeKAvzLigL8nYSfigL8r4oC/NQojIEdlbmVyYWwgTGlzdCBTeW50YXg6CmFycjEg4oaQIOKfqDEsMiwnYScsKyw14p+pCuKAolNob3cgYXJyIOKJoSBhcnIxICMgYm90aCBhcnJheXMgYXJlIHRoZSBzYW1lLgrigKJTaG93IGFycgrigKJTaG93IGFycjEKCiMgVGFraW5nIG50aCBlbGVtZW50KOKKkSk6CuKAolNob3cgM+KKkWFycgoKIyBNb2RpZnlpbmcgdGhlIGFycmF5KOKGqSk6CmFyciDihqkgImhlbGxvIuKMvig04oq44oqRKSBhcnIK Try It Here!]
 
=={{header|Bracmat}}==
Line 897 ⟶ 1,839:
To delete and array (and therefore the variable with the array's name), call <code>tbl</code> with a size <code>0</code>.
 
<langsyntaxhighlight lang="bracmat">( tbl$(mytable,100)
& 5:?(30$mytable)
& 9:?(31$mytable)
Line 907 ⟶ 1,849:
| out$"mytable is gone"
)
);</langsyntaxhighlight>
{{out}}
<pre>5
Line 913 ⟶ 1,855:
9
mytable is gone</pre>
 
=={{header|Boo}}==
<lang boo>
myArray as (int) = (1, 2, 3) // Size based on initialization
fixedArray as (int) = array(int, 1) // Given size(1 in this case)
 
myArray[0] = 10
 
myArray = myArray + fixedArray // Append arrays
 
print myArray[0]
</lang>
 
=={{header|Brainf***}}==
Note that Brainf*** does not natively support arrays, this example creates something that's pretty close, with access of elements at each index, altering elements, and changing size of list at runtime.
 
<syntaxhighlight lang="bf">
<lang bf>
===========[
ARRAY DATA STRUCTURE
Line 1,015 ⟶ 1,945:
return back by finding leftmost null then decrementing pointer
twice then decrement our NEWVALUE cell
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Fixed size static array of integers with initialization:
<langsyntaxhighlight lang="c">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 */</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="c">#define MYFLOAT_SIZE (sizeof(myFloats)/sizeof(myFloats[0]))</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="c">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]))</langsyntaxhighlight>
 
When the size of the array is not known at compile time, arrays may be dynamically
allocated to the proper size. The <code>malloc()</code>, <code>calloc()</code> and <code>free()</code> functions require the header <code>stdlib.h</code>.
<langsyntaxhighlight lang="c">int numElements = 10;
int *myArray = malloc(sizeof(int) * numElements); /* array of 10 integers */
if ( myArray != NULL ) /* check to ensure allocation succeeded. */
Line 1,044 ⟶ 1,974:
/* calloc() additionally pre-initializes to all zeros */
short *myShorts = calloc( numElements, sizeof(short)); /* array of 10 */
if (myShorts != NULL)....</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="c">myArray[0] = 1;
myArray[1] = 3;</langsyntaxhighlight>
 
And to retrieve it (e.g. for printing, provided that the <tt>stdio.h</tt> header was included for the printf function)
<langsyntaxhighlight lang="c">printf("%d\n", myArray[1]);</langsyntaxhighlight>
 
The <tt>array[index]</tt> syntax can be considered as a shortcut for <tt>*(index + array)</tt> and
thus the square brackets are a commutative binary operator:
<langsyntaxhighlight lang="c">*(array + index) = 1;
printf("%d\n", *(array + index));
3[array] = 5;</langsyntaxhighlight>
 
There's no bounds check on the indexes. Negative indexing can be implemented as in the following.
<langsyntaxhighlight lang="c">#define XSIZE 20
double *kernel = malloc(sizeof(double)*2*XSIZE+1);
if (kernel) {
Line 1,071 ⟶ 2,001:
free(kernel-XSIZE);
}
}</langsyntaxhighlight>
 
In C99, it is possible to declare arrays with a size that is only known at runtime (e.g. a number input by the user).
Line 1,077 ⟶ 2,007:
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. In C, arrays may be dynamically resized if they were allocated:
<syntaxhighlight lang="c">
<lang c>
int *array = malloc (sizeof(int) * 20);
....
array = realloc(array, sizeof(int) * 40);
</syntaxhighlight>
</lang>
A Linked List for chars may be implemented like this:
<syntaxhighlight lang="c">
#include <stdlib.h>
#include <stdio.h>
typedef struct node{
char value;
struct node* next;
} node;
typedef struct charList{
node* first;
int size;
} charList;
 
charList createList(){
=={{header|ChucK}}==
charList foo = {.first = NULL, .size = 0};
<lang c>
return foo;
int array[0]; // instantiate int array
}
array << 1; // append item
int addEl(charList* list, char c){
array << 2 << 3; // append items
if(list != NULL){
4 => array[3]; // assign element(4) to index(3)
node* foo = (node*)malloc(sizeof(node));
5 => array.size; // resize
if(foo == NULL) return -1;
array.clear(); // clear elements
foo->value = c; foo->next = NULL;
<<<array.size()>>>; // print in cosole array size
if(list->first == NULL){
[1,2,3,4,5,6,7] @=> array;
list->first = foo;
array.popBack(); // Pop last element
}else{
</lang>
node* it= list->first;
while(it->next != NULL)it = it->next;
it->next = foo;
}
list->size = list->size+1;
return 0;
}else return -1;
}
int removeEl(charList* list, int index){
if(list != NULL && list->size > index){
node* it = list->first;
for(int i = 0; i < index-1; i++) it = it->next;
node* el = it->next;
it->next = el->next;
free(el);
list->size--;
return 0;
}else return -1;
}
char getEl(charList* list, int index){
if(list != NULL && list->size > index){
node* it = list->first;
for(int i = 0; i < index; i++) it = it->next;
return it->value;
}else return '\0';
}
static void cleanHelp(node* el){
if(el != NULL){
if(el->next != NULL) cleanHelp(el->next);
free(el);
}
}
void clean(charList* list){
cleanHelp(list->first);
list->size = 0;
}
</syntaxhighlight>
 
=={{header|C sharp|C#}}==
 
Example of array of 10 int types:
 
<syntaxhighlight lang="csharp"> int[] numbers = new int[10];</syntaxhighlight>
 
Example of array of 3 string types:
 
<syntaxhighlight lang="csharp"> string[] words = { "these", "are", "arrays" };</syntaxhighlight>
 
You can also declare the size of the array and initialize the values at the same time:
 
<syntaxhighlight lang="csharp"> int[] more_numbers = new int[3]{ 21, 14 ,63 };</syntaxhighlight>
 
 
For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration.
 
The following creates a 3x2 int matrix
<syntaxhighlight lang="csharp"> int[,] number_matrix = new int[3,2];</syntaxhighlight>
 
As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces.
 
<syntaxhighlight lang="csharp"> string[,] string_matrix = { {"I","swam"}, {"in","the"}, {"freezing","water"} };</syntaxhighlight>
 
or
 
<syntaxhighlight lang="csharp"> string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} };</syntaxhighlight>
 
<syntaxhighlight lang="csharp">int[] array = new int[10];
 
array[0] = 1;
array[1] = 3;
 
Console.WriteLine(array[0]);</syntaxhighlight>
 
Dynamic
 
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
List<int> list = new List<int>();
 
list.Add(1);
list.Add(3);
 
list[0] = 2;
 
Console.WriteLine(list[0]);</syntaxhighlight>
 
=={{header|C++}}==
Line 1,108 ⟶ 2,136:
<code>std::vector<T></code> is a resizable array of <code>T</code> objects.
The memory for the array will be allocated from the heap (unless a custom allocator is used).
<langsyntaxhighlight lang="cpp">#include <array>
#include <vector>
 
Line 1,151 ⟶ 2,179:
demonstrate(fixed_size_array);
demonstrate(dynamic_array);
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
 
Example of array of 10 int types:
 
<lang csharp> int[] numbers = new int[10];</lang>
 
Example of array of 3 string types:
 
<lang csharp> string[] words = { "these", "are", "arrays" };</lang>
 
You can also declare the size of the array and initialize the values at the same time:
 
<lang csharp> int[] more_numbers = new int[3]{ 21, 14 ,63 };</lang>
 
 
For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration.
 
The following creates a 3x2 int matrix
<lang csharp> int[,] number_matrix = new int[3,2];</lang>
 
As with the previous examples you 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 csharp> string[,] string_matrix = { {"I","swam"}, {"in","the"}, {"freezing","water"} };</lang>
 
or
 
<lang csharp> string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} };</lang>
 
<lang csharp>int[] array = new int[10];
 
array[0] = 1;
array[1] = 3;
 
Console.WriteLine(array[0]);</lang>
 
Dynamic
 
<lang csharp>using System;
using System.Collections.Generic;
 
List<int> list = new List<int>();
 
list.Add(1);
list.Add(3);
 
list[0] = 2;
 
Console.WriteLine(list[0]);</lang>
 
=={{header|Ceylon}}==
{{works with|Ceylon|1.3.0}}
<langsyntaxhighlight lang="ceylon">import ceylon.collection {
 
ArrayList
Line 1,223 ⟶ 2,202:
list.push("hello again");
print(list);
}</langsyntaxhighlight>
 
=={{header|ChucK}}==
<syntaxhighlight lang="c">
int array[0]; // instantiate int array
array << 1; // append item
array << 2 << 3; // append items
4 => array[3]; // assign element(4) to index(3)
5 => array.size; // resize
array.clear(); // clear elements
<<<array.size()>>>; // print in cosole array size
[1,2,3,4,5,6,7] @=> array;
array.popBack(); // Pop last element
</syntaxhighlight>
 
=={{header|Clean}}==
Line 1,229 ⟶ 2,221:
===Lazy array===
Create a lazy array of strings using an array denotation.
<langsyntaxhighlight lang="clean">array :: {String}
array = {"Hello", "World"}</langsyntaxhighlight>
Create a lazy array of floating point values by sharing a single element.
<langsyntaxhighlight lang="clean">array :: {Real}
array = createArray 10 3.1415</langsyntaxhighlight>
Create a lazy array of integers using an array (and also a list) comprehension.
<langsyntaxhighlight lang="clean">array :: {Int}
array = {x \\ x <- [1 .. 10]}</langsyntaxhighlight>
===Strict array===
Create a strict array of integers.
<langsyntaxhighlight lang="clean">array :: {!Int}
array = {x \\ x <- [1 .. 10]}</langsyntaxhighlight>
===Unboxed array===
Create an unboxed array of characters, also known as <tt>String</tt>.
<langsyntaxhighlight lang="clean">array :: {#Char}
array = {x \\ x <- ['a' .. 'z']}</langsyntaxhighlight>
 
=={{header|Clipper}}==
Clipper arrays aren't divided to fixed-length and dynamic. Even if we declare it with a certain dimensions, it can be resized in the same way as it was created dynamically. The first position in an array is 1, not 0, as in some other languages.
<langsyntaxhighlight lang="visualfoxpro"> // Declare and initialize two-dimensional array
Local arr1 := { { "NITEM","N",10,0 }, { "CONTENT","C",60,0} }
// Create an empty array
Line 1,258 ⟶ 2,250:
 
// Array can be dynamically resized:
arr4 := ASize( arr4, 80 )</langsyntaxhighlight>
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
<langsyntaxhighlight lang="visualfoxpro">// Adding new item to array, its size is incremented
Aadd( arr1, { "LBASE","L",1,0 } )
// Delete the first item of arr3, The size of arr3 remains the same, all items are shifted to one position, the last item is replaced by Nil:
ADel( arr1, 1 )
// Assigning a value to array item
arr3[1,1,1] := 11.4</langsyntaxhighlight>
Retrieve items of an array:
<langsyntaxhighlight lang="visualfoxpro"> x := arr3[1,10,2]
// The retrieved item can be nested array, in this case it isn't copied, the pointer to it is assigned
</syntaxhighlight>
</lang>
There is a set of functions to manage arrays in Clipper, including the following:
<langsyntaxhighlight lang="visualfoxpro">// Fill the 20 items of array with 0, starting from 5-th item:
AFill( arr4, 0, 5, 20 )
//Copy 10 items from arr4 to arr3[2], starting from the first position:
Line 1,277 ⟶ 2,269:
//Duplicate the whole or nested array:
arr5 := AClone( arr1 )
arr6 := AClone( arr1[3] )</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">;clojure is a language built with immutable/persistent data structures. there is no concept of changing what a vector/list
;is, instead clojure creates a new array with an added value using (conj...)
;in the example below the my-list does not change.
Line 1,313 ⟶ 2,305:
 
user=> (conj my-vec 300) ;adding to a vector always adds to the end of the vector
[1 2 3 4 5 6 300]</langsyntaxhighlight>
 
=={{header|COBOL}}==
In COBOL, arrays are called ''tables''. Also, indexes begin from 1.
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. arrays.
 
Line 1,355 ⟶ 2,347:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">array1 = []
array1[0] = "Dillenidae"
array1[1] = "animus"
Line 1,365 ⟶ 2,357:
 
array2 = ["Cepphus", "excreta", "Gansu"]
alert "Value of array2[1]: " + array2[1] # excreta</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
Creating a one-dimensional Array:
<langsyntaxhighlight lang="cfm"><cfset arr1 = ArrayNew(1)></langsyntaxhighlight>
 
Creating a two-dimensional Array in CFScript:
<langsyntaxhighlight lang="cfm"><cfscript>
arr2 = ArrayNew(2);
</cfscript></langsyntaxhighlight>
''ColdFusion Arrays are '''NOT''' zero-based, they begin at index '''1'''''
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(let ((array (make-array 10)))
(setf (aref array 0) 1
(aref array 1) 3)
(print array))</langsyntaxhighlight>
 
Dynamic
 
<langsyntaxhighlight lang="lisp">(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))</langsyntaxhighlight>
 
Creates a one-dimensional array of length 10. The initial contents are undefined.
<syntaxhighlight lang ="lisp">(make-array 10)</langsyntaxhighlight>
Creates a two-dimensional array with dimensions 10x20.
<langsyntaxhighlight lang="lisp">(make-array '(10 20))</langsyntaxhighlight>
<tt>make-array</tt> may be called with a number of optional arguments.
<langsyntaxhighlight lang="lisp">; Makes an array of 20 objects initialized to nil
(make-array 20 :initial-element nil)
; Makes an integer array of 4 elements containing 1 2 3 and 4 initially which can be resized
(make-array 4 :element-type 'integer :initial-contents '(1 2 3 4) :adjustable t)</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
Line 1,407 ⟶ 2,399:
 
 
<langsyntaxhighlight lang="oberon2">
MODULE TestArray;
(* Implemented in BlackBox Component Builder *)
Line 1,434 ⟶ 2,426:
END DoTwoDim;
 
END TestArray.</langsyntaxhighlight>
 
=={{header|Computer/zero Assembly}}==
An array is simply a sequence of memory addresses. If we have an array beginning at address <tt>ary</tt>, we can access element <math>n</math> (zero-indexed) using an instruction of the form <tt>LDA ary+n</tt> (or <tt>STA ary+n</tt>, <tt>ADD ary+n</tt>, <tt>SUB ary+n</tt>). Generating this instruction will often involve the use of self-modifying code: we start with an instruction like <tt>LDA ary</tt>, add <math>n</math> to it, store it back, and execute it.
 
It is often convenient to be able to iterate through an array—which means knowing where the array ends. There are two easy ways to do this: <i>fixed-length arrays</i> and <i>zero-terminated arrays</i>. As an illustration, we shall find the sum of an array of the first ten positive integers using each technique.
 
===Fixed-length array===
We have finished iterating through the array when the next load instruction would be <tt>LDA ary+length(ary)</tt>.
<syntaxhighlight lang="czasm">load: LDA ary
ADD sum
STA sum
 
LDA load
ADD one
STA load
 
SUB end
BRZ done
 
JMP load
 
done: LDA sum
STP
 
one: 1
end: LDA ary+10
 
sum: 0
 
ary: 1
2
3
4
5
6
7
8
9
10</syntaxhighlight>
===Zero-terminated array===
<syntaxhighlight lang="czasm">load: LDA ary
BRZ done
 
ADD sum
STA sum
 
LDA load
ADD one
STA load
 
JMP load
 
done: LDA sum
STP
 
one: 1
 
sum: 0
 
ary: 1
2
3
4
5
6
7
8
9
10
0</syntaxhighlight>
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">
# create an array with one object in it
a = ["foo"]
 
# Empty array literals always need a type specification:
[] of Int32 # => Array(Int32).new
# The array's generic type argument T is inferred from the types of the elements inside the literal. When all elements of the array have the same type, T equals to that. Otherwise it will be a union of all element types.
[1, 2, 3] # => Array(Int32)
[1, "hello", 'x'] # => Array(Int32 | String | Char)
 
# An explicit type can be specified by immediately following the closing bracket with of and a type, each separated by whitespace. This overwrites the inferred type and can be used for example to create an array that holds only some types initially but can accept other types later.
array_of_numbers = [1, 2, 3] of Float64 | Int32 # => Array(Float64 | Int32)
array_of_numbers << 0.5 # => [1, 2, 3, 0.5]
 
array_of_int_or_string = [1, 2, 3] of Int32 | String # => Array(Int32 | String)
array_of_int_or_string << "foo" # => [1, 2, 3, "foo"]
 
# percent array literals
%w(one two three) # => ["one", "two", "three"]
%i(one two three) # => [:one, :two, :three]
</syntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">// All D arrays are capable of bounds checks.
 
import std.stdio, core.stdc.stdlib;
Line 1,477 ⟶ 2,563:
writeln("D) Element 0: ", array4[0]);
writeln("D) Element 1: ", array4[1]);
}</langsyntaxhighlight>
{{out}}
<pre>A) Element 0: 1
Line 1,488 ⟶ 2,574:
D) Element 1: 3</pre>
One more kind of built-in array:
<langsyntaxhighlight lang="d">import std.stdio, core.simd;
 
void main() {
Line 1,498 ⟶ 2,584:
writeln("E) Element 0: ", vector5.array[0]);
writeln("E) Element 1: ", vector5.array[1]);
}</langsyntaxhighlight>
{{out}}
<pre>E) Element 0: 1
Line 1,504 ⟶ 2,590:
 
=={{header|Dao}}==
<langsyntaxhighlight lang="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
Line 1,513 ⟶ 2,599:
d = a[1]
e = b[0,1] # first row, second column
f = c[1]</langsyntaxhighlight>
 
=={{header|Déjà VuDart}}==
<syntaxhighlight lang="javascript">
In Déjà Vu, the relevant datatype is called list, which is basically a stack with random element access for getting and setting values.
main(){
<lang dejavu>#create a new list
// Dart uses Lists which dynamically resize by default
local :l []
final growable = [ 1, 2, 3 ];
 
// Add to the list using the add method
#add something to it
growable.add(4);
push-to l "Hi"
 
print('growable: $growable');
#add something else to it
push-to l "Boo"
 
// You can pass an int to the constructor to create a fixed sized List
#the list could also have been built up this way:
final fixed = List(3);
local :l2 [ "Hi" "Boo" ]
// We must assign each element individually using the Subscript operator
// using .add would through an error
fixed[0] = 'one';
fixed[1] = 'two';
fixed[2] = 'three';
 
print('fixed: $fixed');
#this prints 2
!print len l
 
// If we want to create a fixed list all at once we can use the of constructor
#this prints Hi
// Setting growable to false is what makes it fixed
!print get-from l 0
final fixed2 = List.of( [ 1.5, 2.5, 3.5 ], growable: false);
 
print('fixed2: $fixed2');
#this prints Boo
!print pop-from l
// A potential gotcha involving the subscript operator [] might surprise JavaScripters
</lang>
// One cannot add new elements to a List using the subscript operator
// We can only assign to existing elements, even if the List is growable
 
final gotcha = [ 1, 2 ];
// gotcha[2] = 3 would cause an error in Dart, but not in JavaScript
// We must first add the new element using .add
gotcha.add(3);
// Now we can modify the existing elements with the subscript
gotcha[2] = 4;
 
print('gotcha: $gotcha');
 
 
}
 
</syntaxhighlight>
{{out}}
<pre>
growable: [1, 2, 3, 4]
fixed: [one, two, three]
fixed2: [1.5, 2.5, 3.5]
gotcha: [1, 2, 4]
</pre>
 
=={{header|DBL}}==
<syntaxhighlight lang="dbl">;
; Arrays for DBL version 4 by Dario B.
;
 
.DEFINE NR,5
 
RECORD
 
VNUM1, 5D8 ;array of number
VNUM2, [5]D8 ;array of number
VNUM3, [5,2]D8 ;two-dimensional array of number
 
VALP1, 5A10 ;array of strings
VALP2, [5]A10 ;array of strings
VALP3, [5,2]A10 ;two-dimensional array of strings
 
VALP4, [NR]A10 ;array of strings
 
PROC
;------------------------------------------------------------------
 
;Valid uses of arrays
VNUM1(1)=12345678
 
VNUM2(1)=VNUM1(1) ; = 12345678
VNUM2[2]=VNUM1(1) ; = 12345678
 
VNUM2[3]=VNUM2[1](3:2) ; = 34
 
VNUM3[1,1]=1
VNUM3[1,2]=2
VNUM3[2,1]=3
 
 
VALP1(1)="ABCDEFGHIJ"
 
VALP2(2)=VALP1(1) ; = "ABCDEFGHIJ"
VALP2[2]=VALP1(1) ; = "ABCDEFGHIJ"
 
VALP2[3](3:2)=VALP2[1](3:2) ; = " CD "
 
VALP3[1,1]="ABCDEFGHIJ"
VALP3[1,2]=VALP3[1,1] ;= "ABCDEFGHIJ"
VALP3[2,1](3:2)=VALP3[1,2](3:2) ;= " CD "
 
VALP4[1]="ABCDEFGHIJ"
 
;Clear arrays
CLEAR VNUM1(1:5*8),VNUM3(1:5*2*8)
VNUM2(1:5*8)=
CLEAR VALP1(1:5*8),VALP2(1:5*10)
VALP3(1:5*2*10)=</syntaxhighlight>
 
=={{header|Delphi}}==
This example creates a static and dynamic array, asks for a series of numbers storing them in the static one, puts in the dynamic one the numbers in reverse order, concatenates the number in two single string variables and display those strings in a popup window.
<langsyntaxhighlight lang="delphi">
procedure TForm1.Button1Click(Sender: TObject);
var
StaticArray: array[01..910] of Integer; // static arrays can start at any index
DynamicArray: array of Integer; // dynamic arrays always start at 0
StaticArrayText,
DynamicArrayText: string;
lcvixS, ixD: Integer;
begin
// Setting the length of the dynamic array the same as the static one
SetLength(DynamicArray, Length(StaticArray));
// Asking random numbers storing into the static array
for lcvixS := 0Low(StaticArray) to Pred(LengthHigh(StaticArray)) do
begin
StaticArray[lcvixS] := StrToInt(
InputBox('Random number',
'Enter a random number for position',
IntToStr(Succ(lcv)ixS)));
end;
// Storing entered numbers of the static array in reverse order into the dynamic
ixD := High(DynamicArray);
for lcv := 0 to Pred(Length(StaticArray)) do
for ixS DynamicArray[Pred(Length:= Low(DynamicArray)StaticArray) - lcv] :=to High(StaticArray[lcv];) do
// Concatenating the static and dynamic array into a single string variable
for lcv := 0 to Pred(Length(StaticArray)) do
begin
StaticArrayTextDynamicArray[ixD] := StaticArrayText + IntToStr(StaticArray[lcvixS]);
Dec(ixD);
DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[lcv]);
end;
// Concatenating the static and dynamic array into a single string variable
StaticArrayText := '';
for ixS := Low(StaticArray) to High(StaticArray) do
StaticArrayText := StaticArrayText + IntToStr(StaticArray[ixS]);
DynamicArrayText := '';
for ixD := Low(DynamicArray) to High(DynamicArray) do
DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[ixD]);
end;
// Displaying both arrays (#13#10 = Carriage Return/Line Feed)
ShowMessage(StaticArrayText + #13#10 + DynamicArrayText);
end;</langsyntaxhighlight>
 
=={{header|Diego}}==
<syntaxhighlight lang="diego">set_ns(rosettacode);
set_base(0);
 
// Create a new dynamic array with length zero, variant and/or mixed datatypes
add_array(myEmptyArray);
 
// Create a new dynamic array with length zero, of integers with no mixed datatypes
add_array({int}, myIntegerArray);
// Create a new fixed-length array with length 5
add_array(myFiveArray)_len(5)_base(0); // The value base '_base(0)' is usually defaulted to zero, depends upon thing.
 
// Create an array with 2 members (length is 2)
add_ary(myStringArray)_value(Item1,Item2); // '_array' can be shortened to '_ary'
// Assign a value to member [2]
with_ary(myChangeArray)_at(2)_v(5); // '_value' can be shortened to '_v'
// Add a member to an array with the push function (defaulted at end), length increased by one
[myExpandedArray]_push()_v(9); // 'with_ary(...)' can be shortened to '[...]'
[myExpandedArray]_append()_v(9);
 
// Add a member to an array with the push function (at a location), length increased by one
[myExpandedArray]_pushat(3)_v(8);
// Remove a member to an array with the pop function (defaulted at end), length reduced by one
[myExpandedArray]_pop();
 
// Remove a member to an array with the pop function (at a location), length reduced by one
[myExpandedArray]_popat(3);
 
// Swap a member to an array with the swap function
[myExpandedArray]_swapfrom(2)_swapto(6);
[myExpandedArray]_swap(2, 6);
 
// Rectiline a member in an array
[MyCaterpillarArray]_rectilat(4)_rectilup(2);
[MyCaterpillarArray]_rectilup(4, 2);
[MyCaterpillarArray]_rectilat(5)_rectildown(3);
[MyCaterpillarArray]_rectildown(5, 3);
 
// Null a member to an array with the pluck function (defaulted at end)
[myExpandedArray]_pluck();
 
// Null a member to an array with the pluck function (at a location)
[myExpandedArray]_pluckat(3);
 
// Get size of array
[mySizableArray]_size(); // '_len()' can also be used
[myMultidimensialArray]_size()
 
// Retrieve an element of an array
[myArray]_at(3);
[myArray]_first(); // Retrieve first element in an array
[myArray]_last(); // Retrieve last element in an array
 
// More transformations of arrays (like append, union, intersection) are available
 
// For multi-dimensional array use the 'matrix' object
 
set_matrixorder(row-major); // set major order as row- or column-major order depends on the thing
set_handrule(right); // set hand-rule, most things will use right hand-rule
 
// Create a new dynamic two-dimensional array with length zero, variant and/or mixed datatypes
add_matrix(myMatrix)_dim(2);
 
// Create a new dynamic three-dimensional array with length zero, of integers with no mixed datatypes
add_matrix({int}, my3DEmptyMatrix)_dim(3);
// Convert an array to a matrix by adding a new dimension with length zero, variant and/or mixed datatypes
with_array(MyConvertedArray)_dim(); // Should now use '_matrix' object rather than '_array'
with_array(MyConvertedArray)_dim(3); // Add three dimensions to array, should now use '_matrix' object rather than '_array'
 
// Create a new fixed-length traditional (2D) matrix with 5 rows and 4 columns
add_matrix(myMatrix)_rows(5)_columns(4);
add_matirx(myMatrix)_subs(5, 4); // check or set major order first
 
// Create a new fixed-length mutil-dimensional matrix with 5 rows, 4 columns, 6 subscripts, and 8 subscripts
add_matrix(myMatrix)_rows(5)_columns(4)_subs(6)_subs(8);
add_mat(myMatrix)_subs(5, 4, 6, 8); // check or set major order first, '_matrix' can be shortened to 'mat'
 
// Create a 4 x 4 identiy matrix:
add_mat(myIdentityMatrix)_subs(4, 4)_identity; // ...or...
 
add_mat(myMorphedMatrix)_subs(4, 4)
with_mat(myMorphedMatrix)_trans(morph)_identity(); // More transformations available
// Assign a value to member [2,4]
with_mat(myMatrix)_row(2)_col(4)_value(5); // ...or...
with_mat(myMatrix)_at(2, 4)_v(5); // check or set major order first
// Add a member(s) to a matrix using push functions is available
// Remove a member(s) from a matrix with the pop functions is available
// Swap a member(s) in a matrix with the swap functions is available
 
// Rectiline a single member in a three-dimensional matrix
[MyWobbleMatrix]_rectilat()_row(3)_col(3)_sub(3)_rectilto()_row(-1)_col(1)_sub(0); // ...or...
[MyWobbleMatrix]_rectilat(3, 3, 3)_rectilto(-1, 1, 0); // check or set major order first, ...or...
[MyWobbleMatrix]_rectilat(3, 3, 3)_rectilleft(1)_rectilup(1); / check or set hand-rule, ...or...
 
// Also 'crab', 'elevate', 'slide' and 'pump' movements are available
// Also 'row', 'pitch', and 'yaw' movements are available
// Also, quaternions calculations are available
// Null a member in a matrix using pluck functions is available
 
// Get size of a matrix
mat(mySizableMatrix)_size(); // will return an array of the size()
[myMultidimensialArray]_len(); // '_len()' can also be used
 
// Retrieve an element of a matrix
[myMatrix]_at(3, 2);
[myArray]_first()_atsub(2); // Retrieve first element of a row/column/subscript of a matrix
[myArray]_last()_atsub(2); // Retrieve last element of a row/column/subscript of a matrix
[myArray]_origin(); // Retrieve first element in a matrix
[myArray]_end(); // Retrieve last element in a matrix
 
reset_ns[];</syntaxhighlight>
 
=={{header|Dragon}}==
<syntaxhighlight lang="dragon">array = newarray(3) //optionally, replace "newarray(5)" with a brackets list of values like "[1, 2, 3]"
array[0] = 42
showln array[2] </syntaxhighlight>
 
=={{header|DWScript}}==
 
<langsyntaxhighlight lang="delphi">
// dynamic array, extensible, this a reference type
var d : array of Integer;
Line 1,590 ⟶ 2,889:
// inline array constructor, works for both static and dynamic arrays
s := [1, 2, 3];
</syntaxhighlight>
</lang>
 
=={{header|Dyalect}}==
 
<syntaxhighlight lang="dyalect">//Dyalect supports dynamic arrays
var empty = []
var xs = [1, 2, 3]
 
//Add elements to an array
empty.Add(0)
empty.AddRange(xs)
 
//Access array elements
var x = xs[2]
xs[2] = x * x</syntaxhighlight>
 
=={{header|Déjà Vu}}==
In Déjà Vu, the relevant datatype is called list, which is basically a stack with random element access for getting and setting values.
<syntaxhighlight lang="dejavu">#create a new list
local :l []
 
#add something to it
push-to l "Hi"
 
#add something else to it
push-to l "Boo"
 
#the list could also have been built up this way:
local :l2 [ "Hi" "Boo" ]
 
#this prints 2
!print len l
 
#this prints Hi
!print get-from l 0
 
#this prints Boo
!print pop-from l
</syntaxhighlight>
 
=={{header|E}}==
Line 1,598 ⟶ 2,935:
Literal lists are <code>ConstList</code>s.
 
<langsyntaxhighlight lang="e">? def empty := []
# value: []
 
Line 1,608 ⟶ 2,945:
 
? numbers + [4,3,2,1]
# value: [1, 2, 3, 4, 5, 4, 3, 2, 1]</langsyntaxhighlight>
 
Note that each of these operations returns a different list object rather than modifying the original. You can, for example, collect values:
 
<langsyntaxhighlight lang="e">? var numbers := []
# value: []
 
Line 1,619 ⟶ 2,956:
 
? numbers with= 2 # shorthand for same
# value: [1, 2]</langsyntaxhighlight>
 
FlexLists can be created explicitly, but are typically created by ''diverging'' another list. A ConstList can be gotten from a FlexList by ''snapshot''.
 
<langsyntaxhighlight lang="e">? def flex := numbers.diverge()
# value: [1, 2].diverge()
 
Line 1,634 ⟶ 2,971:
 
? flex.snapshot()
# value: [1, 2, -3]</langsyntaxhighlight>
 
Creating a FlexList with a specific size, generic initial data, and a type restriction:
 
<langsyntaxhighlight lang="e">([0] * 100).diverge(int) # contains 100 zeroes, can only contain integers</langsyntaxhighlight>
 
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.
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">len f[] 4
for i = 1 to len f[]
f[i] = i
.
f[] &= 5
for i = 1 to len f[]
print f[i]
.</syntaxhighlight>
 
=={{header|Ecstasy}}==
Arrays use the [] syntax from C, use zero-based indexing, have a literal syntax, and are implemented by the [https://github.com/xtclang/xvm/blob/master/lib_ecstasy/src/main/x/ecstasy/collections/Array.x Array] class.
 
There are four mutability modes for the Array class, defined by the Array.Mutability enumeration. Here are some examples of how to use these different modes, and to create and manipulate arrays:
 
<syntaxhighlight lang="java">
module test {
void show(Object o=Null) {
@Inject Console console;
console.print(o);
}
 
void run() {
// an array literal has Constant mutability; it is **not** mutable
immutable Int[] literalArray = [1,2,3];
show($"{literalArray=}, {&literalArray.actualType=}");
 
// obtaining the size or any element of an array is easy
show($"{literalArray.size=}, {literalArray[2]=}");
 
// modifications to a Constant array result in a new Constant array;
// in Computer Science, this is called a persistent data structure
immutable Int[] biggerArray = literalArray + 4;
show($"{biggerArray=}, {&biggerArray.actualType=}");
 
immutable Int[] biggestArray = biggerArray + biggerArray;
show($"{biggestArray=}, {&biggestArray.actualType=}");
 
// arrays can be accessed using the bracket operators
show($"element at {biggestArray[2]=}");
 
// attempts to modify an immutable array "in place" will result in an
// exception at runtime
try {
biggestArray[2] = 99;
} catch (ReadOnly e) {
show($"immutable array not modified: {biggestArray=}");
}
 
// fixed-size arrays are like C/Java/C# arrays; their elements are
// all set to the default value of the array Element type
Int[] fixedLengthArray = new Int[10];
show($"element at {fixedLengthArray[2]=}");
 
// you can also initialize all the elements to a specific value
Int[] negOnes = new Int[3](-1);
show($"{negOnes=}");
 
// ... or using a lambda
Int[] counting = new Int[5](i -> i);
show($"{counting=}");
 
// attempts to modify a fixed-size array "in place" will succeed
counting[1] = 99;
show($"replaced [1]=99: {counting=}");
 
// attempts to add or delete elements from a fixed-size array will
// raise an exception
try {
counting += 101;
} catch (ReadOnly e) {
show($"Fixed mutability array not appendable: {counting=}");
}
 
// you can ask an array for its mutability
show($"{literalArray.mutability=}, {fixedLengthArray.mutability=}");
 
// you can convert an array from one mutability to another; the
// Persistent mutability is just like the Constant mutability,
// except that the array doesn't have to be immutable, so the
// array can hold elements that are mutable, but no elements can
// be added, removed, or replaced
Int[] constantToMutable = biggestArray.toArray(Mutable);
show($|{constantToMutable=}, {&constantToMutable.actualType=},\
| {constantToMutable.mutability=}
);
Int[] constantToFixed = biggestArray.toArray(Fixed);
show($|{constantToFixed=}, {&constantToFixed.actualType=},\
| {constantToFixed.mutability=}
);
Int[] fixedToPersistent = counting.toArray(Persistent);
show($|{fixedToPersistent=}, {&fixedToPersistent.actualType=},\
| {fixedToPersistent.mutability=}
);
Int[] fixedToConstant = counting.toArray(Constant);
show($|{fixedToConstant=}, {&fixedToConstant.actualType=},\
| {fixedToConstant.mutability=}
);
 
// a slice of an array is an array; this is very handy
Int[] slice = constantToMutable[1..2];
show($"{slice=}");
 
// slices may rely on the array that they are sliced from; to ensure that
// changes to the original array don't appear in the slice, the slice
// must be reified
constantToMutable[1] = 17; // this will appear in the slice
slice = slice.reify();
constantToMutable[2] = 18; // this will NOT appear in the slice
show($"{constantToMutable=}, {slice=}");
 
// slices can be inclusive or exclusive
show($"{constantToMutable[1..2]=}");
show($"{constantToMutable[1..<2]=}");
show($"{constantToMutable[1>..2]=}");
show($"{constantToMutable[1>..<2]=}");
 
// creating a new Mutable array uses the simplest form of the constructor;
// a Mutable array
Int[] variableArray = new Int[];
show($"new {variableArray=}");
 
// you can specify an estimated capacity for a new Mutable array, but the
// capacity is just an optimization hint!
Int[] willBeGiantArray = new Int[](999);
show($"new {willBeGiantArray=}, {willBeGiantArray.capacity=}");
 
// you can easily add and remove data from a Mutable array
for (Int i : 10..1) {
variableArray.add(i);
}
show($"NASA count-down: {variableArray=}");
 
// remove unlucky numbers in Japanese
variableArray.remove(4);
show($"lucky count-down: {variableArray=}");
 
// delete by index works as well
variableArray.delete(variableArray.size-1);
show($"aborted count-down: {variableArray=}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
literalArray=[1, 2, 3], &literalArray.actualType=immutable Array<Int>
literalArray.size=3, literalArray[2]=3
biggerArray=[1, 2, 3, 4], &biggerArray.actualType=immutable Array<Int>
biggestArray=[1, 2, 3, 4, 1, 2, 3, 4], &biggestArray.actualType=immutable Array<Int>
element at biggestArray[2]=3
immutable array not modified: biggestArray=[1, 2, 3, 4, 1, 2, 3, 4]
element at fixedLengthArray[2]=0
negOnes=[-1, -1, -1]
counting=[0, 1, 2, 3, 4]
replaced [1]=99: counting=[0, 99, 2, 3, 4]
Fixed mutability array not appendable: counting=[0, 99, 2, 3, 4]
literalArray.mutability=Constant, fixedLengthArray.mutability=Fixed
constantToMutable=[1, 2, 3, 4, 1, 2, 3, 4], &constantToMutable.actualType=Array<Int>, constantToMutable.mutability=Mutable
constantToFixed=[1, 2, 3, 4, 1, 2, 3, 4], &constantToFixed.actualType=Array<Int>, constantToFixed.mutability=Fixed
fixedToPersistent=[0, 99, 2, 3, 4], &fixedToPersistent.actualType=Array<Int>, fixedToPersistent.mutability=Persistent
fixedToConstant=[0, 99, 2, 3, 4], &fixedToConstant.actualType=immutable Array<Int>, fixedToConstant.mutability=Constant
slice=[2, 3]
constantToMutable=[1, 17, 18, 4, 1, 2, 3, 4], slice=[17, 3]
constantToMutable[1..2]=[17, 18]
constantToMutable[1..<2]=[17]
constantToMutable[1>..2]=[18]
constantToMutable[1>..<2]=[]
new variableArray=[]
new willBeGiantArray=[], willBeGiantArray.capacity=0
NASA count-down: variableArray=[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
lucky count-down: variableArray=[10, 9, 8, 7, 6, 5, 3, 2, 1]
aborted count-down: variableArray=[10, 9, 8, 7, 6, 5, 3, 2]
</pre>
 
=={{header|EGL}}==
Line 1,648 ⟶ 3,161:
 
'''Fixed-length array'''
<syntaxhighlight lang="egl">
<lang EGL>
array int[10]; //optionally, add a braced list of values. E.g. array int[10]{1, 2, 3};
array[1] = 42;
SysLib.writeStdout(array[1]);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,673 ⟶ 3,186:
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,707 ⟶ 3,220:
my_static_array: ARRAY [STRING]
end
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 6.x:
 
Static array
<langsyntaxhighlight lang="elena"> #var aStaticArraystaticArray := (new int[]{1, 2, 3).};</langsyntaxhighlight>
Generic array
<syntaxhighlight lang ="elena"> #var anArrayarray := system'Array new &length:.allocate(3.);
anArray@array[0] := 1.;
anArray@array[1] := 2.;
anArray@array[2] := 3.;</langsyntaxhighlight>
Stack allocated typed array
<syntaxhighlight lang="elena"> int stackAllocatedArray[3];
<lang elena> #var(int:3)aStackAllocatedArray.
aStackAllocatedArray@stackAllocatedArray[0] := 1.;
aStackAllocatedArray@stackAllocatedArray[1] := 2.;
aStackAllocatedArray@stackAllocatedArray[2] := 3.;</langsyntaxhighlight>
Dynamic array
<langsyntaxhighlight lang="elena"> #var aDynamicArraydynamicArray := ArrayList new. system'collections'ArrayList();
dynamicArray.append(1);
aDynamicArray += 1.
dynamicArray.append(2);
aDynamicArray += 2.
dynamicArray.append(4);
aDynamicArray += 4.
 
aDynamicArray@dynamicArray[2] := 3.;</langsyntaxhighlight>
Printing an element
<syntaxhighlight lang ="elena"> system'console .writeLine:(anArray@array[0]).;
system'console .writeLine:(aStackAllocatedArray@stackAllocatedArray[1]).;
system'console .writeLine:(aDynamicArray@dynamicArray[2]).;</langsyntaxhighlight>
 
=={{header|Elixir}}==
The elixir language has array-like structures called ''tuples''. The values of tuples occur sequentially in memory, and can be of any type. Tuples are represented with curly braces:
 
<langsyntaxhighlight lang="elixir">ret = {:ok, "fun", 3.1415}</langsyntaxhighlight>
 
Elements of tuples are indexed numerically, starting with zero.
 
<langsyntaxhighlight lang="elixir">elem(ret, 1) == "fun"
elem(ret, 0) == :ok
put_elem(ret, 2, "pi") # => {:ok, "fun", "pi"}
ret == {:ok, "fun", 3.1415}</langsyntaxhighlight>
 
Elements can be appended to tuples with <tt>Tuple.append/2</tt>, which returns a new tuple, without having modified the tuple given as an argument.
 
<langsyntaxhighlight lang="elixir">Tuple.append(ret, 3.1415) # => {:ok, "fun", "pie", 3.1415}</langsyntaxhighlight>
 
New tuple elements can be inserted with <tt>Tuple.insert/3</tt>, which returns a new tuple with the given value inserted at the indicated position in the tuple argument.
 
<langsyntaxhighlight lang="elixir">Tuple.insert_at(ret, 1, "new stuff") # => {:ok, "new stuff", "fun", "pie"}</langsyntaxhighlight>
 
Elixir also has structures called ''lists'', which can contain values of any type, and are implemented as linked lists. Lists are represented with square brackets:
 
<langsyntaxhighlight lang="elixir">[ 1, 2, 3 ]</langsyntaxhighlight>
 
Lists can be indexed, appended, added, subtracted, and list elements can be replaced, updated, and deleted. In all cases, new lists are returned without affecting the list being operated on.
 
<langsyntaxhighlight lang="elixir">my_list = [1, :two, "three"]
my_list ++ [4, :five] # => [1, :two, "three", 4, :five]
 
Line 1,767 ⟶ 3,282:
List.delete(my_list, :two) # => [1, "three"]
my_list -- ["three", 1] # => [:two]
my_list # => [1, :two, "three"]</langsyntaxhighlight>
 
Lists have a ''head'', being the first element, and a ''tail'', which are all the elements of the list following the head.
 
<langsyntaxhighlight lang="elixir">iex(1)> fruit = [:apple, :banana, :cherry]
[:apple, :banana, :cherry]
iex(2)> hd(fruit)
Line 1,780 ⟶ 3,295:
true
iex(5)> tl(fruit) == [:banana, :cherry]
true</langsyntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
^|EMal has dynamic lists.
|Lists have differen API to change the value in-place or not.
|SQL like name: insert, append, delete, order alter the current list.
|There are methods that operate on indexes, other on values.
|^
List a = int[] # a:[]
a.append(8) # a:[8]
a.insert(1, 13) # a:[8,13]
a.delete(0) # a:[13]
a.clear() # a:[]
a.of(21, 33) # a:[21,33]
a[1] = 34 # a:[21,34]
List b = a.remove(21) # a:[21, 34], b:[34]
writeLine("a has " + a.length + " items, their values are " + a[0] + ", " + a[1])
writeLine("b has " + b.length + " item, its value is " + b[0])
</syntaxhighlight>
{{out}}
<pre>
a has 2 items, their values are 21, 34
b has 1 item, its value is 34
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
%% Create a fixed-size array with entries 0-9 set to 'undefined'
A0 = array:new(10).
Line 1,814 ⟶ 3,353:
{'EXIT',{badarg,_}} = (catch array:set(18, true, A3)).
{'EXIT',{badarg,_}} = (catch array:get(18, A3)).
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
Line 1,867 ⟶ 3,406:
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">
<lang Euphoria>
--Arrays task for Rosetta Code wiki
--User:Lnettnay
Line 1,897 ⟶ 3,436:
end for
? dynarray
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,905 ⟶ 3,444:
{10,9,8,7,6,5,4,3,2,1,1,4,9,16,25,36,49,64,81,100}
</pre>
 
=={{header|Explore}}==
The [[Scratch]] [[Arrays#Scratch|solution]], which requires making an array named "array" first, works, unmodified:<br>https://i.ibb.co/Hp6dLXX/Arrays-in-Explore-using-the-Scratch-solution.png
 
This example uses a special block located in the Strings category, and outputs the results of the repeating of the string to a "say" block, and additionally starts when the flag is activated:<br>https://i.ibb.co/QN4ys6k/Arrays-in-Explore-using-a-special-block.png
 
=={{header|F Sharp|F#}}==
'''Fixed-length arrays:'''
<langsyntaxhighlight lang="fsharp">> Array.create 6 'A';;
val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
> Array.init 8 (fun i -> i * 10) ;;
Line 1,919 ⟶ 3,463:
val it : unit = ()
> arr;;
val it : int [] = [|0; 1; 2; 3; 65; 5; 6|]</langsyntaxhighlight>
 
'''Dynamic arrays:'''
 
If dynamic arrays are needed, it is possible to use the .NET class <code>System.Collections.Generic.List<'T></code> which is aliased as <code>Microsoft.FSharp.Collections.ResizeArray<'T></code>:
<langsyntaxhighlight lang="fsharp">> let arr = new ResizeArray<int>();;
val arr : ResizeArray<int>
> arr.Add(42);;
Line 1,938 ⟶ 3,482:
Parameter name: index ...
> arr;;
val it : ResizeArray<int> = seq [13]</langsyntaxhighlight>
 
=={{header|Factor}}==
Line 1,945 ⟶ 3,489:
 
Directly in the listener :
<langsyntaxhighlight lang="factor">{ 1 2 3 }
{
[ "The initial array: " write . ]
Line 1,951 ⟶ 3,495:
[ "Modified array: " write . ]
[ "The element we modified: " write [ 1 ] dip nth . ]
} cleave</langsyntaxhighlight>
The initial array: { 1 2 3 }
Modified array: { 1 42 3 }
Line 1,961 ⟶ 3,505:
{ 1 "coucou" f [ ] }
Arrays of growable length are called Vectors.
<langsyntaxhighlight lang="factor">V{ 1 2 3 }
{
[ "The initial vector: " write . ]
[ [ 42 ] dip push ]
[ "Modified vector: " write . ]
} cleave</langsyntaxhighlight>
The initial vector: V{ 1 2 3 }
Modified vector: V{ 1 2 3 42 }
Line 2,031 ⟶ 3,575:
For example, a static array of 10 cells in the dictionary, 5 initialized and 5 uninitialized:
 
<langsyntaxhighlight lang="forth">create MyArray 1 , 2 , 3 , 4 , 5 , 5 cells allot
here constant MyArrayEnd
 
Line 2,037 ⟶ 3,581:
MyArray 7 cells + @ . \ 30
 
: .array MyArrayEnd MyArray do I @ . cell +loop ;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="forth">
: array ( n -- )
create
Line 2,060 ⟶ 3,604:
5fillMyArray
.MyArray \ 1 2 3 4 5 0 30 0 0 0
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="forth">
: array create dup , dup cells here swap 0 fill cells allot ;
: [size] @ ;
Line 2,077 ⟶ 3,621:
5fillMyArray
.MyArray \ 1 2 3 4 5 0 30 0 0 0
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
Line 2,083 ⟶ 3,627:
 
Basic array declaration:
<syntaxhighlight lang ="fortran">integer a (10)</langsyntaxhighlight>
<syntaxhighlight lang ="fortran">integer :: a (10)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">integer, dimension (10) :: a</langsyntaxhighlight>
Arrays are one-based. These declarations are equivalent:
<langsyntaxhighlight lang="fortran">integer, dimension (10) :: a</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">integer, dimension (1 : 10) :: a</langsyntaxhighlight>
Other bases can be used:
<langsyntaxhighlight lang="fortran">integer, dimension (0 : 9) :: a</langsyntaxhighlight>
Arrays can have any type (intrinsic or user-defined), e.g.:
<langsyntaxhighlight lang="fortran">real, dimension (10) :: a</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">type (my_type), dimension (10) :: a</langsyntaxhighlight>
Multidimensional array declaration:
<langsyntaxhighlight lang="fortran">integer, dimension (10, 10) :: a</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">integer, dimension (10, 10, 10) :: a</langsyntaxhighlight>
Allocatable array declaration:
<langsyntaxhighlight lang="fortran">integer, dimension (:), allocatable :: a</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">integer, dimension (:, :), allocatable :: a</langsyntaxhighlight>
Array allocation:
<syntaxhighlight lang ="fortran">allocate (a (10))</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">allocate (a (10, 10))</langsyntaxhighlight>
Array deallocation:
<syntaxhighlight lang ="fortran">deallocate (a)</langsyntaxhighlight>
Array initialisation:
<langsyntaxhighlight lang="fortran">integer, dimension (10) :: a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">integer :: i
integer, dimension (10) :: a = (/(i * i, i = 1, 10)/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">integer, dimension (10) :: a = 0</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">integer :: i
integer, dimension (10, 10) :: a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))</langsyntaxhighlight>
Constant array declaration:
<langsyntaxhighlight lang="fortran">integer :: i
integer, dimension (10), parameter :: a = (/(i * i, i = 1, 10)/)</langsyntaxhighlight>
Element assignment:
<langsyntaxhighlight lang="fortran">a (1) = 1</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a (1, 1) = 1</langsyntaxhighlight>
Array assignment (note that since Fortran 2003 array assignment also allocates or reallocates if necessary):
Array assignment:
<langsyntaxhighlight lang="fortran">a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a = (/(i * i, i = 1, 10)/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a = 0</langsyntaxhighlight>
Array section assignment:
<langsyntaxhighlight lang="fortran">a (:) = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a (1 : 5) = (/1, 2, 3, 4, 5/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a (: 5) = (/1, 2, 3, 4, 5/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a (6 :) = (/1, 2, 3, 4, 5/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a (1 : 5) = (/(i * i, i = 1, 10)/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a (1 : 5)= 0</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a (1, :)= (/(i * i, i = 1, 10)/)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">a (1 : 5, 1)= (/(i * i, i = 1, 5)/)</langsyntaxhighlight>
Element retrieval:
<langsyntaxhighlight lang="fortran">i = a (1)</langsyntaxhighlight>
Array section retrieval:
<langsyntaxhighlight lang="fortran">a = b (1 : 10)</langsyntaxhighlight>
Size retrieval:
<langsyntaxhighlight lang="fortran">i = size (a)</langsyntaxhighlight>
Size along a single dimension retrieval:
<langsyntaxhighlight lang="fortran">i = size (a, 1)</langsyntaxhighlight>
Bounds retrieval:
<langsyntaxhighlight lang="fortran">i_min = lbound (a)</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">i_max = ubound (a)</langsyntaxhighlight>
Bounds of a multidimensional array retrieval:
<langsyntaxhighlight lang="fortran">a = ubound (b)</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Line 2,177 ⟶ 3,721:
 
'''The default lower bound is always 0'''
<langsyntaxhighlight FreeBASIClang="freebasic">' compile with: FBC -s console.
' compile with: FBC -s console -exx to have boundary checks.
 
Line 2,258 ⟶ 3,802:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre> The first dimension has a lower bound of 1 and a upper bound of 2
Line 2,293 ⟶ 3,837:
=={{header|Frink}}==
In Frink, all arrays are dynamically resizable. Arrays can be created as literals or using <CODE>new array</CODE>
<langsyntaxhighlight lang="frink">
a = new array
a@0 = 10
Line 2,300 ⟶ 3,844:
 
b = [1, 2, 3]
</syntaxhighlight>
</lang>
 
=={{header|Futhark}}==
{{incorrect|Futhark|The language's syntax has changed, so "fun" should be "let"}}
 
Multidimensional regular arrays are a built-in datatype in Futhark. They can be written as array literals:
 
<syntaxhighlight lang="futhark">
<lang Futhark>
[1, 2, 3]
</syntaxhighlight>
</lang>
 
Or created by an assortment of built-in functions:
 
<syntaxhighlight lang="futhark">
<lang Futhark>
replicate 5 3 == [3,3,3,3,3]
iota 5 = [0,1,2,3,4]
</syntaxhighlight>
</lang>
 
Uniqueness types are used to permit in-place updates without violating referential transparency. For example, we can write a function that writes an element to a specific index of an array as such:
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun update(as: *[]int, i: int, x: int): []int =
let as[i] = x
in x
</syntaxhighlight>
</lang>
 
Semantically the <code>update</code> function returns a new array, but the compiler is at liberty to re-use the memory where array <code>as</code> is stored, rather than create a copy as is normally needed in pure languages. Whenever the compiler encounters a call <code>update(as,i,x)</code>, it checks that the <code>as</code> is not used again. This prevents the in-place update from being observable, except through the return value of <code>modify</code>.
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
window 1, @"FutureBasic Arrays", (0,0,480,450)
 
begin globals
dynamic gA1(10) as long
dynamic gA2(10) as Str255
end globals
 
void local fn CType
long i
text ,, fn ColorGray
print @"// C-type fixed-length"
text
long a1(4)
a1(0) = 10
a1(1) = 5
a1(2) = 12
a1(3) = 8
a1(4) = 7
for i = 0 to 4
print a1(i),
next
print
a1(0) = 24
a1(2) = 18
a1(4) = 76
for i = 0 to 4
print a1(i),
next
print
CFStringRef a2(4)
a2(0) = @"Alpha"
a2(1) = @"Bravo"
a2(2) = @"Tango"
a2(3) = @"Delta"
a2(4) = @"Echo"
for i = 0 to 4
print a2(i),
next
print
a2(2) = @"Charlie"
for i = 0 to 4
print a2(i),
next
print : print
end fn
 
void local fn CTypeDynamic
long i
text ,, fn ColorGray
print @"// C-type dynamic"
text
gA1(0) = 46
gA1(1) = 38
gA1(10) = 67
for i = 0 to fn DynamicNextElement( dynamic(gA1) ) - 1
print gA1(i),
next
print
 
gA1(5) = 19
gA1(10) = 22
for i = 0 to fn DynamicNextElement( dynamic(gA1) ) - 1
print gA1(i),
next
print
 
gA2(0) = "Kilo"
gA2(1) = "Lima"
gA2(5) = "Mike"
for i = 0 to fn DynamicNextElement( dynamic(gA2) ) - 1
print gA2(i),
next
print
 
gA2(1) = "November"
gA2(6) = "Oscar"
for i = 0 to fn DynamicNextElement( dynamic(gA2) ) - 1
print gA2(i),
next
print : print
end fn
 
void local fn CoreFoundationImmutable
long i
text ,, fn ColorGray
print @"// CoreFoundation (CF) immutable"
text
CFArrayRef a5 = @[@10,@5,@12,@8,@7]
for i = 0 to 4
print a5[i],
next
print
CFArrayRef a6 = @[@"Alpha",@"Bravo",@"Charlie",@"Delta",@"Echo"]
for i = 0 to 4
print a6[i],
next
print : print
end fn
 
void local fn CoreFoundationMutableFixedLength
long i
text ,, fn ColorGray
print @"// CoreFoundation (CF) mutable, fixed-length"
text
CFMutableArrayRef a1 = fn MutableArrayWithCapacity(3)
MutableArrayAddObject( a1, @79 )
MutableArrayAddObject( a1, @43 )
MutableArrayAddObject( a1, @101)
for i = 0 to len(a1) - 1
print a1[i],
next
print
MutableArrayReplaceObjectAtIndex( a1, @15, 2 )
for i = 0 to len(a1) - 1
print a1[i],
next
print
CFMutableArrayRef a2 = fn MutableArrayWithCapacity(4)
MutableArrayAddObject( a2, @"Whisky" )
MutableArrayAddObject( a2, @"Oscar" )
MutableArrayAddObject( a2, @"Yankee" )
MutableArrayAddObject( a2, @"Sierra" )
for i = 0 to len(a2) - 1
print a2[i],
next
print
MutableArrayReplaceObjectAtIndex( a2, @"Xray", 1 )
MutableArrayReplaceObjectAtIndex( a2, @"Zulu", 3 )
for i = 0 to len(a2) - 1
print a2[i],
next
print : print
end fn
 
void local fn CoreFoundationMutableDynamic
long i
text ,, fn ColorGray
print @"// CoreFoundation (CF) mutable, dynamic"
text
CFMutableArrayRef a1 = fn MutableArrayWithCapacity(0)
MutableArrayAddObject( a1, @"Juliet" )
MutableArrayAddObject( a1, @"Golf" )
MutableArrayAddObject( a1, @"India" )
for i = 0 to len(a1) - 1
print a1[i],
next
print
MutableArrayReplaceObjectAtIndex( a1, @"Foxtrot", 0 )
MutableArrayReplaceObjectAtIndex( a1, @"Hotel", 2 )
for i = 0 to len(a1) - 1
print a1[i],
next
print : print
end fn
 
void local fn FB_MDA
long i
text ,, fn ColorGray
print @"// FB MDA - mutable, dynamic, multi-dimensional"
text
mda_add = @"Alpha"
mda_add = @"Romeo"
mda_add = @"Mike"
for i = 0 to mda_count - 1
print mda(i),
next
print
mda_swap(0),(2)
mda(1) = @"Delta"
for i = 0 to mda_count - 1
print mda(i),
next
end fn
 
fn CType
fn CTypeDynamic
fn CoreFoundationImmutable
fn CoreFoundationMutableFixedLength
fn CoreFoundationMutableDynamic
fn FB_MDA
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
// C-type fixed-length
10 5 12 8 7
24 5 18 8 76
Alpha Bravo Tango Delta Echo
Alpha Bravo Charlie Delta Echo
 
// C-type dynamic
46 38 0 0 0 0 0 0 0 0 67
46 38 0 0 0 19 0 0 0 0 22
Kilo Lima Mike
Kilo November Mike Oscar
 
// CoreFoundation (CF) immutable
10 5 12 8 7
Alpha Bravo Charlie Delta Echo
 
// CoreFoundation (CF) mutable, fixed-length
79 43 101
79 43 15
Whisky Oscar Yankee Sierra
Whisky Xray Yankee Zulu
 
// CoreFoundation (CF) mutable, dynamic
Juliet Golf India
Foxtrot Golf Hotel
 
// FB MDA - mutable, dynamic, multi-dimensional
Alpha Romeo Mike
Mike Delta Alpha
</pre>
 
=={{header|Gambas}}==
Line 2,331 ⟶ 4,114:
In Gambas, there is no need to dimension arrays. The first element of an array is numbered zero, and the DIM statement is optional and can be omitted:
 
<langsyntaxhighlight lang="gambas">
DIM mynumbers AS INTEGER[]
myfruits AS STRING[]
Line 2,340 ⟶ 4,123:
myfruits[0] = "apple"
myfruits[1] = "banana"
</syntaxhighlight>
</lang>
 
 
In Gambas, you DO need to dimension arrays. The first element of an array is numbered zero. The DIM statement is optional and can be omitted ONLY if defined as a Global variable.
 
'''[https://gambas-playground.proko.eu/?gist=5061d7f882a4768d212080e416c25e27 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sFixedArray As String[] = ["Rosetta", "code", "is", "a", "programming", "chrestomathy", "site"]
Dim sFixedArray1 As New String[10]
Dim iDynamicArray As New Integer[]
Dim siCount As Short
 
For siCount = 1 To 10
iDynamicArray.Add(siCount)
Next
 
sFixedArray1[5] = "Hello"
sFixedArray1[6] = " world!"
 
Print sFixedArray.Join(" ")
Print iDynamicArray[5]
 
Print sFixedArray1[5] & sFixedArray1[6]
 
End</syntaxhighlight>
Output:
<pre>
Rosetta code is a programming chrestomathy site
6
Hello world!
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Arrays are better called lists in GAP. Lists may have elements of mixed types, e$
v := [ 10, 7, "bob", true, [ "inner", 5 ] ];
# [ 10, 7, "bob", true, [ "inner", 5 ] ]
Line 2,387 ⟶ 4,200:
Add(v, "added");
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000, 8, 9, "added" ]</langsyntaxhighlight>
 
=={{header|Genie}}==
<syntaxhighlight lang="genie">[indent=4]
/*
Arrays, in Genie
 
valac --pkg=gee-0.8 arrays.gs
./arrays
*/
 
uses
Gee
 
init
/* allocate a fixed array */
var arr = new array of int[10]
 
/* initialized array of strings */
initialized:array of string = {"This", "is", "Genie"}
 
/* length is an array property */
stdout.printf("%d\n", arr.length)
 
/* read/write access via index */
arr[1] = 1
arr[9] = arr[1] + 8
stdout.printf("%d\n", arr[9])
 
print initialized[2]
 
/* Dynamic arrays are lists in Genie */
var dyn = new list of int
dyn.add(1)
dyn.add(8)
dyn.add(dyn[0]+dyn[1])
stdout.printf("dyn size: %d\n", dyn.size)
stdout.printf("dyn[2] : %d\n", dyn[2])</syntaxhighlight>
 
{{out}}
<pre>prompt$ valac --pkg=gee-0.8 arrays.gs && ./arrays
10
9
Genie
dyn size: 3
dyn[2] : 9</pre>
 
=={{header|GML}}==
Line 2,394 ⟶ 4,252:
====Example of Fixed Length Array====
Array containing a space (" "), "A", "B", and "C":
<langsyntaxhighlight GMLlang="gml">array[0] = ' '
array[1] = 'A'
array[2] = 'B'
array[3] = 'C'</langsyntaxhighlight>
 
====Example of Arbitrary Length Array====
Array containing the set of all natural numbers from 1 through k:
<langsyntaxhighlight GMLlang="gml">for(i = 0; i < k; i += 1)
array[i] = i + 1</langsyntaxhighlight>
 
===2-Dimensional Array Examples===
====Example of Fixed Length Array====
Array containing the multiplication table of 1 through 4 by 1 through 3:
<langsyntaxhighlight GMLlang="gml">array[1,1] = 1
array[1,2] = 2
array[1,3] = 3
Line 2,418 ⟶ 4,276:
array[3,2] = 6
array[3,3] = 9
array[3,4] = 12</langsyntaxhighlight>
 
====Example of Arbitrary Length Array====
Array containing the multiplication table of 1 through k by 1 through h:
<langsyntaxhighlight GMLlang="gml">for(i = 1; i <= k; i += 1)
for(j = 1; j <= h; j += 1)
array[i,j] = i * j</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,489 ⟶ 4,347:
// the cap()=10 array is no longer referenced
// and would be garbage collected eventually.
}</langsyntaxhighlight>
{{out}}
<pre>len(a) = 5
Line 2,510 ⟶ 4,368:
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.
 
<langsyntaxhighlight lang="golfscript">[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
10 a+puts # prepend 10 to a</langsyntaxhighlight>
 
Append and prepend works for integers or arrays only, since only in these cases the result is coerced to an array.
Line 2,520 ⟶ 4,378:
=={{header|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.
<langsyntaxhighlight lang="groovy">def aa = [ 1, 25, 31, -3 ] // list
def a = [0] * 100 // list of 100 zeroes
def b = 1..9 // range notation
Line 2,539 ⟶ 4,397:
d.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }
println()
e.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }</langsyntaxhighlight>
 
{{out}}
Line 2,555 ⟶ 4,413:
 
Here is a more interesting example showing a function that creates and returns a square identity matrix of order N:
<langsyntaxhighlight lang="groovy">def identity = { n ->
(1..n).collect { i -> (1..n).collect { j -> i==j ? 1.0 : 0.0 } }
}</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">def i2 = identity(2)
def i15 = identity(15)
 
Line 2,566 ⟶ 4,424:
i2.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }
println()
i15.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }</langsyntaxhighlight>
 
{{out}}
Line 2,590 ⟶ 4,448:
Groovy, like every other C-derived language in the known universe, uses ZERO-based array/list indexing.
 
<langsyntaxhighlight lang="groovy">def strings = ['Mary', 'had', 'a', 'little', 'lamb', ". It's", 'fleece', 'was', 'white', 'as', 'snow']
 
println strings
Line 2,600 ⟶ 4,458:
strings[10] = 'strawberries'
 
println strings</langsyntaxhighlight>
 
{{out}}
Line 2,609 ⟶ 4,467:
Negative indices are valid. They indicate indexing from the end of the list towards the start.
 
<syntaxhighlight lang ="groovy">println strings[-1]</langsyntaxhighlight>
 
{{out}}
Line 2,617 ⟶ 4,475:
Groovy lists can be resequenced and subsequenced by providing lists or ranges of indices in place of a single index.
 
<langsyntaxhighlight lang="groovy">println strings[0, 7, 2, 3, 8]
println strings[0..4]
println strings[0..3, -5]</langsyntaxhighlight>
 
{{out}}
Line 2,631 ⟶ 4,489:
Graphical User Interface Support Script does not have variables or array storage of its own. However, it can make use of installed applications, so it is possible to utilize an installed spreadsheet application to create and manipulate arrays. Here we assume that a spreadsheet is installed and create an array containing three names:
 
<langsyntaxhighlight GUISSlang="guiss">Start,Programs,Lotus 123,Type:Bob[downarrow],Kat[downarrow],Sarah[downarrow]</langsyntaxhighlight>
 
=={{header|GW-BASIC}}==
Line 2,638 ⟶ 4,496:
(GW-BASIC User's Guide)
 
<langsyntaxhighlight lang="qbasic">10 DATA 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
20 DIM A(9) ' Array with size 10 (9 is maximum subscript), all elements are set to 0
30 FOR I = 0 TO 9
Line 2,646 ⟶ 4,504:
70 A(4) = 400 ' Set 4th element of array
80 PRINT A(4)
</syntaxhighlight>
</lang>
 
=={{header|Halon}}==
<syntaxhighlight lang="halon">$array = [];
$array[] = 1;
$array["key"] = 3;
$array[0] = 2;
echo $array[0];
echo $array["key"];</syntaxhighlight>
 
=={{header|Harbour}}==
Harbour arrays aren't divided to fixed-length and dynamic. Even if we declare it with a certain dimensions, it can be resized in the same way as it was created dynamically. The first position in an array is 1, not 0, as in some other languages.
<langsyntaxhighlight lang="visualfoxpro"> // Declare and initialize two-dimensional array
local arr1 := { { "NITEM", "N", 10, 0 }, { "CONTENT", "C", 60, 0 } }
// Create an empty array
Line 2,660 ⟶ 4,529:
 
// Array can be dynamically resized:
arr4 := ASize( arr4, 80 )</langsyntaxhighlight>
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
<langsyntaxhighlight lang="visualfoxpro">// Adding new item to array, its size is incremented
AAdd( arr1, { "LBASE", "L", 1, 0 } )
// Delete the first item of arr3, The size of arr3 remains the same, all items are shifted to one position, the last item is replaced by Nil:
ADel( arr1, 1 )
// Assigning a value to array item
arr3[ 1, 1, 1 ] := 11.4</langsyntaxhighlight>
Retrieve items of an array:
<langsyntaxhighlight lang="visualfoxpro"> x := arr3[ 1, 10, 2 ]
// The retrieved item can be nested array, in this case it isn't copied, the pointer to it is assigned
</syntaxhighlight>
</lang>
There is a set of functions to manage arrays in Clipper, including the following:
<langsyntaxhighlight lang="visualfoxpro">// Fill the 20 items of array with 0, starting from 5-th item:
AFill( arr4, 0, 5, 20 )
// Copy 10 items from arr4 to arr3[ 2 ], starting from the first position:
Line 2,679 ⟶ 4,548:
// Duplicate the whole or nested array:
arr5 := AClone( arr1 )
arr6 := AClone( arr1[ 3 ] )</langsyntaxhighlight>
 
=={{header|Haskell}}==
You can read all about Haskell arrays [http://haskell.org/haskellwiki/Arrays here]. The following example is taken from that page:
<langsyntaxhighlight lang="haskell">import Data.Array.IO
 
main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)
Line 2,689 ⟶ 4,558:
writeArray arr 1 64
b <- readArray arr 1
print (a,b)</langsyntaxhighlight>
 
=={{header|hexiscript}}==
<syntaxhighlight lang="hexiscript">let a arr 2 # fixed size
let a[0] 123 # index starting at 0
let a[1] "test" # can hold different types
 
println a[1]</syntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: n = 3, Astat(n), Bdyn(1, 1)
 
Astat(2) = 2.22222222
Line 2,702 ⟶ 4,578:
 
ALIAS(Astat, n-1, last2ofAstat, 2)
WRITE(ClipBoard) last2ofAstat ! 2.22222222 0 </langsyntaxhighlight>
 
=={{header|IHolyC}}==
<syntaxhighlight lang="holyc">// Create an array of fixed size
<lang i>software {
U8 array[10] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
var a = []
 
a & 2
// The first element of a HolyC array is indexed at 0. To set a value:
print(a[0]) //Outputs 2
array[0] = 123;
 
a[0] = 4
// Access an element
Print("%d\n", array[0]);</syntaxhighlight>
print(a[0]) //Outputs 4
}</lang>
 
==Icon and Unicon==
==={{header|Icon}}===
<langsyntaxhighlight lang="icon">record aThing(a, b, c) # arbitrary object (record or class) for illustration
 
procedure main()
Line 2,814 ⟶ 4,689:
S := A[-8 -: -3] # S is [30, 40, 50]
S := A[-5 +: -3] # S is [30, 40, 50]
end</langsyntaxhighlight>
 
==={{header|Unicon}}===
This Icon solution works in Unicon.
<langsyntaxhighlight lang="unicon"># Unicon provides a number of extensions
# insert and delete work on lists allowing changes in the middle
# possibly others
</syntaxhighlight>
</lang>
{{improve|Unicon|Need code examples for these extensions}}
 
=={{header|i}}==
<syntaxhighlight lang="i">main
//Fixed-length arrays.
f $= array.integer[1]()
f[0] $= 2
print(f[0])
 
//Dynamic arrays.
d $= list.integer()
d[+] $= 2
print(d[1])
}</syntaxhighlight>
 
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">> (var my-list [1 2 3 4 5]) ;syntactic sugar
[1 2 3 4 5]
 
> (var my-list (vec 1 2 3 4 5))
[1 2 3 4 5]
 
> my-list
[1 2 3 4 5]
 
> (3 my-list) ;fourth element
4
 
> (-1 my-list) ;last element
5
 
> (append my-list 100)
[1 2 3 4 5 100]
 
> my-list ;variables are immutable so my-list cannot be changed without being redefined
[1 2 3 4 5]</syntaxhighlight>
 
=={{header|Io}}==
<langsyntaxhighlight Iolang="io">foo := list("foo", "bar", "baz")
foo at(1) println // bar
foo append("Foobarbaz")
foo println
foo atPut(2, "barbaz") // baz becomes barbaz</langsyntaxhighlight>
 
<pre>Io> foo := list("foo", "bar", "baz")
Line 2,848 ⟶ 4,758:
=={{header|J}}==
In J, all data occurs in the form of rectangular (or generally [[wp:Hyperrectangle|orthotopic]]) arrays. This is true for both named and anonymous data.
<langsyntaxhighlight lang="j"> 1 NB. a stand-alone scalar value is an array without any axis
1
NB. invoking any array produces that array as the result
Line 2,875 ⟶ 4,785:
Xbcde
fXhij
klXno</langsyntaxhighlight>
Because arrays are so important in J, a large portion of the language applies to this topic.
 
Note also that J's arrays are (with some obscure exceptions) "constants". We can append to an existing array, creating a new array, but if we kept a reference to the original it would have remained unchanged.
 
<syntaxhighlight lang="j"> A=: 7 11
B=: A, 9 5
B
7 11 9 5
A
7 11</syntaxhighlight>
 
Thus, in recent versions of J, special syntax was introduced to refer to a value while discarding the reference: <syntaxhighlight lang="j"> A=: 2 4 6 8
B=: A_:, 1 3 9 5
B
2 4 6 8 1 3 9 5
A
|value error: A</syntaxhighlight>
 
=={{header|Java}}==
In Java you can create an immutable array of any ''Object'' or primitive data-type by appending the declaring type with square brackets, [ and ].
<lang java>int[] array = new int[10]; //optionally, replace "new int[10]" with a braced list of ints like "{1, 2, 3}"
<syntaxhighlight lang="java">
array[0] = 42;
String[] strings;
System.out.println(array[3]);</lang>
int[] values;
Dynamic arrays can be made using <code>List</code>s. Leave generics out for Java versions under 1.5:
</syntaxhighlight>
<lang java5>ArrayList <Integer> list = new ArrayList <Integer>();//optionally add an initial size as an argument
Alternately, you could place the brackets after the declaring variable name, although this is discouraged as it aspects the name rather than the type.
list.add(5);//appends to the end of the list
<syntaxhighlight lang="java">
list.add(1, 6);//assigns the element at index 1
String strings[];
System.out.println(list.get(0));</lang>
int values[];
</syntaxhighlight>
Initialization can appear during the declaration, or after.
<syntaxhighlight lang="java">
String[] strings = new String[] { "rosetta", "code" };
int[] values = new int[] { 1, 2, 3 };
</syntaxhighlight>
<syntaxhighlight lang="java">
String[] strings;
strings = new String[] { "rosetta", "code" };
int[] values;
values = new int[] { 1, 2, 3 };
</syntaxhighlight>
If your arrays contents are more dynamic, and known only at runtime, you can alternately specify the array size by adding it to the assigned type's square brackets.
<syntaxhighlight lang="java">
String[] strings = new String[2];
int[] values = new int[3];
</syntaxhighlight>
To access an array element you, again, use the square-bracket syntax, specifying the element's index within it.<br />
Java indices are 0-based, so, for example, element 1 is at index 0.
<syntaxhighlight lang="java">
String string = strings[0];
int value = values[2];
</syntaxhighlight>
Here is a basic demonstration of using an array.
<syntaxhighlight lang="java">
String[] strings = new String[2];
strings[0] = "rosetta";
strings[1] = "code";
String string = strings[0] + " " + strings[1];
</syntaxhighlight>
If you printed ''string'' to the standard-out, you would get the following.
<pre>
rosetta code
</pre>
Java offers the ''Arrays'' class, which provides numerous array-related operations.<br />
A useful option is the ''Arrays.fill'' method, which can be used to initialize each element to a specified value.
<syntaxhighlight lang="java">
int[] values = new int[10];
Arrays.fill(values, 100);
</syntaxhighlight>
Additionally, you can print the contents of an array using the ''Arrays.toString'' method.
<syntaxhighlight lang="java">
Arrays.toString(values);
</syntaxhighlight>
If you printed ''values'' to the standard-out, you'd get the following.
<syntaxhighlight lang="java">
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
</syntaxhighlight>
<br />
Java also offers a dynamic, mutable array under the Java Collections Framework ''List'' and ''Deque'' interfaces.<br />
Both which provide a substantial amount of implementing classes, for various types of dynamic array related tasks.<br />
The most logical, for this demonstration, would be the ''ArrayList'' and ''ArrayDeque''.<br /><br />
The ''ArrayList'' declaration is slightly different than that of the array, as you are simply calling the constructor of a class.<br />
We'll use ''List'' as our declaring type, since, as with most interfaces, it's more logical to specify it as the declaring type during the instantiation of any implementing type.<br />
Immediately after the declaring type you'll use the 'diamond operators', &lt; and &gt;, with the data type of the array specified within.
<syntaxhighlight lang="java">
List<String> strings;
List<Integer> values;
</syntaxhighlight>
Similar to an array, the initialization can appear during the declaration or after.<br />
Note, the ''ArrayList'' 'diamond-operator' does not require the declared-type, as it's inferred by the declaring-type.
<syntaxhighlight lang="java">
List<String> strings = new ArrayList<>();
List<Integer> values = new ArrayList<>();
</syntaxhighlight>
Adding an element is done via the ''List.add'' method.
<syntaxhighlight lang="java">
strings.add("rosetta");
strings.add("code");
values.add(1);
values.add(2);
values.add(3);
</syntaxhighlight>
Additionally, you could specify an index at the ''List.add'' method, which will insert the element at the index, shifting the current element at that index, and all subsequent elements to the right by 1.
<syntaxhighlight lang="java">
strings.add("code");
strings.add(0, "rosetta");
</syntaxhighlight>
''List.set'' is used for mutating an already existing element.
<syntaxhighlight lang="java">
strings.set(0, "ROSETTA");
strings.set(1, "CODE");
</syntaxhighlight>
It's worth noting that Java also offers a ''Vector'' class, which is nearly similar to the ''ArrayList'' class except it should be used in multi-threaded situations, as ''ArrayList'' will produced concurrency issues.<br /><br />
The ''ArrayDeque'' is also another option for dynamic, mutable array situations, and provides a LIFO, "Last In First Out", operation for its elements.<br />
A LIFO pattern can be assimilated to a stack of plates at a buffet, as the most recent plate to be placed on the stack is the first to be taken.<br />
You declare and instantiate an ''ArrayDeque'' in the same manner as an ''ArrayList'', using the 'diamond-operators'.
<syntaxhighlight lang="java">
Deque<String> strings = new ArrayDeque<>();
</syntaxhighlight>
There are numerous methods within the ''Deque'' class for accessing and mutating the data.<br />
For this task, I'll use the most generic and logical to a LIFO pattern.<br />
To add an element you use the ''Deque.push'' method.
<syntaxhighlight lang="java">
strings.push("code");
strings.push("rosetta");
</syntaxhighlight>
To remove an item you use the ''Deque.pop'' method.<br />
Elements of a ''Deque'' are not index based.
<syntaxhighlight lang="java">
strings.pop();
</syntaxhighlight>
 
=={{header|JavaScript}}==
JavaScript arrays are Objects that inherit from Array prototype and have a special length property that is always one higher than the highest non–negative integer index. Methods inherited from Array.prototype are mostly generic and can be applied to other objects with a suitable length property and numeric property names.
Note that if the Array constructor is provided with one argument, it is treated as specifying the length of the new array, if more than one argument is supplied, they are treated as members of the new array.
<langsyntaxhighlight lang="javascript">// Create a new array with length 0
var myArray = new Array();
 
Line 2,912 ⟶ 4,942:
// Elisions are supported, but are buggy in some implementations
var y = [0,1,,]; // length 3, or 4 in buggy implementations
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
jq arrays have the same syntax as JSON arrays, and there are similarities with Javascript arrays. For example, the index origin is 0; and if a is an array and if n is an integer less than the array's length, then a[n] is the n-th element. The length of any array, a, can be ascertained using the length filter: a|length.
 
There are, however, some interesting extensions, e.g. <tt>[][4] = null</tt> creates an array of length 5 as explained below.<langsyntaxhighlight lang="jq"># Create a new array with length 0
[]
 
Line 2,952 ⟶ 4,982:
a[1:] # => [1,2,3,4]
a[2:4] # => [2,3]
a[4:2] # null</langsyntaxhighlight>
 
=={{header|Jsish}}==
From Javascript, with the differences that Jsi treats ''typeof [elements]'' as "array", not "object".
<syntaxhighlight lang="javascript">/* Arrays in Jsi */
// Create a new array with length 0
var myArray = new Array();
;myArray;
 
// In Jsi, typeof [] is "array". In ECMAScript, typeof [] is "object"
;typeof [];
// Create a new array with length 5
var myArray1 = new Array(5);
;myArray1;
// Create an array with 2 members (length is 2)
var myArray2 = new Array("Item1","Item2");
;myArray2;
;myArray2.length;
// Create an array with 2 members using an array literal
var myArray3 = ["Item1", "Item2"];
;myArray3;
// Assign a value to member [2] (length is now 3)
myArray3[2] = 5;
;myArray3;
;myArray3.length;
var x = myArray3[2] + myArray3.length; // 8
;x;
// You can also add a member to an array with the push function (length is now 4)
myArray3.push('Test');
;myArray3;
;myArray3.length;
 
// Empty array entries in a literal is a syntax error, elisions not allowed
//var badSyntax = [1,2,,4];
 
 
/*
=!EXPECTSTART!=
myArray ==> []
typeof [] ==> array
myArray1 ==> [ undefined, undefined, undefined, undefined, undefined ]
myArray2 ==> [ "Item1", "Item2" ]
myArray2.length ==> 2
myArray3 ==> [ "Item1", "Item2" ]
myArray3 ==> [ "Item1", "Item2", 5 ]
myArray3.length ==> 3
x ==> 8
myArray3 ==> [ "Item1", "Item2", 5, "Test" ]
myArray3.length ==> 4
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish -u arrays.jsi
PASS] arrays.jsi</pre>
 
=={{header|Julia}}==
Julia has both heterogeneous arrays and typed arrays.
<pre>julia> A = cellVector(undef, 3) # create an heterogeneous 1-D array of length 3
3-element ArrayVector{Any,1}:
#undef
#undef
Line 2,982 ⟶ 5,072:
in push! at array.jl:488
 
julia> ['a':'c'...] # type inference
3-element ArrayVector{Char,1}:
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
'a'
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
'b'
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)</pre>
'c'</pre>
 
=={{header|KonsolScript}}==
<langsyntaxhighlight KonsolScriptlang="konsolscript">//creates an array of length 3
Array:New array[3]:Number;
 
Line 2,999 ⟶ 5,089:
array[0] = 5; //assign value
Konsol:Log(array[0]) //retrieve value and display
}</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">fun main(x: Array<String>) {
var a = arrayOf(1, 2, 3, 4)
println(a.asList())
Line 3,008 ⟶ 5,098:
println(a.asList())
println(a.reversedArray().asList())
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3, 4]
Line 3,016 ⟶ 5,106:
=={{header|LabVIEW}}==
{{VI snippet}}<br/>[[File:LabVIEW Arrays.png]]
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
// Create a new array with length 0
{def myArray1 {A.new}}
-> []
// Create an array with 2 members (length is 2)
{def myArray2 {A.new Item1 Item2}}
-> [Item1,Item2]
// Edit a value in an array
{def myArray3 {A.new 1 2 3}}
{A.set! 1 hello {myArray3}}
-> [1,hello,3]
 
// Add a value at the head of an array
{def myArray4 {A.new 1 2 3}}-> myArray4
{A.addfirst! hello {myArray4}}
-> [hello,1,2,3]
// Add a value at the tail of an array
{def myArray5 {A.new 1 2 3}}
{A.addlast! hello {myArray5}}
-> [1,2,3,hello]
 
and so on...
</syntaxhighlight>
 
=={{header|lang5}}==
<langsyntaxhighlight lang="lang5">[]
1 append
['foo 'bar] append
2 reshape
0 remove 2 swap 2 compress collapse .</langsyntaxhighlight>
 
=={{header|langur}}==
Langur uses 1-based indexing.
 
<syntaxhighlight lang="langur">var .a1 = [1, 2, 3, "abc"]
val .a2 = series 4..10
val .a3 = .a1 ~ .a2
 
writeln "initial values ..."
writeln ".a1: ", .a1
writeln ".a2: ", .a2
writeln ".a3: ", .a3
writeln()
 
.a1[4] = .a2[4]
writeln "after setting .a1[4] = .a2[4] ..."
writeln ".a1: ", .a1
writeln ".a2: ", .a2
writeln ".a3: ", .a3
writeln()
 
writeln ".a2[1]: ", .a2[1]
writeln()
 
writeln "using index alternate ..."
writeln ".a2[5; 0]: ", .a2[5; 0]
writeln ".a2[10; 0]: ", .a2[10; 0]
writeln()</syntaxhighlight>
 
{{out}}
<pre>initial values ...
.a1: [1, 2, 3, "abc"]
.a2: [4, 5, 6, 7, 8, 9, 10]
.a3: [1, 2, 3, "abc", 4, 5, 6, 7, 8, 9, 10]
 
after setting .a1[4] = .a2[4] ...
.a1: [1, 2, 3, 7]
.a2: [4, 5, 6, 7, 8, 9, 10]
.a3: [1, 2, 3, "abc", 4, 5, 6, 7, 8, 9, 10]
 
.a2[1]: 4
 
using index alternate ...
.a2[5; 0]: 8
.a2[10; 0]: 0
</pre>
 
=={{header|Lasso}}==
Line 3,028 ⟶ 5,192:
Lasso Array [http://lassoguide.com/operations/containers.html?#array] objects store zero or more elements and provide random access to those elements by position. Positions are 1-based integers. Lasso Arrays will grow as needed to accommodate new elements. Elements can be inserted and removed from arrays at any position. However, inserting an element anywhere but at the end of an array results in all subsequent elements being moved down.
 
<langsyntaxhighlight Lassolang="lasso">// Create a new empty array
local(array1) = array
Line 3,060 ⟶ 5,224:
 
// Insert item at specific position
#array1->insert('0',1) // 0, a, c, c, z</langsyntaxhighlight>
 
=== Static Arrays ===
Lasso also supports Static Arrays[http://lassoguide.com/operations/containers.html#staticarray]. A Lasso staticarray is a container object that is not resizable. Staticarrays are created with a fixed size. Objects can be reassigned within the staticarray, but new positions cannot be added or removed.
 
<langsyntaxhighlight Lassolang="lasso">// Create a staticarray containing 5 items
local(mystaticArray) = staticarray('a','b','c','d','e')
 
Line 3,075 ⟶ 5,239:
 
// Create an empty static array with a length of 32
local(mystaticArray) = staticarray_join(32,void)</langsyntaxhighlight>
 
=={{header|Latitude}}==
 
Like everything in Latitude, arrays are simply objects. In particular, arrays store their elements in numerical slots rather than traditional symbolic ones. The translation scheme used to store them enables constant-time push and pop operations on either side of the array.
<syntaxhighlight lang="latitude">;; Construct an array.
foo := [1, 2, 3].
 
;; Arrays can also be constructed explicitly.
bar := Array clone.
bar pushBack (1).
bar pushBack (2).
bar pushBack (3).
 
;; Accessing values.
println: foo nth (2). ;; 3
 
;; Mutating values.
foo nth (1) = 99.
println: foo. ;; [1, 99, 3]
 
;; Appending to either the front or the back of the array.
foo pushBack ("back").
foo pushFront ("front").
println: foo. ;; ["front", 1, 99, 3, "back"]
 
;; Popping from the front or back.
println: foo popBack. ;; "back"
println: foo popBack. ;; 3
println: foo popFront. ;; "front"
println: foo. ;; [1, 99]</syntaxhighlight>
 
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
myArray is list of numbers
 
procedure:
# add elements
push 1 to myArray
push 2 to myArray
push 3 to myArray
 
# access elements
display myArray:0 lf
 
# store elements
store 99 in myArray:0
 
# remove elements
remove element at 1 from myArray
delete last element of myArray
 
# clear array
clear myArray
</syntaxhighlight>
 
=={{header|LFE}}==
 
Using the LFE REPL, you can explore arrays in the following manner:
<langsyntaxhighlight lang="lisp">
; Create a fixed-size array with entries 0-9 set to 'undefined'
> (set a0 (: array new 10))
Line 3,133 ⟶ 5,351:
in (array get 2)
 
</syntaxhighlight>
</lang>
 
 
 
=={{header|Liberty BASIC}}==
Line 3,148 ⟶ 5,364:
DATA is READ into variables. It cannot be READ directly into arrays.
<br>To fill arrays with DATA items, first READ the item into a variable, then use that variable to fill an index of the array.
<syntaxhighlight lang="lb">
<lang lb>
dim Array(10)
 
Line 3,163 ⟶ 5,379:
print Array( 0), Array( 10)
 
</syntaxhighlight>
</lang>
 
=={{header|LIL}}==
LIL, like Tcl, doesn't manage arrays as such. Indexed lists are used in LIL. The '''list''' command creates a list from the remaining arguments in the statement. The '''index LIST NUM''' command returns the NUM'th item in the list, starting from zero. Lists are copied on assignment. The array-ish functions and operators would be
 
* index LIST NUM, returning the NUM'th item
* count LIST, returning the number of items in the list
* indexof LIST VAL, returning the offset from zero position of where VAL is found in LIST, or an empty string
* filter VARNAME LIST EXPRESSION, returning a new list of filtered items matching EXPRESSION, with the value under test in VARNAME.
* list ..., creating a list from remaining word tokens in the statement.
* append LIST VAL (list VAL values are appended as single items to the given LIST)
* slice LIST FROM-NUM TO-NUM
* foreach VARNAME LIST CODE
* charat STRING NUM, indexing a string for characters
* codeat STRING NUM, indexing a string for the character byte code
* lmap LIST VARNAME..., maps the list items to the given variable names, in the order given.
 
For filter and foreach, the VARNAME fields are optional, LIL creates defaults inside the code block of '''x''' for filter and '''i''' for foreach if user names are not given.
 
<syntaxhighlight lang="tcl"># (not) Arrays, in LIL
set a [list abc def ghi]
set b [list 4 5 6]
print [index $a 0]
print [index $b 1]
print [count $a]
append b [list 7 8 9]
print [count $b]
print $b</syntaxhighlight>
 
{{out}}
<pre>prompt$ lil arrays.lil
abc
5
3
4
4 5 6 {7 8 9}</pre>
 
By and large, LIL is NOT an array processing language; LIL is a Little Interpreted Language built to deal with strings, commands, and substitutions.
 
If need arose for tight array processing, LIL is very easy to embed in C applications and extend with new functions that run at speed. If need arises. LIL is small enough, under 4K of source lines, total, that adding extra commands for LIL scripting using C code is quite approachable. If a developer is more comfortable in Pascal, fplil.pas is only 86K characters of source.
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">a = [1,2] -- or: a = list(1,2)
put a[2] -- or: put a.getAt(2)
-- 2
a.append(3)
put a
-- [1, 2, 3]
a.deleteAt(2)
put a
-- [1, 3]
a[1] = 5 -- or: a.setAt(1, 5)
put a
-- [5, 3]
a.sort()
put a
-- [3, 5]</syntaxhighlight>
 
In addition to the 'list' type shown above, for arrays of bytes (i.e. integers between 0 and 255) there is also the bytearray data type:
 
<syntaxhighlight lang="lingo">ba = bytearray(2, 255) -- initialized with size 2 and filled with 0xff
put ba
-- <ByteArrayObject length = 2 ByteArray = 0xff, 0xff >
ba[1] = 1
ba[2] = 2
ba[ba.length+1] = 3 -- dynamically increases size
put ba
-- <ByteArrayObject length = 3 ByteArray = 0x1, 0x2, 0x3 >
ba[1] = 5
put ba
-- <ByteArrayObject length = 3 ByteArray = 0x5, 0x2, 0x3 ></syntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="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;</langsyntaxhighlight>
 
=={{header|Little}}==
Arrays in Little are list of values of the same type and they grow dynamically.
<langsyntaxhighlight Clang="c">String fruit[] = {"apple", "orange", "Pear"}</langsyntaxhighlight>
 
They are zero-indexed. You can use END to get the last element of an array:
<syntaxhighlight lang="c">
<lang C>
puts(fruit[0]);
puts(fruit[1]);
puts(fruit[END]);
fruit[END+1] = "banana";</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
 
=={{header|LOLCODE}}==
<syntaxhighlight lang="lolcode">HAI 1.4
BTW declaring array
I HAS A array ITZ A BUKKIT
BTW store values in array
array HAS A one ITZ 1
array HAS A two ITZ 2
array HAS A three ITZ 3
array HAS A string ITZ "MEOW"
OBTW
there is no way to get an element of an array at a specified index in LOLCODE
therefore, you can't really iterate through an array
TLDR
BTW get the element of array
VISIBLE array'Z one
VISIBLE array'Z two
VISIBLE array'Z three
VISIBLE array'Z string
KTHXBYE</syntaxhighlight>
 
=={{header|LSE64}}==
<langsyntaxhighlight lang="lse64">10 myArray :array
0 array 5 [] ! # store 0 at the sixth cell in the array
array 5 [] @ # contents of sixth cell in array</langsyntaxhighlight>
 
=={{header|LSL}}==
LSL does not have Arrays, but it does have [http://wiki.secondlife.com/wiki/List lists] which can function similar to a one dimensional ArrayList in Java or C#.
<syntaxhighlight lang="lsl">
<lang LSL>
default {
state_entry() {
Line 3,225 ⟶ 5,531:
llSay(0, "Deserialize a string CSV List\n(note that all elements are now string datatype)\nList=["+llList2CSV(lst)+"]\n");
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,257 ⟶ 5,563:
=={{header|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.
<langsyntaxhighlight lang="lua">l = {}
l[1] = 1 -- Index starts with 1, not 0.
l[0] = 'zero' -- But you can use 0 if you want
Line 3,263 ⟶ 5,569:
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</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Here present Arrays of type variant (can be any type, object, pointer to object), and arrays of structures (unsigned numbers plus double and single, and strings including pointers to BSTR).
We can copy multiple items from an array to another array (ore the same) with statement Stock. We can copy from memory to strings and place them to other address.
 
<syntaxhighlight lang="m2000 interpreter">
Module CheckArray {
\\ Array with parenthesis in name
Dim A(10)=1
Global B(10)=1
For This {
Local A(10)=5
Print A(4)=5
}
Print A(4)=1
\\ Auto Array
M=(1,2,3,4,5)
Link M to M()
Print M(2)=3
Return M, 0:=100, 5-4:=300
\\ Retrieve an Element of an Array
k=Each(M, 1, 2)
\\ print 100 300
While k { Print Array(k),}
Print
Print Array(M, 2)=3
Print Array("M", 2)=3
Print Array(B(), 1)=1
\\ arrays are containers for every value/object/pointer
B(0):="Hello",100,"Good Morning", 200
\\ using set to make B$() global too
Set Link B() to B$()
Print B$(0), B(1), B$(2), B(3)
Swap B(0), B(2)
Swap B(1), B(3)
Print B$(0), B(1), B$(2), B(3)
Print B()
\\ Reduce B() to 4 elements - and change dimensions
\\ we have to redim the global array, using set to send line to console
\\ all globals are part of level 0, at console input.
Set Dim B(4)
Module CheckGlobal {
Print B$(0), B(1), B$(2), B(3)
}
CheckGlobal
Print B()
Dim BB(4)
\\ Copy 4 items from B() to BB(), from B(0), to BB(0)
Stock B(0) keep 4, BB(0)
Link BB() to BB$()
Print BB$(0), BB(1), BB$(2), BB(3)
\\ Arrays of structures in Buffers
Structure TwoByte {
{
ab as integer
}
a as byte
b as byte
}
Print Len(TwoByte) = 2
\ Use clear to clear memory
\\ Mem is a pointer to a Buffer object
Buffer Clear Mem as TwoByte*20
Print Len(Mem)=40
Return Mem, 0!ab:=0xFFAA
Print Eval(Mem, 0!a)=0xAA, Eval(Mem, 0!b)=0xFF
Return Mem, 0!b:=0xF2
Hex Eval(Mem,0!ab) ' print 0xF2AA
\\ Redim with preserve
Buffer Mem as TwoByte*40
\\ copy 40 bytes at index 20 (40 bytes from start)
Return Mem, 20:=Eval$(Mem, 0, 20*2)
Hex Eval(Mem,20!ab) ' print 0xF2AA
A(3)=Mem
Hex Eval(A(3),20!ab) ' print 0xF2AA
\\ now Mem change pointer
Clear Mem
Print Len(Mem)
\\ old Mem is in A(3)
Hex Eval(A(3),20!ab) ' print 0xF2AA
\\ we can change
Buffer Clear Mem as Integer * 200
Print Len(Mem)=400
Return Mem, 0:=Eval$(A(3), 0, 80)
Hex Eval(Mem,20) ' print 0xF2AA
\\ change type without use of clear
Buffer Mem as TwoByte * 200
Hex Eval(Mem,20!ab) ' print 0xF2AA
}
CheckArray
</syntaxhighlight>
===Passing Arrays By Reference===
By default arrays passed by value. Here in make() we read reference in a variable A, which interpreter put then pointer to array, so it is a kind of reference (like in C). Using & we have normal reference. A ++ operator in a pointer of array add one to each element.
<syntaxhighlight lang="m2000 interpreter">
Dim a(10)=1
Print a() ' 1 1 1 1 1 1 1 1 1 1
make(a())
Print a() ' 2 2 2 2 2 2 2 2 2 2
make2(&a())
Print a() ' 3 3 3 3 3 3 3 3 3 3
Sub make(A)
A++
End Sub
Sub make2(&a())
A=A()
A++
End Sub
</syntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">#defining an array of a certain length
a := Array (1..5);
a := [ 0 0 0 0 0 ]
Line 3,282 ⟶ 5,699:
a := [ 9 2 3 4 5 6 ]
a[7] := 7;
Error, Array index out of range</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">a = Array[Sin, 10]
a[[1]]
Delete[a, 2]</langsyntaxhighlight>
{{out}}
<pre>{Sin[1],Sin[2],Sin[3],Sin[4],Sin[5],Sin[6],Sin[7],Sin[8],Sin[9],Sin[10]}
Line 3,296 ⟶ 5,713:
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.
 
<langsyntaxhighlight MATLABlang="matlab">>> a = [1 2 35] %Declaring a vector (i.e. one-dimensional array)
 
a =
Line 3,356 ⟶ 5,773:
 
2 35 10
7 9 42</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* Declare an array, subscripts run from 0 to max value */
array(a, flonum, 20, 20, 3)$
 
Line 3,383 ⟶ 5,800:
 
listarray(b);
/* [1000, 3/4] */</langsyntaxhighlight>
 
=={{header|Mercury}}==
 
Mercury's arrays are a mutable non-functional type, and therefore are slightly more troublesome than functional types to A) accept as parameters to predicates, and B) involve in higher-order code, and C) include as a member of a composite data type. All of this is still very possible, but it requires an understanding of Mercury's variable instantiation system, as you can't just have 'in' and 'out' modes for parameters that involve arrays. Mercury has a 'bt_array' module with performance characteristics very similar to that of arrays, but which is a functional type and therefore is easier to work with. Especially if you're just starting out with Mercury, going with bt_array can be a big win for 'whippitupitude'.
 
<syntaxhighlight lang="mercury">:- module array_example.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module array, int.
:- use_module exception.
 
:- type example_error ---> impossible.
 
main(!IO) :-
some [!A] ( % needed to introduce a state variable not present in the head
% Create an array(int) of length 10, with initial values of 0
array.init(10, 0, !:A),
 
% create an empty array (with no initial value)
% since the created array is never used, type inference can't tell what
% kind of array it is, and there's an unresolved polymorphism warning.
array.make_empty_array(_Empty),
 
% resize our first array, so that we can then set its 17th member
% new values are set to -1
array.resize(20, -1, !A),
!A ^ elem(17) := 5,
 
% Mercury data structures tend to have deterministic (exception thrown
% on error), semideterministic (logical failure on error), and unsafe
% (undefined behavior on error) access methods.
array.lookup(!.A, 5, _), % det
( if array.semidet_lookup(!.A, 100, _) then % semidet
exception.throw(impossible)
else
true
),
array.unsafe_lookup(!.A, 5, _), % could cause a segfault on a smaller array
 
% output: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, 5, -1, -1])
io.print_line(!.A, !IO),
 
plusminus(2, 0, !A),
 
% output: array([2, -2, 2, -2, 2, -2, 2, -2, 2, -2, 1, -3, 1, -3, 1, -3, 1, 3, 1, -3])
io.print_line(!.A, !IO)
).
 
% Sample predicate operating on an array.
% Note the array_* modes instead of in/out.
:- pred plusminus(int, int, array(int), array(int)).
:- mode plusminus(in, in, array_di, array_uo) is det.
plusminus(N, I, !A) :-
( if array.semidet_lookup(!.A, I, X) then
!A ^ unsafe_elem(I) := X + N,
plusminus(-N, I+1, !A)
else
true
).</syntaxhighlight>
 
=={{header|MiniScript}}==
Lists and arrays are synonymous in MiniScript.
 
Operations:
<pre>
+ list concatenation
* replication (i.e. repeat the list some number of times)
/ division (get some fraction of a list)
==, != comparison (for equality)
[i] get/set item i (first item is 0)
[i:j] get sublist ("slice") from i up to j
</pre>
 
Slicing:
<pre>
x = ["a", 42, 3.14, 7, "hike"]
x[0] "a" (first item)
x[1] 42 (second item)
x[-1] "hike" (last item)
x[-2] 7 (next-to-last item)
x[1:-1] [42, 3.14, 7] (everything from the second up to the last item)
x[1:] [42, 3.14, 7, "hike"] (everything from the second item to the end)
x[:-1] ["a", 42, 3.14, 7] (everything up to the last item)
</pre>
 
Example:
<syntaxhighlight lang="miniscript">arr = ["a", 1, 3]
print arr[0]
 
arr.push "x"
print arr.pop</syntaxhighlight>
 
=={{header|MIPS Assembly}}==
<syntaxhighlight lang="mips">
.data
array: .word 1, 2, 3, 4, 5, 6, 7, 8, 9 # creates an array of 9 32 Bit words.
 
.text
main: la $s0, array
li $s1, 25
sw $s1, 4($s0) # writes $s1 (25) in the second array element
# the four counts the bytes after the beginning of the address. 1 word = 4 bytes, so 4 accesses the second element
lw $s2, 20($s0) # $s2 now contains 6
li $v0, 10 # end program
syscall
</syntaxhighlight>
 
=={{header|Modula-2}}==
Same as described for Modula-3
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">VAR astaticArray: ARRAY [1..10] OF INTEGER;</langsyntaxhighlight>
Defines ana static array of 10 elements, indexed 1 through 10.
 
ArraysStatic arrays can also be given initial values:
<langsyntaxhighlight 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. *)</langsyntaxhighlight>
 
Open (dynamic) arrays can be be defined by creating a reference to an array of an unspecified size:
To retrieve an element:
<syntaxhighlight lang ="modula3">VARTYPE arrTOpenIntArray := REF ARRAY [1..3] OF INTEGER {1, 2, 3};
VAR myVar openArray:= a[2]TOpenIntArray;</langsyntaxhighlight>
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:
<syntaxhighlight lang="modula3">openArray := NEW(TOpenIntArray, 10);</syntaxhighlight>
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:
<syntaxhighlight lang="modula3"> VAR
staticArraySize := NUMBER(staticArray);
staticArrayElement := staticArray[4];
 
openArraySize := NUMBER(openArray^); (* Note the dereference. *)
openArrayElement := openArray[9];</syntaxhighlight>
 
<syntaxhighlight lang="modula3">staticArray[4] := 100;
openArray[1] := 200;</syntaxhighlight>
 
=={{header|Monte}}==
 
<langsyntaxhighlight Montelang="monte">var myArray := ['a', 'b', 'c','d']</langsyntaxhighlight>
 
To retrieve a value:
 
<syntaxhighlight lang Monte="monte">traceln(myArray[0])</langsyntaxhighlight>
 
To change a value:
 
<langsyntaxhighlight Montelang="monte">myArray := myArray.with(3, 'z')</langsyntaxhighlight>
 
Now myArray is ['a','b','c','z'].
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">// create a fixed-length array (length 10)
arr = array(10)
 
// assign a value to the first position in the array and then display it
arr[0] = "hello, world!"
println arr[0]
 
 
// create a variable-length list
l = list()
 
// place the numbers 1-10 in the list
for i in range(1,10)
append l i
end
 
// display the list
println l</syntaxhighlight>
{{out}}
<pre>hello, world!
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</pre>
 
=={{header|Neko}}==
<langsyntaxhighlight Nekolang="neko">var myArray = $array(1);
 
$print(myArray[0]);</langsyntaxhighlight>
 
{{out}}
Line 3,423 ⟶ 5,990:
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using System.Collections;
Line 3,442 ⟶ 6,009:
foreach (i in dynamic) Write($"$i\t"); // Nemerle isn't great about displaying arrays, it's better with lists though
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
'''Note:''' Dynamic arrays can be simulated via the [[Java]] [http://download.oracle.com/javase/6/docs/technotes/guides/collections/index.html Collections Framework] or by using [[NetRexx]] ''indexed strings'' (AKA: [[Creating an Associative Array|associative arrays]]).
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 3,479 ⟶ 6,046:
loop x_ = 1 to cymru[0] by 1
say x_':' cymru[x_]
end x_</langsyntaxhighlight>
 
{{out}}
Line 3,496 ⟶ 6,063:
=={{header|NewLISP}}==
This creates an array of 5 elements, initialized to <code>nil</code>:
<langsyntaxhighlight lang="lisp">(array 5)
→ (nil nil nil nil nil)</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="lisp">(set 'myarray (array 3 4 (sequence 1 12)))
→ ((1 2 3 4) (5 6 7 8) (9 10 11 12))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var # fixed size arrays
x = [1,2,3,4,5,6,7,8,9,10] # type and size automatically inferred
y: array[1..5, int] = [1,2,3,4,5] # starts at 1 instead of 0
Line 3,524 ⟶ 6,091:
a.add(200) # append another element
echo a.pop() # pop last item, removing and returning it
echo a</langsyntaxhighlight>
 
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 DIM A(1)
20 A(1)=10
30 PRINT A(1)</syntaxhighlight>
 
=={{header|NSIS}}==
Line 3,531 ⟶ 6,103:
NSIS does not have native support for arrays. Array support is provided by the [http://nsis.sourceforge.net/Arrays_in_NSIS NSISArray] plugin.
</div>
<langsyntaxhighlight lang="nsis">
!include NSISArray.nsh
Function ArrayTest
Line 3,545 ⟶ 6,117:
Pop $0
FunctionEnd
</syntaxhighlight>
</lang>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
let x = [1 2 3]
 
print $x
 
# Both are equivalent
print $x.1 ($x | get 1)
 
# Shadowing the original x
let x = $x | append 4
print $x
 
# Using mut
mut y = [a b c]
print $y
$y = $y | append d
print $y
</syntaxhighlight>
{{out}}
<pre>
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
╰───┴───╯
 
2
2
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
│ 3 │ 4 │
╰───┴───╯
 
╭───┬───╮
│ 0 │ a │
│ 1 │ b │
│ 2 │ c │
╰───┴───╯
 
╭───┬───╮
│ 0 │ a │
│ 1 │ b │
│ 2 │ c │
╰───┴───╯
</pre>
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">
MODULE Arrays;
IMPORT
Line 3,585 ⟶ 6,206:
Dynamic
END Arrays.
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Arithmetic {
Line 3,599 ⟶ 6,220:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">// NSArrays are ordered collections of NSObject subclasses only.
 
// Create an array of NSString objects.
Line 3,625 ⟶ 6,246:
// No nil termination is then needed.
NSArray *thirdArray = @[ @"Hewey", @"Louie", @"Dewey", @1, @2, @3 ];
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
in the toplevel:
<langsyntaxhighlight lang="ocaml"># Array.make 6 'A' ;;
- : char array = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
 
Line 3,645 ⟶ 6,266:
 
# arr ;;
- : int array = [|0; 1; 2; 3; 65; 5; 6|]</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
Array created with [ ... ] are immutable array.
Oforth has no Array class.
To create a mutable array, #new is used.
Lists are immutables and can act like arrays.
To have a mutable array, a ListBuffer can be used.
 
<langsyntaxhighlight Oforthlang="oforth">[ "abd", "def", "ghi" ] at( 3 ) println.
 
ListBufferArray new dup addAll( [1, 2, 3] ) dup put( 2, 8.1 ) println.
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,663 ⟶ 6,283:
[1, 8.1, 3]
</pre>
 
=={{header|Ol}}==
Ol provides arrays in the form of vectors.
 
Vectors are heterogeneous structures whose elements are indexed by integers. A vector typically occupies less space than a list of the same length, and the average time needed to access a randomly chosen element is typically less for the vector than for the list.
 
The length of a vector is the number of elements that it contains. This number is a non-negative integer that is fixed when the vector is created.
 
The valid indices of a vector are the exact non zero integers which absolute value is less or equal than the length of the vector. Negative indices of a vector means counting from the end of a vector.
 
The first element in a vector is indexed '''by one''' (not a zero!), and the last element is indexed by length of the vector.
The last element in a vector is indexed by minus one, and the first element is indexed by minus length of the vector.
 
<syntaxhighlight lang="scheme">
; making a vector
> #(1 2 3 4 5)
#(1 2 3 4 5)
 
; making a vector in a functional way
> (vector 1 2 3 4 5)
#(1 2 3 4 5)
 
; another functional vector making way
> (make-vector '(1 2 3 4 5))
#(1 2 3 4 5)
 
; the same as above functional vector making way
> (list->vector '(1 2 3 4 5))
#(1 2 3 4 5)
 
; modern syntax of making a vector
> [1 2 3 4 5]
#(1 2 3 4 5)
 
; making a vector of symbols
> '[a b c d e]
#(a b c d e)
 
; making a vector of symbols but evaluate a third element
> `[a b ,(* 7 13) d e]
#(a b 91 d e)
 
; making an empty vectors
> #()
#()
 
> []
#()
 
> '[]
#()
 
> `[]
#()
 
> (make-vector '())
#()
 
> (list->vector '())
#()
 
; making a vector of a vectors (a matrix, for example)
> [[1 2 3]
[4 5 6]
[7 8 9]]
#(#(1 2 3) #(4 5 6) #(7 8 9))
 
; getting length of a vector
> (size [1 2 3 4 5])
5
 
; making n-length vector with undefined values (actually, #false)
> (make-vector 5)
#(#false #false #false #false #false)
 
; making n-length vector with default values
> (make-vector 5 0)
#(0 0 0 0 0)
 
; define a test vector for use in below
> (define array [3 5 7 9 11])
;; Defined array
 
; getting first element of a vector
> (ref array 1)
3
 
> (ref array (- (size array)))
3
 
; getting last element of a vector
> (ref array (size array))
11
 
> (ref array -1)
11
 
; vectors comparison
> (equal? [1 2 3 4 5] [1 2 3 4 5])
#true
 
> (equal? [1 2 3 4 5] [7 2 3 4 5])
#false
 
; vectors of vectors comparison
> (equal?
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1 2 3]
[4 5 6]
[7 8 9]])
#true
 
> (equal?
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1 2 3]
[4 5 6]
[7 8 3]])
#false
</syntaxhighlight>
 
=={{header|ooRexx}}==
ooRexx arrays hold object references. Arrays will automatically increase in size if needed.
<langsyntaxhighlight ooRexxlang="oorexx"> a = .array~new -- create a zero element array
b = .array~new(10) -- create an array with initial size of 10
c = .array~of(1, 2, 3) -- createscreate a 3 element array holding objects 1, 2, and 3
a[3] = "Fred" -- assign an item
b[2] = a[3] -- retrieve an item from the array
c~append(4) -- adds to end. c[4] == 4 now</langsyntaxhighlight>
 
The above Array class supports only one-dimensional arrays (vectors) with positive integer indexes.
ooRexx provides a built-in array class that provides one- and more dimensional arrays
Much more powerful are stems such as a.i.j where i and j can be any string value.
with positive integer indexes.
See category REXX for details.
The above example shows the use of a one-dimensional array (vector).
 
For other related classes see
http://rosettacode.org/wiki/Associative_array/Creation#ooRexx
 
Much more powerful than the array class are stems with tails as described in the following.
 
A stem is a symbol followed by a period, e.g., XXX.
Compound variables consist of a stem
followed by a tail, i.e., one or more symbols separated by one or more periods,
e.g., XXX.U..V.W
or just one or more periods, e.g., XXX..
An assignment of some value to a stem gives this value
to all compound variables with that stem.
 
<syntaxhighlight lang="oorexx">
XXX.='*'
Say 'xxx.1='xxx.1 -- shows xxx.1=*
u=17
xxx.u='Joe'
Say 'xxx.u='xxx.17 -- shows xxx.u=Joe
</syntaxhighlight>
ooRexx introduces a notation a.[x,y] where x and y can actually be expressions.
This way one can implement one- and multidimensional (associative) arrays.
The indexes can be strings containing any characters including blanks.
The total length of the stemmed variable (stem and index values separated by periods) must
not be longer than 250.
 
Another improvement introduced by ooRexx is the possibility to use
=={{header|OxygenBasic}}==
expressions instead of symbols for the tail:
<lang oxygenbasic>
Instead of z=z+1; xxx.z='something'
one can now write xxx.[z+1]='something'
Notice the period in contrast to array references as shown above!
 
The effective "name" of a compound variable is the stem
'CREATING AN ARRAY
concatenated with the periods and the values of the tail's symbols or expressions.
If u=17 and v='zz' Then
XXX.u.v or xxx.[u,v] evaluates to the "effective name" XXX.17.zz
The tail's symbols' values can be any character string
with v='John Doe'
XXX.u.v... will evaluate to XXX.17.John Doe...
The old restriction that the length of such an effective name
must not exceed 250 bytes no longer applies to ooRexx and Regina.
XXX.u.v...='something'
<syntaxhighlight lang="oorexx">u=17
v='John Doe'
XXX.u.v...='some value'
z='17.John Doe...'
Say xxx.z shows 'some value'</syntaxhighlight>
 
When using a stem for storing structured data, as in
float f[100]
<syntaxhighlight lang="oorexx">person.first='Walter'
person.last='Pachl'</syntaxhighlight>
it is advisable to use constant symbols such as 0first and 0last in the tail
since an accidental use of the variables first or last would render confusion.
 
=={{header|OxygenBasic}}==
'SETTING INDEX BASE
<syntaxhighlight lang="oxygenbasic">
 
'CREATING A STATIC ARRAY
float fs[100]
 
'SETTING INDEX BASE
indexbase 1 'default
 
'FILLING PART OF AN ARRAY
fs[20]={2,4,6,8,10,12}
 
f[20]<=1,2,3,4,5,1.25
 
'MAPPING AN ARRAY TO ANOTHER
 
float *g
@g=@ffs[20]
print g[6] 'result 1.2512
 
'DYNAMIC (RESIZEABLE) ARRAYS
</lang>
redim float fd(100)
fd={2,4,6,8} 'assign some values
redim float fd(200) 'expand array
print fd(2) 'original values are preserved by default
redim float fd(200) clear 'array elements are cleared
print fd(2) 'value set to 0.0
redim float fd(0) 'release allocated memory '
</syntaxhighlight>
 
=={{header|Oz}}==
 
<langsyntaxhighlight lang="oz">declare
Arr = {Array.new 1 %% lowest index
10 %% highest index
Line 3,713 ⟶ 6,506:
{Show Arr.1}
Arr.1 := 64
{Show Arr.1}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">v=[];
v=concat(v,7);
v[1]</langsyntaxhighlight>
 
=={{header|Pascal}}==
A modification of the Delphi example:
<langsyntaxhighlight lang="pascal">
Program ArrayDemo;
uses
Line 3,756 ⟶ 6,549:
writeln(DynamicArrayText);
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
Line 3,762 ⟶ 6,555:
In-line
 
<langsyntaxhighlight lang="perl"> my @empty;
my @empty_too = ();
Line 3,770 ⟶ 6,563:
my $aref = ['This', 'That', 'And', 'The', 'Other'];
print $aref->[2]; # And
</syntaxhighlight>
</lang>
 
Dynamic
 
<langsyntaxhighlight lang="perl">my @arr;
 
push @arr, 1;
Line 3,781 ⟶ 6,574:
$arr[0] = 2;
 
print $arr[0];</langsyntaxhighlight>
 
Two-dimensional
 
<langsyntaxhighlight lang="perl"> my @multi_dimensional = (
[0, 1, 2, 3],
[qw(a b c d e f g)],
[qw(! $ % & *)],
);
</syntaxhighlight>
</lang>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2015.12}}
 
<lang perl6>my @arr;
push @arr, 1;
push @arr, 3;
@arr[0] = 2;
say @arr[0];</lang>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
 
In Phix, sequences are '''it''' - there are no other data structures to learn.
 
Line 3,812 ⟶ 6,593:
without any need to worry about memory management issues.
 
<!--<syntaxhighlight lang="phix">-->
<lang Phix>-- simple one-dimensional arrays:
<span style="color: #000080;font-style:italic;">-- simple one-dimensional arrays:</span>
sequence s1 = {0.5, 1, 4.7, 9}, -- length(s1) is now 4
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s1</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4.7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">},</span> <span style="color: #000080;font-style:italic;">-- length(s1) is now 4</span>
s2 = repeat(0,6), -- s2 is {0,0,0,0,0,0}
<span style="color: #000000;">s2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">),</span> <span style="color: #000080;font-style:italic;">-- s2 is {0,0,0,0,0,0}</span>
s3 = tagset(5) -- s3 is {1,2,3,4,5}
<span style="color: #000000;">s3</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- s3 is {1,2,3,4,5}</span>
 
?s1[3] -- displays 4.7 (nb 1-based indexing)
<span style="color: #0000FF;">?</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- displays 4.7 (nb 1-based indexing)</span>
s1[3] = 0 -- replace that 4.7
<span style="color: #000000;">s1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- replace that 4.7</span>
s1 &= {5,6} -- length(s1) is now 6 ({0.5,1,0,9,5,6})
<span style="color: #000000;">s1</span> <span style="color: #0000FF;">&=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- length(s1) is now 6 ({0.5,1,0,9,5,6})</span>
s1 = s1[2..5] -- length(s1) is now 4 ({1,0,9,5})
<span style="color: #000000;">s1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..</span><span style="color: #000000;">5</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- length(s1) is now 4 ({1,0,9,5})</span>
s1[2..3] = {2,3,4} -- length(s1) is now 5 ({1,2,3,4,5})
<span style="color: #000000;">s1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- length(s1) is now 5 ({1,2,3,4,5})</span>
s1 = append(s1,6) -- length(s1) is now 6 ({1,2,3,4,5,6})
<span style="color: #000000;">s1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- length(s1) is now 6 ({1,2,3,4,5,6})</span>
s1 = prepend(s1,0) -- length(s1) is now 7 ({0,1,2,3,4,5,6})
<span style="color: #000000;">s1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- length(s1) is now 7 ({0,1,2,3,4,5,6})
 
-- negative subscripts can also be used, counting from the other end, eg
-- negative subscripts can also be used, counting from the other end, eg</span>
s2[-2..-1] = {-2,-1} -- s2 is now {0,0,0,0,-2,-1}
<span style="color: #000000;">s2</span><span style="color: #0000FF;">[-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- s2 is now {0,0,0,0,-2,-1}
 
-- multi dimensional arrays:
-- multi dimensional arrays:</span>
sequence y = {{{1,1},{3,3},{5,5}},
<span style="color: #004080;">sequence</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">}},</span>
{{0,0},{0,1},{9,1}},
<span style="color: #0000FF;">{{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}},</span>
{{1,7},{1,1},{2,2}}}
<span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">}}}</span>
-- y[2][3][1] is 9
<span style="color: #000080;font-style:italic;">-- y[2][3][1] is 9</span>
 
y = repeat(repeat(repeat(0,2),3),3)
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span><span style="color: #000000;">3</span><span style="color: #0000FF;">),</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
-- same structure, but all 0s
<span style="color: #000080;font-style:italic;">-- same structure, but all 0s
 
-- Array of strings:
-- Array of strings:</span>
sequence s = {"Hello", "World", "Phix", "", "Last One"}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Hello"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"World"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Phix"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">""</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Last One"</span><span style="color: #0000FF;">}</span>
-- s[3] is "Phix"
<span style="color: #000080;font-style:italic;">-- s[3][2] is 'h'"Phix"
-- s[3][2] is 'h'
 
-- A Structure:
-- A Structure:</span>
sequence employee = {{"John","Smith"},
<span style="color: #004080;">sequence</span> <span style="color: #000000;">employee</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">"John"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Smith"</span><span style="color: #0000FF;">},</span>
45000,
27 <span style="color: #000000;">45000</span><span style="color: #0000FF;">,</span>
185.5} <span style="color: #000000;">27</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">185.5</span><span style="color: #0000FF;">}</span>
 
-- To simplify access to elements within a structure it is good programming style to define constants that name the various fields, eg:
<span style="color: #000080;font-style:italic;">-- To simplify access to elements within a structure it is good programming style to define constants that name the various fields, eg:</span>
constant SALARY = 2
<span style="color: #008080;">constant</span> <span style="color: #000000;">SALARY</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span>
 
-- Array of structures:
<span style="color: #000080;font-style:italic;">-- Array of structures:</span>
sequence employees = {
<span style="color: #004080;">sequence</span> <span style="color: #000000;">employees</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span>
{{"Jane","Adams"}, 47000, 34, 135.5}, -- a[1]
<span style="color: #0000FF;">{{</span><span style="color: #008000;">"Jane"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Adams"</span><span style="color: #0000FF;">},</span> <span style="color: #000000;">47000</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">34</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">135.5</span><span style="color: #0000FF;">},</span> <span style="color: #000080;font-style:italic;">-- a[1]</span>
{{"Bill","Jones"}, 57000, 48, 177.2}, -- a[2]
<span style="color: #0000FF;">{{</span><span style="color: #008000;">"Bill"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Jones"</span><span style="color: #0000FF;">},</span> <span style="color: #000000;">57000</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">48</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">177.2</span><span style="color: #0000FF;">},</span> <span style="color: #000080;font-style:italic;">-- a[2]
-- .... etc.
} -- .... etc.</span>
<span style="color: #0000FF;">}</span>
-- employees[2][SALARY] is 57000
<span style="color: #000080;font-style:italic;">-- employees[2][SALARY] is 57000
 
-- A tree can be represented easily, for example after adding "b","c","a" to it you might have:
-- A tree can be represented easily, for example after adding "b","c","a" to it you might have:</span>
sequence tree = {{"b",3,2},
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tree</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">"b"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},</span>
{"c",0,0},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"c"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{"a",0,0}}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"a"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}}</span>
 
-- ie assuming
<span style="color: #000080;font-style:italic;">-- ie assuming </span>
constant ROOT=1, VALUE=1, LEFT=2, RIGHT=3 -- then
<span style="color: #008080;">constant</span> <span style="color: #000000;">ROOT</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">VALUE</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">LEFT</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">RIGHT</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span> <span style="color: #000080;font-style:italic;">-- then
-- tree[ROOT][VALUE] is "b"
-- tree[ROOT][LEFTVALUE] is 3, and tree[3] is the "ab"
-- tree[ROOT][RIGHTLEFT] is 23, and tree[23] is the "ca"
-- tree[ROOT][RIGHT] is 2, and tree[2] is the "c"
 
-- The operations you might use to build such a tree (tests/loops/etc omitted) could be:
-- The operations you might use to build such a tree (tests/loops/etc omitted) could be:</span>
tree = {}
<span style="color: #000000;">tree</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
tree = append(tree,{"b",0,0})
<span style="color: #000000;">tree</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"b"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
tree = append(tree,{"c",0,0})
<span style="color: #000000;">tree</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"c"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
tree[1][RIGHT] = length(tree)
<span style="color: #000000;">tree</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">RIGHT</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">)</span>
tree = append(tree,{"a",0,0})
<span style="color: #000000;">tree</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"a"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
tree[1][LEFT] = length(tree)
<span style="color: #000000;">tree</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">LEFT</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Finally, some tests (recall that we have already output a 4.7):</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">tree</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ROOT</span><span style="color: #0000FF;">][</span><span style="color: #000000;">VALUE</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">employees</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">employees</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">employee</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">employees</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">][</span><span style="color: #000000;">SALARY</span><span style="color: #0000FF;">]</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s1</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s2</span>
<!--</syntaxhighlight>-->
 
-- Finally, some tests (recall that we have already output a 4.7):
?s[3]
?tree
?tree[ROOT][VALUE]
employees = append(employees, employee)
?employees[3][SALARY]
?s1
?s2</lang>
{{out}}
<pre>
Line 3,896 ⟶ 6,680:
{0,0,0,0,-2,-1}
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
 
0 tolist /# create an empty array/list. '( )' is equivalent #/
drop /# remove top of the stack #/
0 10 repeat /# put an array/list of 10 elements (each element has value 0) to the stack #/
flush /# remove all elements. List is empty [] #/
drop
( 1 2 "Hello" pi ) /# put an initialize array/list to stack #/
-7 1 set /# modified first element to -7 #/
0 get /# get the last element. '-1 get' is equivalent #/
drop
( "next" "level" ) 2 put /# insert a list in a list = [-7, ["next", "level"], 2, "Hello", 3.141592653589793]] #/
3 2 slice /# extract the subarray/sublist [ 2 "Hello" ] #/
 
pstack /# show the content of the stack #/ </syntaxhighlight>
 
=={{header|PHP}}==
===Writing To An Array===
====Single Dimension====
<langsyntaxhighlight lang="php">$NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];</langsyntaxhighlight>
 
====Multi-Dimensional====
<langsyntaxhighlight lang="php">$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)
);</langsyntaxhighlight>
 
====Array push====
 
<langsyntaxhighlight lang="php">$arr = ['apple', 'orange'];
array_push($arr, 'pear');
print implode(',', $arr); // Returns apple,orange,pear</langsyntaxhighlight>
 
===Reading From An Array===
====Single Dimension====
Read the 5th value in the array:
<langsyntaxhighlight lang="php">echo $NumberArray[5]; // Returns 5
echo $LetterArray[5]; // Returns f</langsyntaxhighlight>
====Multi-Dimensional====
Read the 2nd line, column 5
<langsyntaxhighlight lang="php">echo $MultiArray[1][5]; // 2</langsyntaxhighlight>
===Print a whole array===
This is useful while developing to view the contents of an array:
<syntaxhighlight lang ="php">print_r($MultiArray);</langsyntaxhighlight>
Which would give us:
<langsyntaxhighlight lang="php">Array(
0 => array(
0 => 0
Line 3,963 ⟶ 6,764:
5 => 3
)
)</langsyntaxhighlight>
=== Set custom keys for values===
This example starts the indexing from 1 instead of 0
<langsyntaxhighlight lang="php">$StartIndexAtOne = array(1 => "A", "B", "C", "D");</langsyntaxhighlight>
This example shows how you can apply any key you want
<langsyntaxhighlight lang="php">$CustomKeyArray = array("d" => "A", "c" => "B", "b" =>"C", "a" =>"D");</langsyntaxhighlight>
 
To read the 3rd value of the second array:
<langsyntaxhighlight lang="php">echo $CustomKeyArray["b"]; // Returns C</langsyntaxhighlight>
 
===Other Examples===
Create a blank array:
<langsyntaxhighlight lang="php">$BlankArray = array();</langsyntaxhighlight>
 
Set a value for the next key in the array:
<langsyntaxhighlight lang="php">$BlankArray[] = "Not Blank Anymore";</langsyntaxhighlight>
 
Assign a value to a certain key:
<langsyntaxhighlight lang="php">$AssignArray["CertainKey"] = "Value";</langsyntaxhighlight>
 
=={{header|Picat}}==
Picat has support both arrays and lists. Arrays are general much faster than lists, especially for many elements and if there are much element accesses/updates.
 
Here are some examples how to use arrays.
<syntaxhighlight lang="picat">import util.
 
go =>
 
% Create an array of length 10
Len = 10,
A = new_array(Len),
bind_vars(A,0), % Initialize all values to 0
println(a=A),
A[1] := 1, % Assign a value
println(a=A),
println(a1=A[1]), % print first element
% (re)assign a value
foreach(I in 1..Len) A[I] := I end,
println(A[3..7]), % print some interval of an array
nl,
% 2D arrays
A2 = new_array(4,4),
foreach(I in 1..4, J in 1..4)
A2[I,J] := (I-1)*4+J
end,
foreach(Row in A2) println(Row) end,
 
% These functions are defined in the util module.
% They returns lists so we have to convert them to arrays.
println('rows '=to_array(A2.rows)),
println('columns '=A2.columns.to_array),
println(diagonal1=A2.diagonal1.to_array),
println(diagonal2=A2.diagonal2.to_array),
 
nl,
% Pushing values to an array
A3 = {}, % an empty array
foreach(I in 1..4)
A3 := A3 ++ {10**I+I}
end,
println(a3=A3),
nl,
 
% Some misc functions
println([first=A3.first(), second=A3.second(),last=A3.last()]),
 
nl.
</syntaxhighlight>
 
{{out}}
<pre>a = {0,0,0,0,0,0,0,0,0,0}
a = {1,0,0,0,0,0,0,0,0,0}
a1 = 1
{3,4,5,6,7}
 
{1,2,3,4}
{5,6,7,8}
{9,10,11,12}
{13,14,15,16}
rows = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}
columns = {{1,5,9,13},{2,6,10,14},{3,7,11,15},{4,8,12,16}}
diagonal1 = {1,6,11,16}
diagonal2 = {4,7,10,13}
 
a3 = {11,102,1003,10004}
 
[first = 11,second = 102,last = 10004]</pre>
 
{{trans|Prolog}}
<syntaxhighlight lang="picat">listvariant :-
List = new_list(5), % create a list of length 5
nth(1,List,a), % put an a at position 1 , nth/3 uses indexing from 1
nth(4,List,b), % put an b at position 4
println(list=List),
append(List,[d],List2), % append an d at the end , List2 has 5 elements
println(list2=List2),
Add = new_list(5), % create a new list of length 5
append(List2,Add,List3), % append 5 free variables to List2
println(len=List3.len), % List3 now has 11 elements
println(list3=List3),
Value = List3[1], % get the value at position 1
println(value=Value). % will print out a
</syntaxhighlight>
 
{{out}}
("_4970" etc are undefined variables):
<pre>
list = [a,_4970,_4980,b,_49a0]
list2 = [a,_4970,_4980,b,_49a0,d]
len = 11
list3 = [a,_4970,_4980,b,_49a0,d,_4e50,_4e60,_4e70,_4e80,_4e90]
value = a</pre>
 
=={{header|PicoLisp}}==
PicoLisp has no built-in array data type. Lists are used instead.
<langsyntaxhighlight PicoLisplang="picolisp">(setq A '((1 2 3) (a b c) ((d e) NIL 777))) # Create a 3x3 structure
(mapc println A) # Show it</langsyntaxhighlight>
{{out}}
<pre>(1 2 3)
Line 3,992 ⟶ 6,888:
((d e) NIL 777)</pre>
Replace 'b' with 'B' in middle row:
<langsyntaxhighlight PicoLisplang="picolisp">(set (nth A 2 2) 'B)
(mapc println A)</langsyntaxhighlight>
{{out}}
<pre>(1 2 3)
Line 3,999 ⟶ 6,895:
((d e) NIL 777)</pre>
Insert '1' in front of the middle row:
<langsyntaxhighlight PicoLisplang="picolisp">(push (cdr A) 1)
(mapc println A)</langsyntaxhighlight>
{{out}}
<pre>(1 2 3)
Line 4,006 ⟶ 6,902:
((d e) NIL 777)</pre>
Append '9' to the middle row:
<langsyntaxhighlight PicoLisplang="picolisp">(queue (cdr A) 9)
(mapc println A)</langsyntaxhighlight>
{{out}}
<pre>(1 2 3)
Line 4,014 ⟶ 6,910:
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">int main(){
// Initial array, few random elements.
array arr = ({3,"hi",84.2});
Line 4,021 ⟶ 6,917:
 
write(arr[5] + "\n"); // And finally print element 5.
}</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">/* Example of an array having fixed dimensions */
declare A(10) float initial (1, 9, 4, 6, 7, 2, 5, 8, 3, 10);
 
Line 4,035 ⟶ 6,931:
declare B(N) float initial (9, 4, 7, 3, 8, 11, 0, 5, 15, 6);
B(3) = -11;
put (B(2));
end;
 
Line 4,042 ⟶ 6,939:
allocate C;
C = 0;
c(7) = 12;</lang>
put (C(9));</syntaxhighlight>
 
=={{header|Plain English}}==
Arrays are a bit of a sticking point for Plain English, because its creators have not as yet devised a sufficiently elegant way to work with them within the constraints of the language. Only lists have high-level routine support. Nevertheless, the capability to build arrays ourselves exists within the language. Following is an example of how it could be done.
 
<syntaxhighlight lang="plainenglish">To run:
Start up.
Write "Creating an array of 100 numbers..." on the console.
Create a number array given 100.
Write "Putting 1 into the array at index 0." on the console.
Put 1 into the number array at 0.
Write "Putting 33 into the array at index 50." on the console.
Put 33 into the number array at 50.
Write "Retrieving value from array at index 0... " on the console without advancing.
Get a number from the number array at 0.
Write "" then the number on the console.
Write "Retrieving value from array at index 50... " on the console without advancing.
Get another number from the number array at 50.
Write "" then the other number on the console.
Write "Retrieving value from array at index 99... " on the console without advancing.
Get a third number from the number array at 99.
Write "" then the third number on the console.
Destroy the number array.
Wait for the escape key.
Shut down.
 
\\\\\\\\\\\\\\\\\\ Array implementation \\\\\\\\\\\\\\\\\\\\
 
A number array has a first element pointer.
A location is a number.
 
To create a number array given a count:
Put a number's magnitude times the count into a size.
Assign the number array's first element pointer given the size. \ allocate memory for the array
 
To destroy a number array:
Unassign the number array's first element pointer. \ free the array's memory
To get a number from a number array at a location:
Put the location times the number's magnitude into an offset.
Put the number array's first element pointer into a number pointer.
Add the offset to the number pointer.
Put the number pointer's target into the number.
To put a number into a number array at a location:
Put the location times the number's magnitude into an offset.
Put the number array's first element pointer into a number pointer.
Add the offset to the number pointer.
Put the number into the number pointer's target.</syntaxhighlight>
{{out}}
<pre>
Creating an array of 100 numbers...
Putting 1 into the array at index 0.
Putting 33 into the array at index 50.
Retrieving value from array at index 0... 1
Retrieving value from array at index 50... 33
Retrieving value from array at index 99... 0
</pre>
 
=={{header|Pony}}==
 
Arrays are homogenous.
<syntaxhighlight lang="pony">use "assert" // due to the use of Fact
<lang Pony>var numbers = Array[I32](16) // creating array of 32-bit ints with initial allocation for 16 elements
 
- - -
 
var numbers = Array[I32](16) // creating array of 32-bit ints with initial allocation for 16 elements
numbers.push(10) // add value 10 to the end of array, extending the underlying memory if needed
try
Line 4,059 ⟶ 7,019:
Fact(s == 3) // size of array 'other' is 3
other(1) = 40 // 'other' now is [10, 40, 30]
end</langsyntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="text">
%Declaring array
 
Line 4,079 ⟶ 7,039:
 
x 1 get
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
Empty array:
<langsyntaxhighlight lang="powershell">$a = @()</langsyntaxhighlight>
Array initialized with only one member:
<langsyntaxhighlight lang="powershell">$a = ,2
$a = @(2) # alternative</langsyntaxhighlight>
Longer arrays can simply be created by separating the values with commas:
<langsyntaxhighlight lang="powershell">$a = 1,2,3</langsyntaxhighlight>
A value can be appended to an array using the <code>+=</code> operator:
<langsyntaxhighlight lang="powershell">$a += 5</langsyntaxhighlight>
Since arrays are immutable this simply creates a new array containing one more member.
 
Values can be retrieved using a fairly standard indexing syntax:
<syntaxhighlight lang ="powershell">$a[1]</langsyntaxhighlight>
Similarly, those values can also be replaced:
<langsyntaxhighlight lang="powershell">$a[1] = 42</langsyntaxhighlight>
The range operator <code>..</code> can be used to create contiguous ranges of integers as arrays:
<langsyntaxhighlight lang="powershell">$r = 1..100</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="powershell">$r[0..9+25..27+80,85,90]</langsyntaxhighlight>
Indexing from the end of the array can be done with negative numbers:
<langsyntaxhighlight lang="powershell">$r[-1] # last index</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 4,110 ⟶ 7,071:
retrieve and set elements.
 
<langsyntaxhighlight lang="prolog">
singleassignment:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
Line 4,120 ⟶ 7,081:
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
</syntaxhighlight>
</lang>
 
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.
 
<langsyntaxhighlight lang="prolog">
destructive:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
Line 4,134 ⟶ 7,095:
arg(1 ,Array,Value1), % get the value at position 1
print(Value1),nl. % will print Value1 and therefore c followed by a newline
</syntaxhighlight>
</lang>
 
Lists can be used as arrays.
 
<langsyntaxhighlight lang="prolog">
listvariant:-
length(List,100), % create a list of length 100
Line 4,148 ⟶ 7,109:
nth1(1 ,List3,Value), % get the value at position 1
print(Value),nl. % will print out a
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
Line 4,154 ⟶ 7,115:
'''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.
 
<langsyntaxhighlight PureBasiclang="purebasic"> ;Set up an Array of 23 cells, e.g. 0-22
Dim MyArray.i(22)
MyArray(0) = 7
MyArray(1) = 11
MyArray(7) = 23</langsyntaxhighlight>
'''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.
<langsyntaxhighlight PureBasiclang="purebasic"> ;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</langsyntaxhighlight>
<langsyntaxhighlight PureBasiclang="purebasic"> ;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</langsyntaxhighlight>
<langsyntaxhighlight PureBasiclang="purebasic"> ; Now, set up a multi dimensional Array
Dim MultiArray.i(800, 600)
MultiArray(100, 200) = 640
MultiArray(130, 40) = 120</langsyntaxhighlight>
<langsyntaxhighlight PureBasiclang="purebasic">Dim MultiArray2.i(64, 128, 32)
PrintN( Str(ArraySize(MultiArray2(), 2)) ; Will tell that second dimension size is '128'</langsyntaxhighlight>
 
=={{header|Python}}==
Python lists are dynamically resizeable.
<langsyntaxhighlight lang="python">array = []
 
array.append(1)
Line 4,187 ⟶ 7,148:
array[0] = 2
 
print (array[0])</langsyntaxhighlight>
 
A simple, single-dimensional array can also be initialized thus:
 
<langsyntaxhighlight lang="python">myArraymy_array = [0] * size</langsyntaxhighlight>
 
However, this will not work as intended if one tries to generalize from the syntax:
 
<langsyntaxhighlight lang="python">myArraymy_array = [[0] * width] * height] # DOES NOT WORK AS INTENDED!!!</langsyntaxhighlight>
 
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 differingdifferent semantics of immutables (strings, numbers) and mutables (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:
 
<langsyntaxhighlight lang="python">myArraymy_array = [[0 for x in range(width)] for y in range(height)]</langsyntaxhighlight>
 
That is equivalent to:
 
<langsyntaxhighlight lang="python">myArraymy_array = list()
for x in range(height):
myArraymy_array.append([0] * width)</langsyntaxhighlight>
 
To retrieve an element in an array, use any of the following methods:
 
<langsyntaxhighlight lang="python">
# Retrieve an element directly from the array.
item = array[index]
Line 4,217 ⟶ 7,178:
# Use the array like a stack. Note that using the pop() method removes the element.
array.pop() # Pop last item in a list
array.pop(0) # Pop first item in a list
 
# Using a negative element counts from the end of the list.
item = array[-1] # Retrieve last element in a list.
</syntaxhighlight>
</lang>
 
Python produces an IndexError when accessing elements out of range:
<langsyntaxhighlight lang="python">
try:
# This will cause an exception, which will then be caught.
print (array[len(array)])
except IndexError as e:
# Print the exception.
print (e)
</syntaxhighlight>
</lang>
 
Slicing a list creates a new list.
<syntaxhighlight lang="python">
another_array = my_array[1:3]
</syntaxhighlight>
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
'Task
'Show basic array syntax in your language.
 
'Basically, create an array, assign a value to sit, and retrieve an element (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it).
Rem DECLARATION PART
 
Rem QB64/QuickBasic/Qbasic array examples
'-----------
MyArray%(10) = 11 ' it creates an array integer of 11 elements from 0 to 11
Dim MyArray2%(0 To 10) ' it is equal to the previous line of code, it is its explicit way
 
'--------------
Option Base 1 ' from here all arrays have as default as index of first item 1
MyArray3%(10) = 14 'it creates array from 1 to 14
 
Dim Myarray4%(1 To 14) ' it is equal to the 2 previous lines of code
 
'-----------------
Dim Shared myArray$(-12 To 12) ' it creates a string array with 25 elements and SHARED makes it global array
 
'---------------------
'$dynamic
Dim MyArray1!(1 To 4) ' these two lines of code create a resizable array
 
ReDim myArray2!(1 To 4) ' it does the same of the 2 previous lines of code
 
'-------------------------
' alternatively at the place of suffix ! or $ or % or # or &
' you can use the explicit way "DIM namearray (start to end) AS TypeOfVariable"
Dim MyIntegerArray(1 To 10) As Integer
Dim MyStringArray(1 To 10) As String
Dim MySingleArray(1 To 10) As Single
Dim MyLongArray(1 To 10) As Long
Dim MyDoubleArray(1 To 10) As Double
 
'---------------------------
'it is possible defining an User Data Type and creating an array with that type
Type MyType
Name As String * 8 ' a fixed lenght string variable
ID As Integer
Position As Single
End Type
 
Dim Lists(1 To 10) As MyType
ReDim WhoIs(-19 To 10) As MyType
 
 
'------------------------------
' Number of dimensions of an array: QuickBasic vs QB64
' an array can have from 1 to until 60 dimensions in QuickBasic
' an array can have from 1 to RAM dimension of your machine
' you must think that in the dayly practice is rare to use more than 3 dimensions
Dim Calendar%(1 To 31, 1 To 56, 1 To 12) ' array calendar with days, week, mounths
ReDim Time(1 To 60, 1 To 60, 1 To 24) As Integer ' array Time with seconds, minutes and hours
 
Rem ONLY QB64 arrays
'--------
' QB64 introduces more TypeOfVariable all of them associated to a suffix
' so you can declare also these kind of data
' _BIT or `, _BYTE or %%, _INTEGER64 or &&, _FLOAT or ##, OFFSET or %&, _MEM (no suffix)
Dim MyByteArray%%(1 To 4)
Dim MyByteArray2(1 To 4) As _Byte
' are the same declaration of the array
 
'----------------
'QB64 lets you to use an alternative way to declare variables and array
'using the following syntax: DIM / REDIM AS Type of data Array1, Array2, Array3"
ReDim As _MEM Mem1(1 To 5), Mem2(6 To 10)
Dim As _Unsigned _Byte UByte(-3 To 25), Ubyte2(100 To 200)
 
 
Rem QB64 / QB PDS (7.1) arrays
ReDim MyPreservedArray(1 To 5) As Integer ' it creates a dynamic array
ReDim _Preserve MyPreservedArray(-3 To 100) As Integer ' it changes limit of dimension of array
 
Rem ASSIGNING PART
' at declaration point each array is initializated: 0 for digit arrays, "" for string arrays
' in the UDT arrays each variable is initializated following its type
 
 
' all types of array can be accessed using the index of item choice to change
' in the UDT array each item of UDT is reached using the "." while the item of array needs the index
Print MyPreservedArray(2)
MyPreservedArray(2) = 12345
Print MyPreservedArray(2)
 
Print WhoIs(-10).Name
WhoIs(-10).Name = "QB64"
Print WhoIs(-10).Name
WhoIs(10).Name = WhoIs(-10).Name
Print WhoIs(10).Name
 
Rem RETRIEVE AN ELEMENT
' basically the coder must use a loop for scanning the whole array for that value choosen
 
'-----------------
' static array
MySingleArray(4) = 4
MySingleArray(8) = 8
For n = 1 To 10
If MySingleArray(n) > 0 Then Print MySingleArray(n)
Next
 
 
'dynamic array
 
WhoIs(-10).Name = "QB64"
WhoIs(10).Name = "C#"
WhoIs(1).Name = "Java"
Print WhoIs(-10).Name, WhoIs(10).Name, WhoIs(1).Name
ReDim _Preserve WhoIs(-10 To 19) As MyType
Print
Print WhoIs(-10).Name, WhoIs(10).Name, WhoIs(1).Name
Print WhoIs(-1).Name, WhoIs(19).Name, WhoIs(10).Name
 
 
 
</syntaxhighlight>
 
=={{header|Quackery}}==
 
A selection of the nest related words in Quackery, demonstrated as a dialogue in the Quackery shell.
 
<pre>Welcome to Quackery.
 
Enter "leave" to leave the shell.
 
Building extensions.
 
/O> ( nests are dynamic arrays, zero indexed from the left, -1 indexed from the right )
...
 
Stack empty.
 
/O> [] ( create an empty nest )
... 23 join 24 join ( append two numbers )
... ' [ 33 34 ] ( create a nest of two numbers )
... join ( concatenate them )
... ' [ 45 46 ] ( create a nest of two numbers )
... nested join ( add that nest as an item of the nest )
...
 
Stack: [ 23 24 33 34 [ 45 46 ] ]
 
/O> ' [ 55 56 ] ( create a nest of two numbers )
... swap 2 stuff ( insert it into the previous nest as the 2nd item )
...
 
Stack: [ 23 24 [ 55 56 ] 33 34 [ 45 46 ] ]
 
/O> -3 pluck drop ( remove the third item from the end and dispose of it )
...
 
Stack: [ 23 24 [ 55 56 ] 34 [ 45 46 ] ]
 
/O> dup 0 peek ( copy the first item )
...
 
Stack: [ 23 24 [ 55 56 ] 34 [ 45 46 ] ] 23
 
/O> swap -1 poke ( ... and overwrite the last item with it )
...
 
Stack: [ 23 24 [ 55 56 ] 34 23 ]
 
/O> behead join ( remove the first item and append it to the end )
...
 
Stack: [ 24 [ 55 56 ] 34 23 23 ]
 
/O> -2 split nip ( split it two items from the end and dispose of the left hand side )
...
 
Stack: [ 23 23 ]
 
/O> ' ** join ( append the exponentiation word )
...
 
Stack: [ 23 23 ** ]
 
/O> do ( ... and perform the nest as Quackery code. )
...
 
Stack: 20880467999847912034355032910567 </pre>
 
 
=={{header|R}}==
Line 4,237 ⟶ 7,391:
Dynamic
 
<langsyntaxhighlight Rlang="r">arr <- array(1)
 
arr <- append(arr,3)
Line 4,243 ⟶ 7,397:
arr[1] <- 2
 
print(arr[1])</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
;; import dynamic arrays
Line 4,258 ⟶ 7,412:
(gvector-ref gv 0) ; 1
(gvector-add! gv 5) ; increase size
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
At its most basic, an array in Raku is quite similar to an array in Perl 5.
 
<syntaxhighlight lang="raku" line>my @arr;
push @arr, 1;
push @arr, 3;
@arr[0] = 2;
say @arr[0];</syntaxhighlight>
 
===Some further exposition:===
 
In Raku, arrays have a very specific definition: "A collection of Scalar containers that do the Positional Role." Scalar container means it is mutable and may contain any object; an Integer, a Rational number, a String, another Array, whatever... literally any other object that can be instantiated in Raku. The Positional Role means that it uses integer indexing for access. The index must be a positive integer, an expression that evaluates to a positive integer, or something that can be coerced to a positive integer. Arrays are always indexed from 0. The starting index can not be changed.
 
Arrays are unconstrained by default. They may hold any number of any type of object up to available memory. They do not need to be pre-allocated. Simply assigning (or even referring in some cases) to an index slot is enough to autovivify the container and allocate enough memory to hold the assigned object. Memory will automatically be allocated and will grow and shrink as necessary to hold the values assigned.
 
Values may be pushed onto the end of an array, popped off of the end, shifted off of the front or unshifted onto the front, and spliced into or out of the interior.
@array.push: 'value';
my $value = @array.pop;
@array.unshift: 'value';
my $value = @array.shift;
@array.splice(2,3, <some arbitrary string values>);
 
Arrays may be constrained to only accept a certain number of objects or only a certain type of object.
my Int @array; # can only hold Integer objects. Assigning any other type will cause an exception.
my @array[9]; # can only 10 objects (zero indexed). Trying to assign to an index greater than 9 with cause an exception.
 
Arrays are constructed with square brackets, an explicit constructor, or by coercing some other object either explicitly using a coercer or implicitly by simply assigning to an array variable. These are all arrays:
[1, 2, 3, 4]
['a', 'b', 'c', 'd']
Array.new<this is an array of words>
('as', 'is', 'this').Array
my @implicit = <yep, this too>
 
Array variables in Raku are variables whose names bear the @ sigil, and are expected to contain some sort of list-like object. Of course, other variables may also contain these objects, but @-sigiled variables always do, and are expected to act the part. Array storage slots are accessed through postcircumfix square bracket notation. Unlike Perl 5, @-sigiled variables are invariant on access, whether you are accessing one slot, many slots, or all of the slots. The first slot in @array is @array[0] not $array[0]. @array and $array are two different unconnected variables.
@array[1] # a single value in the 2nd slot
@array[*-1] # a single value in the last slot
@array[1..5] # an array slice, 2nd through 6th slots
@array[1,3,7] # slice, 2nd, 4th and 8th slot
@array[8,5,2] # can be in any order
@array[*] # all the slots
@array[] # all the slots (zen slice)
@array[^10] # first 10 slots (upto 10 or 0..9)
@array.head(5) # first 5 slots
@array.tail(2) # last two
 
Multi-dimensioned arrays also use postcircumfix square brackets for access. If the array is not ragged, (every sub array is the same size) you may use semicolon subscripting.
@array[1][1] # 2nd item in the second slot
@array[1;1] # same thing, implies rectangular (non-ragged) arrays
 
There are several objects that have an Iterable Role and a PositionalBindFailover Role which makes them act similar to arrays and allows them to be used nearly interchangeably in read-only applications. (Raku is big on duck typing. "If it looks like a duck and quacks like a duck and waddles like a duck, it's a duck.") These constructs are ordered and use integer indexing and are often used in similar circumstances as arrays, however, '''they are immutable'''. Values in slots can not be changed. They can not be pushed to, popped from or spliced. They can easily converted to arrays by simply assigning them to an array variable.
 
'''List''': A fixed Iterable collection of immutable values. Lists are constructed similarly to arrays:
(1, 2, 3, 4)
('a', 'b', 'c', 'd')
List.new(<this is a list of words>)
('as', 'is', 'this').List
my @not-a-list = (<oops, this isn't>)
my @implicit := (<but this is>) # note the values are bound := not assigned =
 
'''Range''': Iterable list of consecutive numbers or strings with a lower and an upper boundary. (That boundary may be infinite.) Reified on demand.
2..20 # integers two through twenty
1..Inf # natural numbers
'a'..'z' # lowercase latin letters
 
'''Sequence''': Iterable list of objects with some method to determine the next (or previous) item in the list. Reified on demand. Will try to automatically deduce simple arithmetic or geometric sequences. Pass in a code object to calculate more complex sequences.
0,2,4 ... 64 # even numbers up to 64
1,2,4 ... 64 # geometric increase
1,1, *+* ... * # infinite Fibonacci sequence
1,1,{$^n2 + $^n1 + 1} ... * # infinite Leonardo numbers
 
Postcircumfix indexing works for any object that has a Positional (or PositionalBindFailover) role, it need not be in a @-sigiled variable, or indeed, in a variable at all.
[2,4,6,8,10][1] # 4 - anonymous array
<my dog has fleas>[*-2] # 'has' - anonymous list
sub a {(^Inf).grep: *.is-prime}; a()[99]; # 541 - (100th prime) subroutine returning a sequence
my $lol = ((1,2), (3,4), (5,6)); $lol[1]; # (3 4) - list of lists in a Scalar variable
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">
<lang REBOL>
a: [] ; Empty.
b: ["foo"] ; Pre-initialized.
</syntaxhighlight>
</lang>
 
Inserting and appending.
 
<syntaxhighlight lang="rebol">
<lang REBOL>
append a ["up" "down"] ; -> ["up" "down"]
insert a [left right] ; -> [left right "up" "down"]
</syntaxhighlight>
</lang>
 
Getting specific values.
 
<syntaxhighlight lang="rebol">
<lang REBOL>
first a ; -> left
third a ; -> "up"
last a ; -> "down"
a/2 ; -> right (Note: REBOL is 1-based.)
</syntaxhighlight>
</lang>
 
Getting subsequences. REBOL allows relative motion through a block (list).
Line 4,286 ⟶ 7,520:
you can even assign to it without destroying the list.
 
<syntaxhighlight lang="rebol">
<lang REBOL>
a ; -> [left right "up" "down"]
next a ; -> [right "up" "down"]
Line 4,297 ⟶ 7,531:
copy/part a 2 ; -> [left right]
copy/part skip a 2 2 ; -> ["up" "down"]
</syntaxhighlight>
</lang>
 
=={{header|Red}}==
<syntaxhighlight lang="red">arr1: [] ;create empty array
arr2: ["apple" "orange" 1 2 3] ;create an array with data
>> insert arr1 "blue"
>> arr1
== ["blue"]
append append arr1 "black" "green"
>> arr1
== ["blue" "black" "green"]
>> arr1/2
== "black"
>> second arr1
== "black"
>> pick arr1 2
== "black"</syntaxhighlight>
A vector! is a high-performance series! of items.
The items in a vector! must all have the same type.
The allowable item types are: integer! float! char! percent!
Vectors of string! are not allowed.
<syntaxhighlight lang="red">>> vec1: make vector! [ 20 30 70]
== make vector! [20 30 70]
>> vec1/2
== 30
>> second vec1
== 30
>> append vec1 90
== make vector! [20 30 70 90]
>> append vec1 "string"
*** Script Error: invalid argument: "string"
*** Where: append
*** Stack:
>> append vec1 3.0
*** Script Error: invalid argument: 3.0
*** Where: append
*** Stack:</syntaxhighlight>
 
=={{header|ReScript}}==
 
<syntaxhighlight lang="rescript">let arr = [1, 2, 3]
 
let _ = Js.Array2.push(arr, 4)
 
arr[3] = 5
 
Js.log(Js.Int.toString(arr[3]))</syntaxhighlight>
{{out}}
<pre>
$ bsc arrs.res > arrays.bs.js
$ node arrays.bs.js
5
</pre>
 
=={{header|Retro}}==
Retro has a vocabulary for creating and working with arrays.
 
<syntaxhighlight lang="retro">
<lang Retro>
needs array'
 
Line 4,337 ⟶ 7,623:
( Create a quote from the values in an array )
d ^array'toQuote
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
Line 4,344 ⟶ 7,630:
 
===simple arrays===
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates a simple array usage. */
a.='not found' /*value for all a.xxx (so far).*/
do j=1 to 100 /*start at 1, define 100 elements*/
Line 4,352 ⟶ 7,638:
say 'element 50 is:' a.50
say 'element 3000 is:' a.3000
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
{{out}}
<pre>
Line 4,360 ⟶ 7,646:
 
===simple arrays, mimic other languages===
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates array usage with mimicry. */
a. = 'not found' /*value for all a.xxx (so far). */
do j=1 to 100 /*start at 1, define 100 elements*/
Line 4,370 ⟶ 7,656:
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────A subroutine────────────────────────*/
a: _a_ = arg(1); return a._a_</langsyntaxhighlight>
<pre>
element 50 is: -5000
Line 4,377 ⟶ 7,663:
 
===simple arrays, assigned default===
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates array usage with mimicry. */
a. = 00 /*value for all a.xxx (so far). */
do j=1 to 100 /*start at 1, define 100 elements*/
Line 4,387 ⟶ 7,673:
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────A subroutine────────────────────────*/
a: _a_ = arg(1); return a._a_</langsyntaxhighlight>
{{out}}
<pre>
Line 4,395 ⟶ 7,681:
 
===arrays with non-unity index start===
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates array usage (with elements out-of-range).*/
array. = 'out of range' /*define ALL elements to this. */
 
Line 4,404 ⟶ 7,690:
say g "squared is:" array.g
say 7000 "squared is:" array.7000
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
{{out}}
<pre>
Line 4,412 ⟶ 7,698:
 
===arrays, disjoint===
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates disjointed array usage. */
yr. = 'year not supported' /*value for all yr.xxx (so far).*/
 
Line 4,428 ⟶ 7,714:
year=1744
say 'DOB' year "is:" yr.year
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
{{out}}
<pre>
Line 4,436 ⟶ 7,722:
 
===sparse arrays and special indices===
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates array usage: sparse and disjointed. */
yyy = -55 /*REXX must use this mechanism···*/
a.yyy = 1e9 /*··· when assigning neg indices.*/
Line 4,462 ⟶ 7,748:
│ identify stemmed arrays (the period). │
└────────────────────────────────────────────────────────────────────┘*/
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
 
=={{header|Ring}}==
 
Dynamic
 
<syntaxhighlight lang="ring"># create an array with one string in it
a = ['foo']
 
# add items
a + 1 # ["foo", 1]
 
# set the value at a specific index in the array
a[1] = 2 # [2, 1]
 
# retrieve an element
see a[1]</syntaxhighlight>
 
=={{header|RLaB}}==
<syntaxhighlight lang="rlab">
<lang RLaB>
// 1-D (row- or column-vectors)
// Static:
Line 4,497 ⟶ 7,799:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Robotic}}==
Robotic does not natively support arrays of any kind.
However, using [https://www.digitalmzx.net/wiki/index.php?title=Counter_interpolation Counter Interpolation], we can create a simple (faux) array.
<syntaxhighlight lang="robotic">
set "index" to 0
. "Assign random values to array"
: "loop"
set "array&index&" to random 0 to 99
inc "index" by 1
if "index" < 100 then "loop"
 
* "Value of index 50 is ('array('50')')."
end
</syntaxhighlight>
 
You can even create multi-dimensional arrays using the Counter Interpolation method.
<syntaxhighlight lang="robotic">
set "xx" to 0
set "yy" to 0
. "Assign random values to array"
: "loopX"
set "array&xx&,&yy&" to random 0 to 99
inc "xx" by 1
if "xx" < 32 then "loopX"
set "xx" to 0
inc "yy" by 1
if "yy" < 32 then "loopX"
 
* "Value of 16,16 is ('array('16'),('16')')."
end
</syntaxhighlight>
 
Because arrays aren't built in, there are no functions that allow you to manipulate the data you create within an array. You would have to create your own function when, for example, you want to sort numbers from least to greatest.
 
=={{header|RPG}}==
Line 4,503 ⟶ 7,839:
{{works with|ILE RPG}}
 
<langsyntaxhighlight lang="rpg">
//-Static array
//--def of 10 el array of integers, initialised to zeros
Line 4,531 ⟶ 7,867:
/end-free
</syntaxhighlight>
</lang>
 
{{works with|ILE RPG v7.1+}}
<nowiki>**</nowiki>free
//-Static array
//--def of 10 el array of integers, initialised to zeros
dcl-s array int(10) dim(10) inz;
//--def an el
dcl-s el_1 int(10) inz(0);
//-assign first el
//--first element of RPG array is indexed with 1
array(1) = 111;
//-get first el of array
el_1 = array(1);
//--display it
dsply ('First el of array='+%char(el_1));
//--displays: First el of array=111
//---or shorter, without "el_1"
dsply ('First el of array='+%char(array(1)));
//--displays: First el of array=111
 
=={{header|RingRPL}}==
Arrays have a predefined size and can only contain floating point numbers.
 
They can be created either by enumerating their elements one by one or by creating an array with the same value everywhere:
Dynamic
[ 1 2 3 4 5 ]
 
{ 5 } -1 CON <langspan ringstyle="color:grey">#@ create anthe array with[ one-1 string-1 in-1 it-1 -1 ]</span>
To assign a value, you can use either <code>PUT</code> or <code>PUTI</code>. <code>PUT</code> returns only the updated array - other input arguments are gone - whilst <code>PUTI</code> leaves in stack the index, incremented by one : you can then easily assign another value to the following position.
a = ['foo']
[ 1 2 3 4 5 ] 3 10 PUT
 
returns:
# add items
a 1: +[ 1 2 10 4 5 # ["foo", 1]
but
 
[ 1 2 3 4 5 ] 3 10 PUTI
# set the value at a specific index in the array
returns:
a[1] = 2 # [2, 1]
2: [ 1 2 10 4 5 ]
 
1: 4
# retrieve an element
Similarly, you can use <code>GET</code> or <code>GETI</code> to retrieve an element.
see a[1]</lang>
[ 10 20 30 40 50 ] 3 GET
returns:
1: 30
but
[ 10 20 30 40 50 ] 3 GETI
returns:
3: [ 10 20 30 40 50 ]
2: 4
1: 30
Another useful data structure in RPL is the list, which is very similar in use to arrays: <code>PUT</code>, <code>PUTI</code>, <code>GET</code> and <code>GETI</code> give the same results. Lists can contain any kind of objects, including lists. Beside direct assignment through <code>PUT</code>, it is also possible to append an element at the beginning or the end of the list with the <code>+</code> operator.
In recent RPL versions, several functions such as <code>SORT</code> can be applied only to lists, which make this data structure very versatile. The only drawback is the necessity to create a list element by element
by direct enumeration:
{ 1 2 3 4 5 }
by concatenation:
{ 1 2 3 } { 4 5 } +
or through a loop:
{ } 1 5 '''FOR''' j j + '''NEXT'''
 
=={{header|Ruby}}==
Line 4,554 ⟶ 7,929:
Dynamic
 
<langsyntaxhighlight lang="ruby"># create an array with one object in it
a = ['foo']
 
Line 4,573 ⟶ 7,948:
 
# retrieve an element
puts a[0]</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print "Enter array 1 greater than 0"; : input a1
print "Enter array 2 greater than 0"; : input a2
Line 4,583 ⟶ 7,959:
chrArray$(1,1) = "Hello"
numArray(1,1) = 987.2
print chrArray$(1,1);" ";numArray(1,1)</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 4,591 ⟶ 7,967:
By default, arrays are immutable unless defined otherwise.
 
<langsyntaxhighlight lang="rust">let a = [1, 2, 3]; // immutable array
let mut m = [1, 2, 3]; // mutable array
let zeroes = [0; 200]; // creates an array of 200 zeroes</langsyntaxhighlight>
 
To get the length and iterate,
 
<langsyntaxhighlight lang="rust">let a = [1, 2, 3];
a.len();
for e in a.iter() {
e;
}</langsyntaxhighlight>
 
Accessing a particular element uses subscript notation, starting from 0.
 
<langsyntaxhighlight lang="rust">let names = ["Graydon", "Brian", "Niko"];
names[1]; // second element</langsyntaxhighlight>
 
Dynamic arrays in Rust are called vectors.
 
<langsyntaxhighlight lang="rust">let v = vec![1, 2, 3];</langsyntaxhighlight>
 
However, this defines an immutable vector. To add elements to a vector, we need to define v to be mutable.
 
<langsyntaxhighlight lang="rust">let mut v = vec![1, 2, 3];
v.push(4);
v.len(); // 4</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">-- a is an array of INTs
a :ARRAY{INT};
-- create an array of five "void" elements
Line 4,630 ⟶ 8,006:
b[1] := c; -- syntactic sugar for b.aset(1, c)
-- append another array
b := b.append(|5.5|);</langsyntaxhighlight>
 
=={{header|Scala}}==
Arrays are not used often in Scala, since they are mutable and act differently to other collections with respect to type erasure, but are necessary for interoperability with Java. Alternatives such as List, Seq, and Vector are more commonly used.
<langsyntaxhighlight lang="scala">// Create a new integer array with capacity 10
val a = new Array[Int](10)
 
Line 4,644 ⟶ 8,020:
 
// Retrieve item at element 2
val c = b(2)</langsyntaxhighlight>
Dynamic arrays can be made using <code>ArrayBuffer</code>s:
<langsyntaxhighlight lang="scala">val a = new collection.mutable.ArrayBuffer[Int]
a += 5 // Append value 5 to the end of the list
a(0) = 6 // Assign value 6 to element 0</langsyntaxhighlight>
 
=={{header|Scheme}}==
Lists are more often used in Scheme than vectors.
 
<langsyntaxhighlight lang="scheme">(let ((array #(1 2 3 4 5)) ; vector literal
(array2 (make-vector 5)) ; default is unspecified
(array3 (make-vector 5 0))) ; default 0
(vector-set! array 0 3)
(vector-ref array 0)) ; 3</langsyntaxhighlight>
 
=={{header|Scratch}}==
Line 4,669 ⟶ 8,045:
Every type, which can be mapped to integer, can be used as index type.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: charArray is array [char] string; # Define an array type for arrays with char index.
Line 4,703 ⟶ 8,079:
array1 := array3[2 len 4]; # Assign a slice of four elements beginning with the second element.
array1 := array3 & array6; # Concatenate two arrays and assign the result to array1.
end func;</langsyntaxhighlight>
 
=={{header|Self}}==
Line 4,711 ⟶ 8,087:
Creating simple vectors:
<syntaxhighlight lang ="self">vector copySize: 100</langsyntaxhighlight>
<langsyntaxhighlight lang="self">vector copySize: 100 FillingWith: anObject</langsyntaxhighlight>
 
A polymorphic vector:
<langsyntaxhighlight lang="self">(1 & 'Hello' & 2.0 & someObject) asVector</langsyntaxhighlight>
 
Using a vector:
<langsyntaxhighlight lang="self">|v|
"creates an vector that holds up to 20 elements"
v: vector copySize: 20.
Line 4,726 ⟶ 8,102:
(v at: 9) printLine.
"put 100 as second value"
vat: 1 Put: 100.</langsyntaxhighlight>
 
Enumeration:
<langsyntaxhighlight lang="self">v do: [:each | each printLine].
v copy mapBy: [:each | each squared].
v copy filterBy: [:each | each > 10].</langsyntaxhighlight>
 
Using a squence:
<langsyntaxhighlight lang="self">|s|
"creates a new sequence"
s: sequence copyRemoveAll.
Line 4,744 ⟶ 8,120:
s removeFirst.
"Check size"
s size printLine.</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">// Initial creation of an array
set a to (1, 2, 3)
 
// pushing a value to the array
// Both approaches are valid
insert 4 after a
push 5 into a
 
put a -- (1, 2, 3, 4, 5)
 
// Treating the array as a stack, using `push` and `pop`
pop a into v1
 
put a -- (1, 2, 3, 4)
put v1-- 5
 
// Treating the array as a queue, using `push` and `pull`
push 6 into a
pull a into v2
 
put a -- (2, 3, 4, 6)
put v2 -- 1
 
// Referencing the items in the array
put the second item of a -- 3
 
// Changing the values in the array
set the third item of a to "abc"
put a -- (2, 3, "abc", 6)</syntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby"># create an empty array
var arr = [];
 
Line 4,775 ⟶ 8,182:
 
# retrieve an element
say arr[-1]; #=> 'baz'</langsyntaxhighlight>
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
PROCEDURE STATIC;
BEGIN
INTEGER ARRAY X(0:4);
 
X(0) := 10;
X(1) := 11;
X(2) := 12;
X(3) := 13;
X(4) := X(0);
 
OUTTEXT("STATIC AT 4: ");
OUTINT(X(4), 0);
OUTIMAGE
END STATIC;
PROCEDURE DYNAMIC(N); INTEGER N;
BEGIN
INTEGER ARRAY X(0:N-1);
X(0) := 10;
X(1) := 11;
X(2) := 12;
X(3) := 13;
X(4) := X(0);
OUTTEXT("DYNAMIC AT 4: ");
OUTINT(X(4),0);
OUTIMAGE
END DYNAMIC;
STATIC;
DYNAMIC(5)
END ARRAYS.
</syntaxhighlight>
{{out}}
<pre>
STATIC AT 4: 10
DYNAMIC AT 4: 10
</pre>
One can write an ArrayList class like Java has in package java.util.
<syntaxhighlight lang="simula">BEGIN
 
CLASS ITEM;;
 
CLASS ITEMARRAY(N); INTEGER N;
BEGIN
REF(ITEM) ARRAY DATA(1:N);
OUTTEXT("NEW ITEMARRAY WITH "); OUTINT(N, 0); OUTTEXT(" ELEMENTS");
OUTIMAGE;
END;
 
CLASS ARRAYLIST;
BEGIN
 
PROCEDURE EXPAND(N); INTEGER N;
BEGIN
INTEGER I;
REF(ITEMARRAY) TEMP;
OUTTEXT("EXPAND TO CAPACITY "); OUTINT(N, 0); OUTIMAGE;
TEMP :- NEW ITEMARRAY(N);
FOR I := 1 STEP 1 UNTIL SIZE DO
TEMP.DATA(I) :- ITEMS.DATA(I);
ITEMS :- TEMP;
END;
 
PROCEDURE ADD(T); REF(ITEM) T;
BEGIN
IF SIZE + 1 > CAPACITY THEN
BEGIN
CAPACITY := 2 * CAPACITY;
EXPAND(CAPACITY);
END;
SIZE := SIZE + 1;
ITEMS.DATA(SIZE) :- T;
OUTTEXT("SIZE IS "); OUTINT(SIZE, 0); OUTIMAGE;
END;
 
PROCEDURE REMOVE(I); INTEGER I;
BEGIN
INTEGER J;
IF I < 1 OR I > SIZE THEN ERROR("REMOVE: INDEX OUT OF BOUNDS");
FOR J := I STEP 1 UNTIL SIZE - 1 DO
ITEMS.DATA(J) :- ITEMS.DATA(J + 1);
ITEMS.DATA(SIZE) :- NONE;
SIZE := SIZE - 1;
END;
 
REF(ITEM) PROCEDURE GET(I); INTEGER I;
BEGIN
IF I < 1 OR I > SIZE THEN ERROR("GET: INDEX OUT OF BOUNDS");
GET :- ITEMS.DATA(I);
END;
 
INTEGER CAPACITY;
INTEGER SIZE;
REF(ITEMARRAY) ITEMS;
 
CAPACITY := 20;
SIZE := 0;
EXPAND(CAPACITY);
 
END;
 
 
ITEM CLASS TEXTITEM(TXT); TEXT TXT;;
 
ARRAYLIST CLASS TEXTARRAYLIST;
BEGIN
PROCEDURE ADD(T); TEXT T;
THIS TEXTARRAYLIST QUA ARRAYLIST.ADD(NEW TEXTITEM(T));
TEXT PROCEDURE GET(I); INTEGER I;
GET :- THIS TEXTARRAYLIST QUA ARRAYLIST.GET(I) QUA TEXTITEM.TXT;
END;
 
 
ITEM CLASS REALITEM(X); REAL X;;
 
ARRAYLIST CLASS REALARRAYLIST;
BEGIN
PROCEDURE ADD(X); REAL X;
THIS REALARRAYLIST QUA ARRAYLIST.ADD(NEW REALITEM(X));
REAL PROCEDURE GET(I); INTEGER I;
GET := THIS REALARRAYLIST QUA ARRAYLIST.GET(I) QUA REALITEM.X;
END;
 
 
REF(TEXTARRAYLIST) LINES;
REF(REALARRAYLIST) REALS;
INTEGER I;
 
LINES :- NEW TEXTARRAYLIST;
LINES.ADD("WE");
LINES.ADD("HAVE");
LINES.ADD("SEEN");
LINES.ADD("THAT");
LINES.ADD("ARRAYS");
LINES.ADD("ARE");
LINES.ADD("A");
LINES.ADD("VERY");
LINES.ADD("CONVENIENT");
LINES.ADD("WAY");
LINES.ADD("OF");
LINES.ADD("STORING");
LINES.ADD("SIMPLE");
LINES.ADD("VALUES");
LINES.ADD("AND");
LINES.ADD("REFERENCES");
LINES.ADD("TO");
LINES.ADD("MORE");
LINES.ADD("COMPLEX");
LINES.ADD("CLASS");
LINES.ADD("OBJECTS");
LINES.ADD("IN");
LINES.ADD("AN");
LINES.ADD("ORDERED");
LINES.ADD("LIST");
LINES.ADD(".");
 
FOR I := 1 STEP 1 UNTIL LINES.SIZE DO
BEGIN
OUTINT(I, 0); OUTTEXT(": ");
OUTTEXT(LINES.GET(I)); OUTIMAGE;
END;
 
 
REALS :- NEW REALARRAYLIST;
FOR I := 1 STEP 1 UNTIL 10 DO
REALS.ADD(I * I);
 
FOR I := 1 STEP 1 UNTIL REALS.SIZE DO
BEGIN
OUTINT(I, 4); OUTTEXT(": ");
OUTFIX(REALS.GET(I),2,10); OUTIMAGE;
END;
 
FOR I := REALS.SIZE STEP - 2 UNTIL 1 DO
REALS.REMOVE(I);
 
FOR I := 1 STEP 1 UNTIL REALS.SIZE DO
BEGIN
OUTINT(I, 4); OUTTEXT(": ");
OUTFIX(REALS.GET(I),2,10); OUTIMAGE;
END;
 
END;
</syntaxhighlight>
{{out}}
<pre>EXPAND TO CAPACITY 20
NEW ITEMARRAY WITH 20 ELEMENTS
SIZE IS 1
SIZE IS 2
SIZE IS 3
SIZE IS 4
SIZE IS 5
SIZE IS 6
SIZE IS 7
SIZE IS 8
SIZE IS 9
SIZE IS 10
SIZE IS 11
SIZE IS 12
SIZE IS 13
SIZE IS 14
SIZE IS 15
SIZE IS 16
SIZE IS 17
SIZE IS 18
SIZE IS 19
SIZE IS 20
EXPAND TO CAPACITY 40
NEW ITEMARRAY WITH 40 ELEMENTS
SIZE IS 21
SIZE IS 22
SIZE IS 23
SIZE IS 24
SIZE IS 25
SIZE IS 26
1: WE
2: HAVE
3: SEEN
4: THAT
5: ARRAYS
6: ARE
7: A
8: VERY
9: CONVENIENT
10: WAY
11: OF
12: STORING
13: SIMPLE
14: VALUES
15: AND
16: REFERENCES
17: TO
18: MORE
19: COMPLEX
20: CLASS
21: OBJECTS
22: IN
23: AN
24: ORDERED
25: LIST
26: .
EXPAND TO CAPACITY 20
NEW ITEMARRAY WITH 20 ELEMENTS
SIZE IS 1
SIZE IS 2
SIZE IS 3
SIZE IS 4
SIZE IS 5
SIZE IS 6
SIZE IS 7
SIZE IS 8
SIZE IS 9
SIZE IS 10
1: 1.00
2: 4.00
3: 9.00
4: 16.00
5: 25.00
6: 36.00
7: 49.00
8: 64.00
9: 81.00
10: 100.00
1: 1.00
2: 9.00
3: 25.00
4: 49.00
5: 81.00
</pre>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">slate[1]> #x := ##(1 2 3).
{1. 2. 3}
slate[2]> x
Line 4,791 ⟶ 8,473:
1
slate[7]> x at: 0.
1</langsyntaxhighlight>
 
=={{header|SmallBASIC}}==
<syntaxhighlight lang="SmallBASIC">
' One dimensional arrays
DIM A ' empty array
DIM B(3) ' empty array with 4 elements
DIM C(2 TO 4) ' empty array with elements 2,3 and 4
D = [1,2,3,4] ' assign array in one statement
E = ["one", "two", "three"] ' string array
F = [1, "two", [1,2,3]] ' arrays can contain mixed data types
 
B[0] = 1 ' use [] or () to assign value to
B(1) = 2 ' element or access elements
 
A << 2 ' append element to an array
 
print F ' print whole array -> Output: [1,two,[1,2,3]]
print F[0] ' print first element -> Output: 1
print F(1) ' print second element -> Output: two
 
' Multi dimensional arrays
DIM A(2,0) ' column array (vector) with 3 elements
DIM B(2,2) ' empty 2D array (matrix) with 3x3 elements
DIM C(2,2,2) ' empty 3D array with 3x3x3 elements
 
A[0,0] = 1
A[1,0] = 2
A[2,0] = 3
 
' Math with arrays
 
A = [1,2,3]
B = [4,5,6]
 
print A + B ' Output: [5,7,9]
print 3 * A ' Output: [3,6,9]
print A * B ' Output: [4,10,18]
 
C = [1;2;3] ' vector
D = [1,2,3;4,5,6;7,8,9] ' 2D matrix
 
print D * C ' matrix * vector -> Output [14;32;50]
print D * D ' matrix * matrix -> Output [30,36,42;66,81,96;102,126,150]
</syntaxhighlight>
 
 
=={{header|Smalltalk}}==
Line 4,802 ⟶ 8,529:
Literal Arrays (Array constants):
<langsyntaxhighlight lang="smalltalk">#(1 2 3 'four' 5.0 true false nil (10 20) $a)</langsyntaxhighlight>
a polymorphic array containing integers, a string, a float, booleans, a nil, another array with integers and a character constant.
 
Programatic use:
<langsyntaxhighlight lang="smalltalk">|array|
"creates an array that holds up to 20 elements"
array := Array new: 20 .
Line 4,817 ⟶ 8,544:
array := Array withAll: #('an' 'apple' 'a' 'day' 'keeps' 'the' 'doctor' 'away').
"Replacing apple with orange"
array at: 2 put: 'orange'.</langsyntaxhighlight>
 
<langsyntaxhighlight lang="smalltalk">"assigning values to an array"
"suppose array is bound to an array of 20 values"
array at: 5 put: 'substitute fifth element'.
Line 4,825 ⟶ 8,552:
[ array at: 21 put: 'error' ]
on: SystemExceptions.IndexOutOfRange
do: [ :sig | 'Out of range!' displayNl ].</langsyntaxhighlight>
 
<langsyntaxhighlight lang="smalltalk">"retrieving a value from an array"
#($a $b $c) at: 2</langsyntaxhighlight>
 
Enumeration:
<langsyntaxhighlight lang="smalltalk">array do:[:each | each printOn: aStream ]
array collect:[:each | each squared|
array select:[:each | each > 10]</langsyntaxhighlight>
 
{{works with|Pharo}}
Line 4,839 ⟶ 8,566:
{{works with|Squeak}}
Constructing an Array from evaluated expressions:
<langsyntaxhighlight lang="smalltalk">{ Time now . 10 . Date today . 'foo' }</langsyntaxhighlight>
this construct evaluates each expression and creates a 4-element array containing a time, int, date and string object.
 
OrderedCollection:
<langsyntaxhighlight lang="smalltalk">oc := OrderedCollection withAll: #(4 5 6).
oc add:1. oc add:2. oc add:3.
foo := oc removeFirst.
Line 4,855 ⟶ 8,582:
oc findFirst:[:el | el isString]
"hundreds of other methods skipped here.."
</syntaxhighlight>
</lang>
 
=={{header|SNOBOL4}}==
SNOBOL4 supports multi-dimensional arrays and array initialization.
<langsyntaxhighlight SNOBOL4lang="snobol4"> ar = ARRAY("3,2") ;* 3 rows, 2 columns
fill i = LT(i, 3) i + 1 :F(display)
ar<i,1> = i
Line 4,868 ⟶ 8,595:
OUTPUT = "Row " ar<j,1> ": " ar<j,2>
+ :S(display)
END</langsyntaxhighlight>
{{out}}
<pre>
Line 4,875 ⟶ 8,602:
Row 3: 3-count
</pre>
 
=={{header|SPL}}==
<syntaxhighlight lang="spl">a[1] = 2.5
a[2] = 3
a[3] = "Result is "
#.output(a[3],a[1]+a[2])</syntaxhighlight>
{{out}}
<pre>
Result is 5.5
</pre>
 
=={{header|SSEM}}==
At the machine level, an array is a block of sequential storage addresses. Modern computer architectures support arrays through <i>indexed addressing</i>, where the contents of a particular register can be used to provide an offset from some specified address. A program to find the sum of a four-element array beginning at address <tt>array</tt> might look, in pseudocode, like this:
<pre> load register 0, #0 ; running total
load register 1, #0 ; index
loop: add register 0, array+register 1
add register 1, #1
compare register 1, #4
branchIfLess loop</pre>
If we do not know in advance how many elements the array will have, we can mark the end with a special value (say, zero) and test for that. Again in pseudocode:
<pre> load register 0, #0 ; running total
load register 1, #0 ; index
loop: load register 2, array+register 1
compare register 2, #0
branchIfEqual done
add register 0, register 2
add register 1, #1
goTo loop
done: ; program continues with sum in register 0</pre>
On a machine like the SSEM, which has only one addressing mode and only one general-purpose register (the accumulator or <tt>c</tt>), we can achieve the same things using <i>instruction arithmetic</i>—also known as <i>self-modifying code</i>. Since an instruction that refers to address <math>n+1</math> can be obtained by adding one to an instruction that refers to address <math>n</math>, the pseudocode to find the sum of a four-element array (and store it at address <tt>sum</tt>, which we assume initially holds zero) becomes:
<pre>loop: load accumulator, sum
instr: add accumulator, array
store accumulator, sum
load accumulator, instr
add accumulator, #1
compare accumulator, #(add accumulator, array+4)
branchIfEqual done
store accumulator, instr
goTo loop
done: ; program continues</pre>
We are now in a position to translate this algorithm into SSEM instructions and run it. As always, the SSEM version is a bit fiddlier than the pseudocode because the SSEM has no <tt>load</tt> or <tt>add</tt> instructions; but it follows the pseudocode as closely as the instruction set allows, so it should be comparatively readable. As a test, we shall sum an array of the first four positive integers—a very significant operation for the Pythagoreans of old—and halt with the accumulator holding the result.
<syntaxhighlight lang="ssem">10101000000000100000000000000000 0. -21 to c
11101000000000010000000000000000 1. Sub. 23
00101000000001100000000000000000 2. c to 20
00101000000000100000000000000000 3. -20 to c
10101000000001100000000000000000 4. c to 21
10000000000000100000000000000000 5. -1 to c
01001000000000010000000000000000 6. Sub. 18
00101000000001100000000000000000 7. c to 20
00101000000000100000000000000000 8. -20 to c
10000000000001100000000000000000 9. c to 1
01101000000000010000000000000000 10. Sub. 22
00000000000000110000000000000000 11. Test
01001000000001000000000000000000 12. Add 18 to CI
11001000000000000000000000000000 13. 19 to CI
10101000000000100000000000000000 14. -21 to c
00101000000001100000000000000000 15. c to 20
00101000000000100000000000000000 16. -20 to c
00000000000001110000000000000000 17. Stop
10000000000000000000000000000000 18. 1
11111111111111111111111111111111 19. -1
00000000000000000000000000000000 20. 0
00000000000000000000000000000000 21. 0
11011000000000010000000000000000 22. Sub. 27
10000000000000000000000000000000 23. 1
01000000000000000000000000000000 24. 2
11000000000000000000000000000000 25. 3
00100000000000000000000000000000 26. 4</syntaxhighlight>
The program could easily be modified to work with arrays of unknown length, if required, along the lines of the second pseudocode example above.
 
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
(* create first array and assign elements *)
-val first = Array.tabulate (10,fn x=>x+10) ;
val first = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array
 
(* assign to array 'second' *)
-val second=first ;
val second = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array
 
(* retrieve 5th element *)
-Array.sub(second,4);
val it = 14: int
</syntaxhighlight>
=={{header|Stata}}==
In Stata, there are mainly two ways to work with arrays: the '''[http://www.stata.com/help.cgi?matrix matrix]''' command can create and manipulate arrays, either elementwise or using matrix functions. And there is Mata, a matrix programming language similar to MATLAB, R or SAS/IML.
 
There are ways to exchange data between Stata datasets, Stata matrices, and Mata matrices:
 
* the Mata functions '''[http://www.stata.com/help.cgi?mf_st_data st_data]''' and '''[http://www.stata.com/help.cgi?mf_st_view st_view]''' are used to read data from the current Stata dataset to a Mata matrix (st_data copies data, while st_view creates a view, that can be used to modify the dataset in place).
* The Mata function '''[http://www.stata.com/help.cgi?mf_st_store st_store]''' is used to write a Mata matrix into the current dataset.
* the Mata function '''[http://www.stata.com/help.cgi?mf_st_matrix st_matrix]''' is used to read or write from/to a Stata matrix to a Mata matrix.
* the '''[http://www.stata.com/help.cgi?mkmat mkmat]''' and '''svmat''' commands are used to store data from a dataset to a Stata matric and vice versa.
 
Both Stata matrices and Mata matrices have either one or two dimensions. For both, functions are provided for the usual linear algebra functions (Cholesky and SVD decompositions, for instance). Stata matrices must contain real numbers (or missing values), while Mata matrices may contain complex numbers, or strings (but either a matrix contains only numeric values, either it contains only string values).
 
=== Matrix command ===
<syntaxhighlight lang="stata">matrix a = 2,9,4\7,5,3\6,1,8
display det(a)
matrix svd u d v = a
matrix b = u*diag(d)*v'
matrix list b
* store the u and v matrices in the current dataset
svmat u
svmat v</syntaxhighlight>
 
=== Mata ===
<syntaxhighlight lang="stata">mata
a = 2,9,4\7,5,3\6,1,8
det(a)
svd(a, u=., s=., v=.)
// Notice that to reconstruct the matrix, v is not transposed here,
// while it is with -matrix svd- in Stata.
u*diag(s)*v</syntaxhighlight>
 
=={{header|Suneido}}==
<langsyntaxhighlight Suneidolang="suneido">array = Object('zero', 'one', 'two')
array.Add('three')
array.Add('five', at: 5)
array[4] = 'four'
Print(array[3]) --> 'three'</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">// Arrays are typed in Swift, however, using the Any object we can add any type. Swift does not support fixed length arrays
var anyArray = [Any]()
anyArray.append("foo") // Adding to an Array
anyArray.append(1) // ["foo", 1]
anyArray.removeAtIndex(1) // Remove object
anyArray[0] = "bar" // ["bar"]]</langsyntaxhighlight>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
// arrays are created as literals, by simply listing elements, or by a generator expression, or a combination.
def a: [1, 2, 3..7:2, 11];
$a -> !OUT::write
'
' -> !OUT::write
 
// Natural indexes start at 1
$a(1) -> !OUT::write
'
' -> !OUT::write
 
// But you can have an array start at any index
def b: -5:['foo', 'bar', 'qux'];
$b(-3) -> !OUT::write
'
' -> !OUT::write
 
// You can select a range
$a(3..last) -> !OUT::write
'
' -> !OUT::write
 
// Or a permutation/selection
$a([4,1,5]) -> !OUT::write
'
' -> !OUT::write
 
// Values in Tailspin are generally immutable, but there is a mutable slot in a function/templates.
// A mutable array can be appended
5 -> \(@: [1,2]; $ -> ..|@: $; $@ ! \) -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
[1, 2, 3, 5, 7, 11]
1
qux
[3, 5, 7, 11]
[5, 1, 7]
[1, 2, 5]
</pre>
 
=={{header|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.)
<langsyntaxhighlight lang="tcl">set ary {}
 
lappend ary 1
Line 4,900 ⟶ 8,784:
lset ary 0 2
 
puts [lindex $ary 0]</langsyntaxhighlight>
Note also that serialization is automatic on treating as a string:
<langsyntaxhighlight lang="tcl">puts $ary; # Print the whole array</langsyntaxhighlight>
 
=={{header|Tern}}==
Arrays and lists are synonymous in Tern.
<syntaxhighlight lang="tern">let list = [1, 22, 3, 24, 35, 6];
 
for(i in list) {
println(i);
}
</syntaxhighlight>
 
{{out}}
<pre>1
22
3
24
35
6</pre>
 
=={{header|TI-83 BASIC}}==
Line 4,908 ⟶ 8,809:
<br>'''List'''<br>
One dimensional arrays are lists, they can be set as a whole with the syntax:
<langsyntaxhighlight lang="ti83b">{1,2,3,4,5}→L1</langsyntaxhighlight>
using only numerical values separated by commas and enclosed by curly braces.<br>
Lists can be accessed as a whole using L1-L6 or a custom list name
Line 4,914 ⟶ 8,815:
You can also retrieve a single value from a list using the name of the list and
the position of the value, which starts at 1 on the left.
<langsyntaxhighlight lang="ti83b">{1,2,3,4,5}→L1
Disp L1(3)
0→L1(4)</langsyntaxhighlight>
This would return 3 and set the fourth list element to 0.
<br>You can dynamically define or delete lists by:
<langsyntaxhighlight lang="ti83b">20→dim(L1)
DelVar L1
5→dim(∟MYLIST)
DelVar ∟MYLIST</langsyntaxhighlight>
'''Matrix'''<br>
Two dimensional arrays are matrices. Similar, set them and retrieve numbers using the syntax:
<langsyntaxhighlight lang="ti83b">[[11,21,31,41][12,22,32,42][13,23,33,43]]→[A]
Disp [A](1,3)
0→[A](4,2)</langsyntaxhighlight>
This would return 13 and set the element (4,2) to 0.
<br>You can dynamically define or delete matrices by:
<langsyntaxhighlight lang="ti83b">{5,5}→dim([A])
DelVar [A]</langsyntaxhighlight>
 
=={{header|TorqueScript}}==
Arrays in TorqueScript:
 
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
$array[0] = "hi";
$array[1] = "hello";
 
for(%i=0;%i<2;%i++)
echo($array[%i]);</langsyntaxhighlight>
 
=> hi
Line 4,947 ⟶ 8,848:
=> hello
 
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
$array["Greet",0] = "hi";
$array["Greet",1] = "hello";
 
for(%i=0;%i<2;%i++)
echo($array["Greet",%i]);</langsyntaxhighlight>
 
=> hi
 
=> hello
 
=={{header|Transd}}==
Arrays in Transd are implemented in the form of dynamic containers: Vectors. Vector is
a type parameterized container (also known as "generic"), that is a Vector object can
only hold values of a single type.
 
Vectors can be created as empty containers, or they can be initialized with some values at the time of creation.
 
<syntaxhighlight lang="scheme">module1 : {
v1: Vector<Int>(),
v2: Vector<String>(),
v3: Vector<Int>([1,2,3,4]),
v4: Vector<String>(["one","two","three"]),
// the type of vector values can automaticaly deduced
v5: [1.0, 2.5, 8.6], // Vector<Double>
v6: ["one","two","three"] // Vector<String>
}</syntaxhighlight>
 
Individual elements in a vector can be read, appended, and deleted.
 
<syntaxhighlight lang="scheme">(with v [1,2,3]
(textout (get v 1)) // <= 2
(erase v 1)
(textout v) // <= [1, 3]
(append v 7)
(textout v) // <= [1, 3, 7]
)</syntaxhighlight>
 
All standard container operations can be applied to vectors:
 
<syntaxhighlight lang="scheme">(with v [3,1,5,2,4]
(textout (reverse v)) // <= [4, 2, 5, 1, 3]
(textout (sort v)) // <= [1, 2, 3, 4, 5]
(textout (shuffle v)) // <= [5, 3, 4, 1, 2]
)</syntaxhighlight>
 
=={{header|TXR}}==
Line 4,999 ⟶ 8,935:
[ve nil..nil] ;; another way
[ve 1 3] ;; yields #(2 3)
(set [ve 0 ..2] '(a b)) ;; changes vector to #(a b 3)
(set [ve 0 ..2] #(1 2)) ;; changes vector to #(1 2 3)
(set [li 0 ..1] nil) ;; changes list to #(2 3), deleting 1.
(set [li t ..t] '(4 5)) ;; changes list to #(2 3 4 5), appending (4 5)
(set [ve 1 ..2] '(0 0)) ;; changes vector to #(1 0 0 3), replacing 2 with 0 0</pre>
 
====In The Pattern Language====
Line 5,023 ⟶ 8,959:
A complete program which turns comma-separated into tab-separated,
where the first and last field from each line are exchanged:
<langsyntaxhighlight lang="txr">@(collect)
@line
@(bind f @(split-str line ","))
Line 5,029 ⟶ 8,965:
@{f[-1]}@\t@{f[1..-1] "\t"}@\t@{f[0]}
@(end)
@(end)</langsyntaxhighlight>
 
====Other Kinds of Objects====
Line 5,039 ⟶ 8,975:
=={{header|uBasic/4tH}}==
uBasic/4tH has only one single, global array of 256 integers. Since it's fixed, it can't be declared.
<syntaxhighlight lang="text">Let @(0) = 5 : Print @(0)</langsyntaxhighlight>
 
=={{header|Unicon}}==
Unicon's arrays are provided by the list type, which is a hybrid list/array type.
Lists of integers or reals, if not polluted by other types nor changed in size, may use a C-compatible internal representation (long and double).
<syntaxhighlight lang="text">L := list(100); L[12] := 7; a := array(100, 0.0); a[3] +:= a[1]+a[2]</syntaxhighlight>
 
=={{header|UNIX Shell}}==
Bash 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.
Line 5,048 ⟶ 8,990:
 
To create an array:
<langsyntaxhighlight lang="bash">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)</langsyntaxhighlight>
To obtain the number of items in an array:
<langsyntaxhighlight lang="bash">count=${#alist[*]}
echo "The number of items in alist is ${#alist[*]}"</langsyntaxhighlight>
To iterate up over the items in the array:
<langsyntaxhighlight lang="bash">x=0
while [[ $x < ${#alist[*]} ]]; do
echo "Item $x = ${alist[$x]}"
: $((x++))
done</langsyntaxhighlight>
To iterate down over theitems in an array:
<langsyntaxhighlight lang="bash">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</langsyntaxhighlight>
To append to an array, use the current number of items in the array as the next index:
<langsyntaxhighlight lang="bash">alist[${#alist[*]}]=new_item</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="bash"># shell function to append values to an array
# push LIST VALUES ...
push() {
Line 5,081 ⟶ 9,023:
 
push alist "one thing to add"
push alist many words to add</langsyntaxhighlight>
To delete a single array item, the first item:
<syntaxhighlight lang ="bash">unset alist[0]</langsyntaxhighlight>
To delete and return the last item in an array (e.g., "pop" function):
<langsyntaxhighlight lang="bash"># pop ARRAY -- pop the last item on ARRAY and output it
 
pop() {
Line 5,107 ⟶ 9,049:
c
pop alist
No items in alist</langsyntaxhighlight>
To delete all the items in an array:
<syntaxhighlight lang ="bash">unset alist[*]</langsyntaxhighlight>
To delete the array itself (and all items in it, of course):
<syntaxhighlight lang ="bash">unset alist</langsyntaxhighlight>
 
=={{header|உயிர்/Uyir}}==
<langsyntaxhighlight lang="உயிர்/Uyiruyir">
இருபரிமாணணி வகை எண் அணி {3, 3};
இருபரிமாணணி2 வகை எண் அணி {3} அணி {3};
Line 5,124 ⟶ 9,066:
செவ்வகணி = அணி { அணி {10, 22, 43}, அணி {31, 58, 192}, அணி {46, 73, 65} };
முக்கோண்ணி = அணி { அணி {1}, அணி {2, 3}, அணி {4, 5, 6}, அணி {7, 8, 9, 1, 2} };
</syntaxhighlight>
</lang>
 
=={{header|Vala}}==
Non-dynamic arrays:
<langsyntaxhighlight lang="vala">
int[] array = new int[10];
 
Line 5,135 ⟶ 9,077:
 
stdout.printf("%d\n", array[0]);
</syntaxhighlight>
</lang>
 
{{libheader|Gee}}
Dynamic Arrays with Gee:
<langsyntaxhighlight lang="vala">
var array = new ArrayList<int> ();
 
Line 5,148 ⟶ 9,090:
 
stdout.printf("%d\n", array[0]);
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
The Option Base statement is used at the module level to declare the default lower bound for array subscripts.
<syntaxhighlight lang="vb">Option Base {0|1} </syntaxhighlight>
<syntaxhighlight lang="vb">Sub matrix()
'create an array,
Dim a(3) As Integer
Dim i As Integer
'assign a value to it,
For i = 1 To 3
a(i) = i * i
Next i
'and retrieve an element
For i = 1 To 3
Debug.Print a(i)
Next i
'dynamic
Dim d() As Integer
ReDim d(3)
For i = 1 To 3
d(i) = i * i
Next i
'and retrieve an element
For i = 1 To 3
Debug.Print d(i)
Next i
'push a value to it - expand the array and preserve existing values
ReDim Preserve d(4)
d(4) = 16:
For i = 1 To 4
Debug.Print d(i)
Next i
End Sub</syntaxhighlight>
{{out}}
<pre> 1 4 9 1 4 9 1 4 9 16 </pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">'Arrays - VBScript - 08/02/2021
 
'create a static array
Dim a(3) ' 4 items : a(0), a(1), a(2), a(3)
'assign a value to elements
For i = 1 To 3
a(i) = i * i
Next
'and retrieve elements
buf=""
For i = 1 To 3
buf = buf & a(i) & " "
Next
WScript.Echo buf
'create a dynamic array
Dim d()
ReDim d(3) ' 4 items : d(0), d(1), d(2), d(3)
For i = 1 To 3
d(i) = i * i
Next
buf=""
For i = 1 To 3
buf = buf & d(i) & " "
Next
WScript.Echo buf
d(0) = 0
'expand the array and preserve existing values
ReDim Preserve d(4) ' 5 items : d(0), d(1), d(2), d(3), d(4)
d(4) = 16
buf=""
For i = LBound(d) To UBound(d)
buf = buf & d(i) & " "
Next
WScript.Echo buf
 
'create and initialize an array dynamicaly
b = Array(1, 4, 9)
'and retrieve all elements
WScript.Echo Join(b,",")
 
'Multi-Dimensional arrays
'The following creates a 5x4 matrix
Dim mat(4,3) </syntaxhighlight>
{{out}}
<pre>
1 4 9
1 4 9
0 1 4 9 16
1,4,9
</pre>
 
 
=={{header|VHDL}}==
<syntaxhighlight lang="vhdl">
entity Array_Test is
end entity Array_Test;
 
architecture Example of Array_test is
 
-- Array type have to be defined first
type Integer_Array is array (Integer range <>) of Integer;
 
-- Array index range can be ascending...
signal A : Integer_Array (1 to 20);
 
-- or descending
signal B : Integer_Array (20 downto 1);
 
-- VHDL array index ranges may begin at any value, not just 0 or 1
signal C : Integer_Array (-37 to 20);
 
-- VHDL arrays may be indexed by enumerated types, which are
-- discrete non-numeric types
type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
type Activities is (Work, Fish);
type Daily_Activities is array (Days) of Activities;
signal This_Week : Daily_Activities := (Mon to Fri => Work, Others => Fish);
 
type Finger is range 1 to 4; -- exclude thumb
type Fingers_Extended is array (Finger) of Boolean;
signal Extended : Fingers_Extended;
 
-- Array types may be unconstrained.
-- Objects of the type must be constrained
type Arr is array (Integer range <>) of Integer;
signal Uninitialized : Arr (1 to 10);
signal Initialized_1 : Arr (1 to 20) := (others => 1);
constant Initialized_2 : Arr := (1 to 30 => 2);
constant Const : Arr := (1 to 10 => 1, 11 to 20 => 2, 21 | 22 => 3);
signal Centered : Arr (-50 to 50) := (0 => 1, others => 0);
 
signal Result : Integer;
 
begin
 
A <= (others => 0); -- Assign whole array
B <= (1 => 1, 2 => 1,
3 => 2, others => 0); -- Assign whole array, different values
A (1) <= -1; -- Assign individual element
A (2 to 4) <= B (3 downto 1); -- Assign a slice
A (3 to 5) <= (2, 4, -1); -- Assign an aggregate
A (3 to 5) <= A (4 to 6); -- It is OK to overlap slices when assigned
 
-- VHDL arrays does not have 'first' and 'last' elements,
-- but have 'Left' and 'Right' instead
Extended (Extended'Left) <= False; -- Set leftmost element of array
Extended (Extended'Right) <= False; -- Set rightmost element of array
 
Result <= A (A'Low) + B (B'High);
 
end architecture Example;
</syntaxhighlight>
 
=={{header|Vim Script}}==
Lists can be used for dynamic arrays. Indexing starts at 0.
<langsyntaxhighlight lang="vim">" Creating a dynamic array with some initial values
let array = [3, 4]
 
Line 5,170 ⟶ 9,263:
call insert(array, 3, 2)
 
echo array</langsyntaxhighlight>
 
{{Out}}
<pre>[1, 2, 3, 4, 5]</pre>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">'Example of array of 10 int types:
Dim numbers As Integer() = New Integer(09) {}
'Example of array of 4 string types:
Dim words As String() = {"hello", "world", "from", "mars"}
Line 5,205 ⟶ 9,299:
list.Add(3)
list(0) = 2
Console.WriteLine(list(0))</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="go">// Arrays, in V (Vlang)
// Tectonics: v run arrays.v
module main
 
// A little bit about V variables. V does not allow uninitialized data.
// If an identifier exists, there is a valid value. "Empty" arrays have
// values in all positions, and V provides defaults for base types if not
// explicitly specified. E.g. 0 for numbers, `0` for rune, "" for strings.
 
// V uses := for definition and initialization, and = for assignment
 
// starts here, V programs start by invoking the "main" function.
pub fn main() {
// Array definition in source literal form (immutable)
array := [1,2,3,4]
// print first element, 0 relative indexing
println("array: $array")
println("array[0]: ${array[0]}")
// immutable arrays cannot be modified after initialization
// array[1] = 5, would fail to compile with a message it needs mut
 
// Dynamic arrays have some property fields
println("array.len: $array.len")
println("array.cap: $array.cap")
// array specs are [n]type{properties}
// Dynamic array definition, initial default values, "" for string
mut array2 := []string{}
// Append an element, using lessless
array2 << "First"
println("array2[0]: ${array2[0]}")
println("array2.len: $array2.len")
println("array2.cap: $array2.cap")
 
// Fixed array definition, capacity is fixed (! suffix), mutable entries
mut array3 := ["First", "Second", "Third"]!
println("array3: $array3")
array3[array3.len-1] = "Last"
println("array3: $array3")
println("array3.len: $array3.len")
 
// Advanced, array intiailization using non default value
mut array4 := [4]int{init: 42}
array4[2] = 21
println("array4: $array4")
 
// Arrays can be sliced, creating a copy
mut array5 := array4[0..3]
println("array5: $array5")
array5[2] = 10
println("array4: $array4")
println("array5: $array5")
}</syntaxhighlight>
 
{{out}}
<pre>
prompt$ v run arrays.v
array: [1, 2, 3, 4]
array[0]: 1
array.len: 4
array.cap: 4
array2[0]: First
array2.len: 1
array2.cap: 2
array3: ['First', 'Second', 'Third']
array3: ['First', 'Second', 'Last']
array3.len: 3
array4: [42, 42, 21, 42]
array5: [42, 42, 21]
array4: [42, 42, 21, 42]
array5: [42, 42, 10]</pre>
 
=={{header|Wee Basic}}==
<syntaxhighlight lang="wee basic">dim array$(2)
let array$(1)="Hello!"
let array$(2)="Goodbye!"
print 1 array$(1)</syntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight lang="wren">var arr = []
arr.add(1)
arr.add(2)
Line 5,217 ⟶ 9,391:
arr.add(arr[0])
arr.add(1)
arr.add(arr[-1]) // [0, 0, 1, 1]
 
arr[-1] = 0
arr.insert(-1, 0) // [0, 0, 1, 0, 0]
arr.removeAt(2) // [0, 0, 0, 0]</syntaxhighlight>
</lang>
 
=={{header|X86 Assembly}}==
<langsyntaxhighlight lang="asm">
section .text
global _start
Line 5,304 ⟶ 9,477:
resd 1
resd 1
</syntaxhighlight>
</lang>
Arrays in assembly are a reference to anything, from groups of data such as f/uArray to strings like _msg's or sArray.
Mutlidimentional arrays don't exist in assembly. To make a reference to one from assembly, we use a format as such. "row * r_len + column * member_size".
 
=={{header|XBS}}==
Arrays in [[XBS]] are very similar to [[JavaScript]].
<syntaxhighlight lang="xbs">set Array = ["Hello","World"];
log(Array[0]);
Array.push("Test");
log(?Array);
log(Array[?Array-1]);</syntaxhighlight>
 
=={{header|XLISP}}==
Like some other languages, XLISP refers to one-dimensional arrays as vectors. Examples of vector and array syntax, from a REPL (interactive session):
<langsyntaxhighlight lang="scheme">[1] (define a (make-vector 10)) ; vector of 10 elements initialized to the empty list
 
A
Line 5,333 ⟶ 9,514:
[8] (array-ref d 1 2 3) ; and get the value of d_1,2,3
 
10</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
char A(10); \creates a static array of 10 bytes, pointed to by "A"
char B; \declares a variable for a pointer to a dynamic array
Line 5,343 ⟶ 9,524:
B(7):= 28;
IntOut(0, A(3)+B(7)); \displays 42
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">dim a(10) // create a numeric array with 11 elements, from 0 to 10
// Indexed at your preference (0 to 9 or 1 to 10)
print arraysize(a(), 1) // this function return the element's higher number of an array
 
a(7) = 12.3 // access to an element of the array
redim a(20) // alias of 'dim'. Grouth size of array
 
// Yabasic not allow direct downsize an array, but ...
 
dim a$(20) // create a textual array with 21 elements
 
print arraysize(a$(), 1)
 
void = token("1,2,3,4,5,6,7,8,9,10", a$(), ",") // populate it. Begun with element 1 (not 0).
 
print arraysize(a$(), 1) // hey! the size is down
 
print a$(5) // show the content of an element of the array
 
void = token("", a$()) // "erase" the array content AND redim it to 0 size
 
print arraysize(a$(), 1)
 
redim a$(10) // resize the array
 
print arraysize(a$(), 1)
 
print a$(5) // show the content of an element of the array. Now is empty</syntaxhighlight>
 
=={{header|Z80 Assembly}}==
 
An array is nothing more than a contiguous section of memory. Whether an array is mutable or not is solely determined by whether its memory location is in ROM or RAM.
<syntaxhighlight lang="z80">Array: ;an array located in RAM. Its values can be updated freely.
byte 0,0,0,0,0
byte 0,0,0,0,0
byte 0,0,0,0,0
byte 0,0,0,0,0</syntaxhighlight>
 
<i>Side note: Some systems, such as the Game Boy or other ROM cartridge-based computers, cannot use the above declaration to initialize an array in RAM at assemble time; only in ROM. While the label "Array" can be given to an arbitrary RAM location on any system, you won't be able to define a data block in RAM the same way you would on an assembly program meant to run on the Amstrad CPC or ZX Spectrum for example. The examples below will still work on any system, you just won't be able to "see" the array before running the program, if that makes sense. Clearing the system ram will suffice to initialize the array to zero.</i>
 
Although it is heavily implied that the above array is 4x5, the CPU makes <b>no distinction whatsoever</b> between linear data and square arrays or matrices. The programmer has <i>intended</i> the array to be 4x5 (and it is the best practice to write the array as such) but the CPU doesn't enforce array sizes in any way. One way to do this in software is with metadata that is placed in front of the actual array, which has a fixed length. This metadata can specify the dimensions of the array as well as the data type (8 bits per element, 16 bits per element, etc.)
 
This code will assign a value of decimal 20 to the 1st (zero-indexed) row and 2nd (zero-indexed) column. The resulting array will look like this:
<syntaxhighlight lang="z80">Array:
byte 0,0,0,0,0
byte 0,0,20,0,0
byte 0,0,0,0,0
byte 0,0,0,0,0</syntaxhighlight>
 
 
 
<syntaxhighlight lang="z80">;for this example the array's size, the data we want to write, and where we want to write the data, are all known in advance.
 
ld hl,Array ;hl points to the 0th element of row 0.
ld c,5 ;one-indexed row length
ld b,0 ;set bc = row length
add hl,bc ;now hl points to the 0th element of row 1.
inc hl ;now hl points to the 1st element of row 1.
inc hl ;now hl points to the 2nd element of row 1. This is where we planned on storing our new value.
ld a,20 ;get the value 20 which we want to store here
ld (hl),a ;store 20 into the desired slot. (Retrieving a value is the same process except we skip the step above and
; execute "ld a,(hl)" at this point instead.)</syntaxhighlight>
 
The main takeaway from all this is that arrays are handled the same as any other type of memory, and have no "special" syntax, apart from the boilerplate pointer arithmetic of <code>*array = *array + (desired_row_number*row_length*bytes_per_element) + (desired_column_number*bytes_per_element)</code>. This is the case for most assembly languages, even though the methods of offsetting a pointer may vary.
 
===Array Alignment===
One very important topic for arrays in Z80 Assembly is alignment. If you need fast access to the data in an array, you can more than triple your lookup speed by aligning the table ahead of time. If an array of 8-bit data is placed so that its base address ends in 00, you really only need to load half the pointer to the table into the "high register" (B, D, H, IXH, or IYH) and the desired index into the corresponding "low register." Using an <code>org</code> or <code>align</code> directive is the easiest way to accomplish this task. Aligned tables are very important in Z80 Assembly, more so than in other assembly languages, since Z80's index registers are, for a lack of a better term, underwhelming at best. Not only are they slow, you are limited to using constant offsets only (unless you use self-modifying code) and are also signed offsets meaning that you can't index an array longer than 128 bytes without doing additional pointer arithmetic. Having indexing limitations is not unusual for most CPUs but the Z80 is probably one of the worst at it. Thankfully, table alignment can solve nearly all those problems (assuming you have enough padding to spare.)
 
In the example below, we wish to load the 13th (zero-indexed) element from the array MyTable.
 
<syntaxhighlight lang="z80">LD H,>MyTable ;works out to be LD h,4 thanks to our alignment below.
;>LABEL means "the high byte of the address represented by LABEL
LD L,13 ;this was a lot faster than doing LD HL,&0400 and adding the desired index later.
LD a,(HL) ;loads 12 into the accumulator.
RET
 
org &0400
MyTable: ;thanks to the ORG statement above, this label's address is guaranteed to be &0400
byte 1,2,3,4,5
byte 2,4,6,8,10
byte 3,6,9,12,15
byte 4,8,12,16,20
byte 5,10,15,20,25</syntaxhighlight>
 
But what if you're working with 16-bit data? If you've got bytes to burn, you can separate your data into two "byteplanes" - a pair of tables, one of which contains the low bytes and the other containing the high bytes, both sharing a common index. Using alignment you can guarantee that they are a multiple of &0100 bytes apart, which simplifies the lookup process greatly. You can get away with loading just the high byte of the pointer to the "low table" and incrementing that half of the pointer to get to the high byte, while leaving the index (which is stored in the low half of your pointer register) intact.
 
That might have been a bit confusing, so let's visualize the concept. Here's a practical example of storing a sine wave pattern. Instead of storing 16-bit data together like you normally would:
<syntaxhighlight lang="z80">org &0400
word &8000,&8327,&864e,&8973,&8c98,&8fba,&92da,&95f7
word &9911,&9c27,&9f38,&a244,&a54c,&a84d,&ab48,&ae3c
word &b12a,&b40f,&b6ed,&b9c2,&bc8e,&bf50,&c209,&c4b7
word &c75b,&c9f4,&cc81,&cf02,&d177,&d3e0,&d63b,&d889</syntaxhighlight>
 
You can instead store it like this:
<syntaxhighlight lang="z80">org &0400
byte <&8000,<&8327,<&864e,<&8973,<&8c98,<&8fba,<&92da,<&95f7
byte <&9911,<&9c27,<&9f38,<&a244,<&a54c,<&a84d,<&ab48,<&ae3c
byte <&b12a,<&b40f,<&b6ed,<&b9c2,<&bc8e,<&bf50,<&c209,<&c4b7
byte <&c75b,<&c9f4,<&cc81,<&cf02,<&d177,<&d3e0,<&d63b,<&d889
org &0500
byte >&8000,>&8327,>&864e,>&8973,>&8c98,>&8fba,>&92da,>&95f7
byte >&9911,>&9c27,>&9f38,>&a244,>&a54c,>&a84d,>&ab48,>&ae3c
byte >&b12a,>&b40f,>&b6ed,>&b9c2,>&bc8e,>&bf50,>&c209,>&c4b7
byte >&c75b,>&c9f4,>&cc81,>&cf02,>&d177,>&d3e0,>&d63b,>&d889</syntaxhighlight>
 
If your assembler is cool like mine is, this will be valid despite looking like I'm trying to declare what is obviously 16-bit data as 8-bit data. Many Z80 assemblers have some sort of "low byte" and "high byte" operator, it might not be the same symbol but most have it. If yours doesn't, I'd recommend using one that does, because it's really necessary for optimizations like these. In addition it makes the code more readable as it communicates to the reader how the data is intended to be interpreted.
 
So let's say we want to read the last entry in "the table".
<syntaxhighlight lang="z80">LD h,&04 ;load high byte of address &0400
LD L,&1F ;desired index
ld a,(hl)
ld c,a
inc h ;LD h,&05. We can keep L the same since the index is the same.
;Effectively we did all the necessary pointer arithmetic for indexing the second table, just with this one instruction!
ld a,(hl) ;now we have the low byte in C and the high byte in A.</syntaxhighlight>
 
That would have taken a lot more instructions had this been a single table of words with more than 128 entries. You'd have to do some bit shifting to offset the pointer to the table by the desired index, and it would have just taken a lot more time. If you're trying to get something done quickly (such as a raster interrupt) you want to spend as little time doing lookups as possible.
 
=={{header|zkl}}==
Core zkl does not support arrays or vectors of one type. It does support heterogeneous lists, which are usually a super set at the cost of space.
<langsyntaxhighlight lang="zkl">var array=List(); // array of size 0
array=(0).pump(10,List().write,5).copy(); // [writable] array of size 10 filled with 5
array[3]=4;
array[3] //-->4
array+9; //append a 9 to the end, same as array.append(9)</langsyntaxhighlight>
 
=={{header|zonnon}}==
<syntaxhighlight lang="pascal">
var
a: array 10 of integer;
da: array * of cardinal;
</syntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 DIM a(5)
20 LET a(2)=128
30 PRINT a(2)</langsyntaxhighlight>
 
{{omit from|X86-64 Assembly|the same as X86, Just R based registers(eax,rax)}}
2

edits