Arrays: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 31: Line 31:
{{trans|Python}}
{{trans|Python}}


<lang 11l>[Int] array
<syntaxhighlight lang=11l>[Int] array
array.append(1)
array.append(1)
array.append(3)
array.append(3)
Line 44: Line 44:
V width = 3
V width = 3
V height = 4
V height = 4
V myArray2 = [[0] * width] * height // create array of arrays</lang>
V myArray2 = [[0] * width] * height // create array of arrays</syntaxhighlight>


{{out}}
{{out}}
Line 55: Line 55:


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Arrays 04/09/2015
<syntaxhighlight lang=360asm>* Arrays 04/09/2015
ARRAYS PROLOG
ARRAYS PROLOG
* we use TA array with 1 as origin. So TA(1) to TA(20)
* we use TA array with 1 as origin. So TA(1) to TA(20)
Line 84: Line 84:
J DC F'4'
J DC F'4'
YREGS
YREGS
END ARRAYS</lang>
END ARRAYS</syntaxhighlight>
=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==


Line 90: Line 90:
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.
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.


<lang 6502asm>Array:
<syntaxhighlight lang=6502asm>Array:
db 5,10,15,20,25,30,35,40,45,50</lang>
db 5,10,15,20,25,30,35,40,45,50</syntaxhighlight>




Line 98: Line 98:
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:
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:


<lang c> char foo()
<syntaxhighlight lang=c> char foo()
{
{
char array[5] = {3,6,9,12,15};
char array[5] = {3,6,9,12,15};
return array[2];
return array[2];
}</lang>
}</syntaxhighlight>


would (theoretically) compile to the following in 6502 Assembly:
would (theoretically) compile to the following in 6502 Assembly:
<lang 6502asm>
<syntaxhighlight lang=6502asm>
foo:
foo:
LDX #2 ;load the desired index
LDX #2 ;load the desired index
Line 112: Line 112:


array: ;this is the array we're reading from.
array: ;this is the array we're reading from.
db 3,6,9,12,15</lang>
db 3,6,9,12,15</syntaxhighlight>
===Arrays in the Zero Page - A Word of Warning===
===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:
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:


<lang 6502asm>LDX #$80
<syntaxhighlight lang=6502asm>LDX #$80
LDA $80,x ;evaluates to LDA $00
LDA $80,x ;evaluates to LDA $00
LDA $0480,x ;evaluates to LDA $0500</lang>
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.
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.
Line 124: Line 124:
===Arrays of 16-Bit Data===
===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:
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:
<lang 6502>wordArray:
<syntaxhighlight lang=6502>wordArray:
dw $ABCD,$BEEF,$CAFE,$DADA</lang>
dw $ABCD,$BEEF,$CAFE,$DADA</syntaxhighlight>


The 6502 is little-endian, so the above would be exactly the same as the following:
The 6502 is little-endian, so the above would be exactly the same as the following:
<lang 6502>wordArray:
<syntaxhighlight lang=6502>wordArray:
db $CD,$AB,$EF,$BE,$FE,$CA,$DA,$DA</lang>
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>:
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>:
<lang 6502>LDX #2 ;load the 1st (zero-indexed) WORD from the array (which is why this is 2 not 1)
<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
LDA wordArray,X ;evaluates to LDA #$EF
STA $00 ;store in a zero page temporary variable
STA $00 ;store in a zero page temporary variable
Line 138: Line 138:
LDA wordArray,X ;evaluates to LDA #$BE
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,
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.</lang>
;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.
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.
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.
<lang 6502asm>wordArray_Lo:
<syntaxhighlight lang=6502asm>wordArray_Lo:
db $CD,$EF,$FE,$DA
db $CD,$EF,$FE,$DA


wordArray_Hi:
wordArray_Hi:
db $AB,$BE,$CA,$DA ;both this version and the above versions are 8 bytes of memory.</lang>
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:
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:


<lang 6502>LDX #1 ;with split arrays we DON'T need to double our index.
<syntaxhighlight lang=6502>LDX #1 ;with split arrays we DON'T need to double our index.
LDA wordArray_Lo,x ;evaluates to LDA #$EF
LDA wordArray_Lo,x ;evaluates to LDA #$EF
STA $00
STA $00
LDA wordArray_Hi,x ;evaluates to LDA #$BE
LDA wordArray_Hi,x ;evaluates to LDA #$BE
STA $01</lang>
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.
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.
Line 162: Line 162:
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.
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:
In the first section I had this example of an array:
<lang 6502asm>Array:
<syntaxhighlight lang=6502asm>Array:
db 5,10,15,20,25,30,35,40,45,50</lang>
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:
In the eyes of the CPU, this is the same as ANY of the following:
<lang 6502asm>Array:
<syntaxhighlight lang=6502asm>Array:
db 5
db 5
db 10
db 10
Line 176: Line 176:
db 40
db 40
db 45
db 45
db 50</lang>
db 50</syntaxhighlight>


<lang 6502asm>Array:
<syntaxhighlight lang=6502asm>Array:
db 5,10
db 5,10
db 15,20
db 15,20
db 25,30
db 25,30
db 35,40
db 35,40
db 45,50</lang>
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:
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:


<lang 6502asm>Array:
<syntaxhighlight lang=6502asm>Array:
db 5,10
db 5,10
db 15,20
db 15,20
db 25,30
db 25,30
db 35,40
db 35,40
db 45,50</lang>
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.
For this example, we want row 3 and column 1 (zero-indexed for both) which means we want to load 40.
<lang 6502>
<syntaxhighlight lang=6502>
LDA #3 ;desired row
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)
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)
Line 203: Line 203:
TAX ;move A to X so we can use it as the index
TAX ;move A to X so we can use it as the index


LDA Array,x ;evaluates to LDA #40</lang>
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.
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.
Line 211: Line 211:
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.
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.


<lang 68000devpac>MOVE.L #$00100000,A0 ;define an array at memory address $100000</lang>
<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:
Defining an array in ROM (or RAM if you're making a program that is loaded from disk) is very simple:
<lang 68000devpac>;8-bit data
<syntaxhighlight lang=68000devpac>;8-bit data
MyArray:
MyArray:
DC.B 1,2,3,4,5
DC.B 1,2,3,4,5
Line 232: Line 232:
DC.L 6,7,8,9,10
DC.L 6,7,8,9,10
DC.L 11,12,13,14,15
DC.L 11,12,13,14,15
</syntaxhighlight>
</lang>


Strings are also arrays and most assemblers accept single or double quotes. The following are equivalent:
Strings are also arrays and most assemblers accept single or double quotes. The following are equivalent:
<lang 68000devpac>MyString:
<syntaxhighlight lang=68000devpac>MyString:
DC.B "Hello World",0
DC.B "Hello World",0
even
even
Line 241: Line 241:
MyString2:
MyString2:
DC.B 'H','e','l','l','o',' ','W','o','r','l','d',0
DC.B 'H','e','l','l','o',' ','W','o','r','l','d',0
even</lang>
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 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.
Line 255: Line 255:
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.
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.


<lang 68000devpac>myArray equ $240000
<syntaxhighlight lang=68000devpac>myArray equ $240000


LEA myArray,A0 ;load the base address of the array into A0
LEA myArray,A0 ;load the base address of the array into A0
Line 261: Line 261:
LSL.W #2,D0 ;this array is intended for 32-bit values.
LSL.W #2,D0 ;this array is intended for 32-bit values.
MOVE.L #23,D1 ;load decimal 23 into D1
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)</lang>
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:
This is the equivalent of the [[C]] code:
<lang C>int myArray[];
<syntaxhighlight lang=C>int myArray[];
myArray[3] = 23;</lang>
myArray[3] = 23;</syntaxhighlight>


Loading an element is very similar to storing it.
Loading an element is very similar to storing it.


<lang 68000devpac>myArray equ $240000
<syntaxhighlight lang=68000devpac>myArray equ $240000


;load element 4
;load element 4
Line 275: Line 275:
MOVE.W #4,D0 ;load the desired offset into D0
MOVE.W #4,D0 ;load the desired offset into D0
LSL.W #2,D0 ;this array is intended for 32-bit values.
LSL.W #2,D0 ;this array is intended for 32-bit values.
MOVE.L (A0,D0),D1 ;load the 4th element into D1.</lang>
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.
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.


<lang 68000devpac>myArray equ $240000
<syntaxhighlight lang=68000devpac>myArray equ $240000


;insert a new element into the 2nd slot and push everything behind it back.
;insert a new element into the 2nd slot and push everything behind it back.
Line 308: Line 308:
MOVE.L (A0,D0),(4,A0,D0)
MOVE.L (A0,D0),(4,A0,D0)
ADDA.L #4,A0
ADDA.L #4,A0
DBRA D2,LOOP</lang>
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.
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.
Line 318: Line 318:
<li>In external RAM - element retrieval/altering is most efficiently done sequentially, necessary for large arrays or peripherals</ul>
<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.
Dynamic (resizable) arrays are possible to implement, but are error-prone since bounds checking must be done by the programmer.
<lang asm>; constant array (elements are unchangeable) - the array is stored in the CODE segment
<syntaxhighlight 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)
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.
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 409: Line 409:
pop dph
pop dph


</syntaxhighlight>
</lang>


=={{header|8th}}==
=={{header|8th}}==


Arrays are declared using JSON syntax, and are dynamic (but not sparse)
Arrays are declared using JSON syntax, and are dynamic (but not sparse)
<lang forth>
<syntaxhighlight lang=forth>
[ 1 , 2 ,3 ] \ an array holding three numbers
[ 1 , 2 ,3 ] \ an array holding three numbers
1 a:@ \ this will be '2', the element at index 1
1 a:@ \ this will be '2', the element at index 1
Line 429: Line 429:
\ arrays don't have to be homogenous:
\ arrays don't have to be homogenous:
[1,"one", 2, "two"]
[1,"one", 2, "two"]
</syntaxhighlight>
</lang>


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<lang AArch64 Assembly>
<syntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program areaString64.s */
/* program areaString64.s */
Line 579: Line 579:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


=={{header|ABAP}}==
=={{header|ABAP}}==
There are no real arrays in ABAP but a construct called internal tables.
There are no real arrays in ABAP but a construct called internal tables.
<lang ABAP>
<syntaxhighlight lang=ABAP>
TYPES: tty_int TYPE STANDARD TABLE OF i
TYPES: tty_int TYPE STANDARD TABLE OF i
WITH NON-UNIQUE DEFAULT KEY.
WITH NON-UNIQUE DEFAULT KEY.
Line 597: Line 597:
cl_demo_output=>display( itab ).
cl_demo_output=>display( itab ).
cl_demo_output=>display( itab[ 2 ] ).
cl_demo_output=>display( itab[ 2 ] ).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 610: Line 610:


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>;; Create an array and store it in array-example
<syntaxhighlight lang=Lisp>;; Create an array and store it in array-example
(assign array-example
(assign array-example
(compress1 'array-example
(compress1 'array-example
Line 624: Line 624:


;; Get a[5]
;; Get a[5]
(aref1 'array-example (@ array-example) 5)</lang>
(aref1 'array-example (@ array-example) 5)</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang=Action!>PROC Main()
BYTE i
BYTE i


Line 686: Line 686:
PrintF("c(%B)=%B ",i,c(i))
PrintF("c(%B)=%B ",i,c(i))
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arrays.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arrays.png Screenshot from Atari 8-bit computer]
Line 710: Line 710:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang ActionScript>//creates an array of length 10
<syntaxhighlight lang=ActionScript>//creates an array of length 10
var array1:Array = new Array(10);
var array1:Array = new Array(10);
//creates an array with the values 1, 2
//creates an array with the values 1, 2
Line 725: Line 725:
array2.push(4);
array2.push(4);
//get and remove the last element of an array
//get and remove the last element of an array
trace(array2.pop());</lang>
trace(array2.pop());</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>procedure Array_Test is
<syntaxhighlight lang=Ada>procedure Array_Test is


A, B : array (1..20) of Integer;
A, B : array (1..20) of Integer;
Line 770: Line 770:
Fingers_Extended'Last := False; -- Set last element of array
Fingers_Extended'Last := False; -- Set last element of array


end Array_Test;</lang>
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.
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}}==
=={{header|Aikido}}==
Aikido arrays (or vectors) are dynamic and not fixed in size. They can hold a set of any defined value.
Aikido arrays (or vectors) are dynamic and not fixed in size. They can hold a set of any defined value.
<lang aikido>
<syntaxhighlight lang=aikido>
var arr1 = [1,2,3,4] // initialize with array literal
var arr1 = [1,2,3,4] // initialize with array literal
var arr2 = new [10] // empty array of 10 elements (each element has value none)
var arr2 = new [10] // empty array of 10 elements (each element has value none)
Line 792: Line 792:
var arr7 = arr1 & arr2 // intersection
var arr7 = arr1 & arr2 // intersection


</syntaxhighlight>
</lang>


# retrieve an element
# retrieve an element
Line 799: Line 799:
=={{header|Aime}}==
=={{header|Aime}}==
The aime ''list'' is a heterogeneous, dynamic sequence. No special creation procedure, only declaration is needed:
The aime ''list'' is a heterogeneous, dynamic sequence. No special creation procedure, only declaration is needed:
<lang aime>list l;</lang>
<syntaxhighlight lang=aime>list l;</syntaxhighlight>
Values (numbers, strings, collections, functions, etc) can be added in a type generic fashion:
Values (numbers, strings, collections, functions, etc) can be added in a type generic fashion:
<lang aime>l_append(l, 3);
<syntaxhighlight lang=aime>l_append(l, 3);
l_append(l, "arrays");
l_append(l, "arrays");
l_append(l, pow);</lang>
l_append(l, pow);</syntaxhighlight>
The insertion position can be specified:
The insertion position can be specified:
<lang aime>l_push(l, 3, .5);
<syntaxhighlight lang=aime>l_push(l, 3, .5);
l_push(l, 4, __type(l));</lang>
l_push(l, 4, __type(l));</syntaxhighlight>
More aptly, values (of selected types) can be inserted in a type specific fashion:
More aptly, values (of selected types) can be inserted in a type specific fashion:
<lang aime>l_p_integer(l, 5, -1024);
<syntaxhighlight lang=aime>l_p_integer(l, 5, -1024);
l_p_real(l, 6, 88);</lang>
l_p_real(l, 6, 88);</syntaxhighlight>
Similarly, values can be retrieved in a type generic fashion:
Similarly, values can be retrieved in a type generic fashion:
<lang aime>l_query(l, 5);</lang>
<syntaxhighlight lang=aime>l_query(l, 5);</syntaxhighlight>
or is type specific fashion:
or is type specific fashion:
<lang aime>l_q_real(l, 6);
<syntaxhighlight lang=aime>l_q_real(l, 6);
l_q_text(l, 1);</lang>
l_q_text(l, 1);</syntaxhighlight>


=={{header|ALGOL 60}}==
=={{header|ALGOL 60}}==
{{trans|Simula}}
{{trans|Simula}}
<lang algol60>begin
<syntaxhighlight lang=algol60>begin
comment arrays - Algol 60;
comment arrays - Algol 60;


Line 850: Line 850:
dynamic(5)
dynamic(5)


end arrays </lang>
end arrays </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 858: Line 858:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>PROC array_test = VOID:
<syntaxhighlight lang=algol68>PROC array_test = VOID:
(
(
[1:20]INT a;
[1:20]INT a;
Line 877: Line 877:
FLEX []CHAR string := "Hello, world!"; # create an array with variable bounds #
FLEX []CHAR string := "Hello, world!"; # create an array with variable bounds #
string := "shorter" # flexible arrays automatically resize themselves on assignment #
string := "shorter" # flexible arrays automatically resize themselves on assignment #
)</lang>
)</syntaxhighlight>


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.
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}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang=algolw>begin
% declare an array %
% declare an array %
integer array a ( 1 :: 10 );
integer array a ( 1 :: 10 );
Line 899: Line 899:
% as parameters to procedures %
% as parameters to procedures %
% multi-dimension arrays are supported %
% multi-dimension arrays are supported %
end.</lang>
end.</syntaxhighlight>


=={{header|AmigaE}}==
=={{header|AmigaE}}==
<lang amigae>DEF ai[100] : ARRAY OF CHAR, -> static
<syntaxhighlight lang=amigae>DEF ai[100] : ARRAY OF CHAR, -> static
da: PTR TO CHAR,
da: PTR TO CHAR,
la: PTR TO CHAR
la: PTR TO CHAR
Line 918: Line 918:
-> "deallocating" the array
-> "deallocating" the array
IF la <> NIL THEN END la[100]
IF la <> NIL THEN END la[100]
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|AntLang}}==
=={{header|AntLang}}==
<lang AntLang>/ Create an immutable sequence (array)
<syntaxhighlight lang=AntLang>/ Create an immutable sequence (array)
arr: <1;2;3>
arr: <1;2;3>


Line 933: Line 933:


/ Get the nth element (index origin = 0)
/ Get the nth element (index origin = 0)
nth:arr[n]</lang>
nth:arr[n]</syntaxhighlight>


=={{header|Apex}}==
=={{header|Apex}}==
<lang apex>Integer[] array = new Integer[10]; // optionally, append a braced list of Integers like "{1, 2, 3}"
<syntaxhighlight lang=apex>Integer[] array = new Integer[10]; // optionally, append a braced list of Integers like "{1, 2, 3}"
array[0] = 42;
array[0] = 42;
System.debug(array[0]); // Prints 42</lang>
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>
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
<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(5);// appends to the end of the list
aList.add(1, 6);// assigns the element at index 1
aList.add(1, 6);// assigns the element at index 1
System.debug(list[0]); // Prints 5, alternatively you can use list.get(0)</lang>
System.debug(list[0]); // Prints 5, alternatively you can use list.get(0)</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
Arrays in APL are one dimensional matrices, defined by seperating variables with spaces. For example:
Arrays in APL are one dimensional matrices, defined by seperating variables with spaces. For example:
<lang apl>+/ 1 2 3</lang>
<syntaxhighlight lang=apl>+/ 1 2 3</syntaxhighlight>
Is equivalent to <lang apl>1 + 2 + 3</lang>We're folding function <lang apl>+</lang> over the array <lang apl>1 2 3</lang>
Is equivalent to <syntaxhighlight lang=apl>1 + 2 + 3</syntaxhighlight>We're folding function <syntaxhighlight lang=apl>+</syntaxhighlight> over the array <syntaxhighlight lang=apl>1 2 3</syntaxhighlight>


=={{header|App Inventor}}==
=={{header|App Inventor}}==
Line 958: Line 958:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
AppleScript arrays are called lists:
AppleScript arrays are called lists:
<lang applescript> set empty to {}
<syntaxhighlight lang=applescript> set empty to {}
set ints to {1, 2, 3}</lang>
set ints to {1, 2, 3}</syntaxhighlight>


Lists can contain any objects including other lists:
Lists can contain any objects including other lists:
<lang applescript> set any to {1, "foo", 2.57, missing value, ints}</lang>
<syntaxhighlight lang=applescript> set any to {1, "foo", 2.57, missing value, ints}</syntaxhighlight>


Items can be appended to the beginning or end of a list:
Items can be appended to the beginning or end of a list:


<lang applescript>set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
<syntaxhighlight lang=applescript>set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
set beginning of any to false
set beginning of any to false
set end of any to Wednesday
set end of any to Wednesday
return any
return any
--> {false, 1, "foo", 2.57, missing value, {1, 2, 3}, Wednesday}</lang>
--> {false, 1, "foo", 2.57, missing value, {1, 2, 3}, Wednesday}</syntaxhighlight>


Or a new list containing the items can be created through concatenation:
Or a new list containing the items can be created through concatenation:


<lang applescript>set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
<syntaxhighlight lang=applescript>set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
set any to false & any & Wednesday
set any to false & any & Wednesday
--> {false, 1, "foo", 2.57, missing value, {1, 2, 3}, Wednesday}</lang>
--> {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!
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!
Line 984: Line 984:
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:
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:


<lang applescript>set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
<syntaxhighlight lang=applescript>set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
item -1 of any --> {1, 2, 3}
item -1 of any --> {1, 2, 3}
items 1 thru 3 of any --> {1, "foo", 2.57}</lang>
items 1 thru 3 of any --> {1, "foo", 2.57}</syntaxhighlight>


If required, items can be specified by class instead of the generic 'item' …
If required, items can be specified by class instead of the generic 'item' …


<lang applescript>set any to {false, 1, "foo", 2.57, missing value, {1, 2, 3}, Wednesday}
<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)</lang>
number 2 of any -- 2.57 (ie. the second number in the list)</syntaxhighlight>


… and some fairly complex range specifiers are possible:
… and some fairly complex range specifiers are possible:


<lang applescript>set any to {false, 1, "foo", 2.57, missing value, 5, 4, 12.0, 38, {1, 2, 3}, 7, Wednesday}
<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}</lang>
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:
The length of a list can be determined in any of three ways, although only the first two below are now recommended:


<lang applescript>count any -- Command.
<syntaxhighlight lang=applescript>count any -- Command.
length of any -- Property.
length of any -- Property.
number of any -- Property.</lang>
number of any -- Property.</syntaxhighlight>


The number of items of a specific class can also be obtained:
The number of items of a specific class can also be obtained:


<lang applescript>count any's reals
<syntaxhighlight lang=applescript>count any's reals
length of any's integers</lang>
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).
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).
Line 1,013: Line 1,013:
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:
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:


<lang applescript>use AppleScript version "2.4" -- Mac OS 10.10 (Yosemite) or later.
<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.
use framework "Foundation" -- Allows access to NSArrays and other Foundation classes.


Line 1,019: Line 1,019:
set myNSArray to current application's NSArray's arrayWithArray:myList -- Bridge the list to an NSArray.
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.
set arrayLength to myNSArray's |count|() -- Get the array's length using its 'count' property.
--> 5</lang>
--> 5</syntaxhighlight>


=={{header|Arendelle}}==
=={{header|Arendelle}}==
Line 1,056: Line 1,056:
=={{header|Argile}}==
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
{{works with|Argile|1.0.0}}
<lang Argile>use std, array
<syntaxhighlight lang=Argile>use std, array
(:::::::::::::::::
(:::::::::::::::::
Line 1,086: Line 1,086:
DynArray[5] = 243
DynArray[5] = 243
prints DynArray[0] DynArray[5]
prints DynArray[0] DynArray[5]
del DynArray</lang>
del DynArray</syntaxhighlight>


{{works with|Argile|1.1.0}}
{{works with|Argile|1.1.0}}
<lang Argile>use std, array
<syntaxhighlight lang=Argile>use std, array
let x = @["foo" "bar" "123"]
let x = @["foo" "bar" "123"]
print x[2]
print x[2]
x[2] = "abc"</lang>
x[2] = "abc"</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<lang ARM Assembly>
<syntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program areaString.s */
/* program areaString.s */
Line 1,284: Line 1,284:
.Ls_magic_number_10: .word 0x66666667
.Ls_magic_number_10: .word 0x66666667


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>; empty array
<syntaxhighlight lang=rebol>; empty array
arrA: []
arrA: []
Line 1,302: Line 1,302:
; retrieve an element at some index
; retrieve an element at some index
print arrB\1</lang>
print arrB\1</syntaxhighlight>
{{out}}
{{out}}
Line 1,313: Line 1,313:
{{works with|AutoHotkey_L}}
{{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.
The current, official build of AutoHotkey is called AutoHotkey_L. In it, arrays are called Objects, and associative/index based work hand-in-hand.
<lang AHK>myArray := Object() ; could use JSON-syntax sugar like {key: value}
<syntaxhighlight lang=AHK>myArray := Object() ; could use JSON-syntax sugar like {key: value}
myArray[1] := "foo"
myArray[1] := "foo"
myArray[2] := "bar"
myArray[2] := "bar"
Line 1,319: Line 1,319:


; Push a value onto the array
; Push a value onto the array
myArray.Insert("baz")</lang>
myArray.Insert("baz")</syntaxhighlight>
AutoHotkey Basic (deprecated) did not have typical arrays.
AutoHotkey Basic (deprecated) did not have typical arrays.
However, variable names could be concatenated, simulating associative 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.
By convention, based on built-in function stringsplit, indexes are 1-based and "0" index is the length.
<lang AutoHotkey>arrayX0 = 4 ; length
<syntaxhighlight lang=AutoHotkey>arrayX0 = 4 ; length
arrayX1 = first
arrayX1 = first
arrayX2 = second
arrayX2 = second
Line 1,333: Line 1,333:
StringSplit arrayX, source, %A_Space%
StringSplit arrayX, source, %A_Space%
Loop, %arrayX0%
Loop, %arrayX0%
Msgbox % arrayX%A_Index%</lang>
Msgbox % arrayX%A_Index%</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
Create an userdefined array.
Create an userdefined array.
<lang AutoIt>
<syntaxhighlight lang=AutoIt>
#include <Array.au3> ;Include extended Array functions (_ArrayDisplay)
#include <Array.au3> ;Include extended Array functions (_ArrayDisplay)


Line 1,352: Line 1,352:


_ArrayDisplay($aInputs) ;Display the Array
_ArrayDisplay($aInputs) ;Display the Array
</syntaxhighlight>
</lang>


=={{header|Avail}}==
=={{header|Avail}}==
Avail supports tuples as its primary ordered collection.
Avail supports tuples as its primary ordered collection.
<lang Avail>tup ::= <"aardvark", "cat", "dog">;</lang>
<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.
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.
<lang Avail><"pinch", "tsp", "tbsp", "cup">[4] \\ "cup"
<syntaxhighlight lang=Avail><"pinch", "tsp", "tbsp", "cup">[4] \\ "cup"
<3, 2, 1>[100] else [0]</lang>
<3, 2, 1>[100] else [0]</syntaxhighlight>


Tuples are immutable, however one can quickly create a new tuple with a specified element replaced.
Tuples are immutable, however one can quickly create a new tuple with a specified element replaced.
<lang Avail><"sheep", "wheat", "wood", "brick", "stone">[5] → "ore"</lang>
<syntaxhighlight lang=Avail><"sheep", "wheat", "wood", "brick", "stone">[5] → "ore"</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Line 1,370: Line 1,370:
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.
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.


<lang awk>BEGIN {
<syntaxhighlight lang=awk>BEGIN {
# to make an array, assign elements to it
# to make an array, assign elements to it
array[1] = "first"
array[1] = "first"
Line 1,399: Line 1,399:
print " " i ": " array[i]
print " " i ": " array[i]
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,425: Line 1,425:


=={{header|Axe}}==
=={{header|Axe}}==
<lang axe>1→{L₁}
<syntaxhighlight lang=axe>1→{L₁}
2→{L₁+1}
2→{L₁+1}
3→{L₁+2}
3→{L₁+2}
Line 1,432: Line 1,432:
Disp {L₁+1}►Dec,i
Disp {L₁+1}►Dec,i
Disp {L₁+2}►Dec,i
Disp {L₁+2}►Dec,i
Disp {L₁+3}►Dec,i</lang>
Disp {L₁+3}►Dec,i</syntaxhighlight>


=={{header|Babel}}==
=={{header|Babel}}==
Line 1,440: Line 1,440:
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:
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:


<lang babel>[1 2 3]</lang>
<syntaxhighlight lang=babel>[1 2 3]</syntaxhighlight>


<lang babel>[ptr 1 2 3]</lang>
<syntaxhighlight lang=babel>[ptr 1 2 3]</syntaxhighlight>




===Get a single array element===
===Get a single array element===


<lang babel>[1 2 3] 1 th ;</lang>
<syntaxhighlight lang=babel>[1 2 3] 1 th ;</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,456: Line 1,456:
Changing a value-array element:
Changing a value-array element:


<lang babel>[1 2 3] dup 1 7 set ;
<syntaxhighlight lang=babel>[1 2 3] dup 1 7 set ;
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 1,464: Line 1,464:
Changing a pointer-array element:
Changing a pointer-array element:


<lang babel>[ptr 1 2 3] dup 1 [ptr 7] set ;</lang>
<syntaxhighlight lang=babel>[ptr 1 2 3] dup 1 [ptr 7] set ;</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,471: Line 1,471:
===Select a range of an array===
===Select a range of an array===


<lang babel>[ptr 1 2 3 4 5 6] 1 3 slice ;</lang>
<syntaxhighlight lang=babel>[ptr 1 2 3 4 5 6] 1 3 slice ;</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,480: Line 1,480:
You can concatenate arrays of same type:
You can concatenate arrays of same type:


<lang babel>[1 2 3] [4] cat</lang>
<syntaxhighlight lang=babel>[1 2 3] [4] cat</syntaxhighlight>


<lang babel>[ptr 1 2 3] [ptr 4] cat</lang>
<syntaxhighlight lang=babel>[ptr 1 2 3] [ptr 4] cat</syntaxhighlight>


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.
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 1,490: Line 1,490:
Convert a value-array to a list of values:
Convert a value-array to a list of values:


<lang babel>[1 2 3] ar2ls lsnum !</lang>
<syntaxhighlight lang=babel>[1 2 3] ar2ls lsnum !</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,497: Line 1,497:
Convert a list of values to a value-array:
Convert a list of values to a value-array:


<lang babel>(1 2 3) ls2lf ;</lang>
<syntaxhighlight lang=babel>(1 2 3) ls2lf ;</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,504: Line 1,504:
Convert a pointer-array to a list of pointers:
Convert a pointer-array to a list of pointers:


<lang babel>[ptr 'foo' 'bar' 'baz'] ar2ls lsstr !</lang>
<syntaxhighlight lang=babel>[ptr 'foo' 'bar' 'baz'] ar2ls lsstr !</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,511: Line 1,511:
Convert a list of pointers to a pointer-array:
Convert a list of pointers to a pointer-array:


<lang babel>(1 2 3) bons ;</lang>
<syntaxhighlight lang=babel>(1 2 3) bons ;</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,522: Line 1,522:
Note: We need to use quotes in DATA
Note: We need to use quotes in DATA


<lang qbasic>
<syntaxhighlight lang=qbasic>
DATA "January", "February", "March", "April", "May", "June", "July"
DATA "January", "February", "March", "April", "May", "June", "July"
DATA "August", "September", "October", "November", "December"
DATA "August", "September", "October", "November", "December"
Line 1,531: Line 1,531:
PRINT dat$[i]
PRINT dat$[i]
NEXT
NEXT
</syntaxhighlight>
</lang>




2.) A modern BaCon approach to do arrays using strings
2.) A modern BaCon approach to do arrays using strings
<lang qbasic>
<syntaxhighlight lang=qbasic>
DECLARE A$[11] = {"January", "February", "March", "April", "May", \
DECLARE A$[11] = {"January", "February", "March", "April", "May", \
"June", "July", "August", "September", "October", "November", "December"} TYPE STRING
"June", "July", "August", "September", "October", "November", "December"} TYPE STRING
Line 1,545: Line 1,545:
INCR i
INCR i
WEND
WEND
</syntaxhighlight>
</lang>




Line 1,551: Line 1,551:
name this '''split.bac'''
name this '''split.bac'''


<lang qbasic>
<syntaxhighlight lang=qbasic>
SPLIT ARGUMENT$ BY " " TO TOK$ SIZE len_array
SPLIT ARGUMENT$ BY " " TO TOK$ SIZE len_array


Line 1,557: Line 1,557:
PRINT TOK$[i]
PRINT TOK$[i]
NEXT i
NEXT i
</syntaxhighlight>
</lang>


in the terminal
in the terminal
<lang bash>
<syntaxhighlight lang=bash>
./split January February March April May June July August September October November December
./split January February March April May June July August September October November December
</syntaxhighlight>
</lang>


Notes: if you want to take a string from the command line
Notes: if you want to take a string from the command line
Line 1,575: Line 1,575:


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.
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.
<lang qbasic> OPTION BASE 1
<syntaxhighlight lang=qbasic> OPTION BASE 1
DIM myArray(100) AS INTEGER </lang>
DIM myArray(100) AS INTEGER </syntaxhighlight>


Alternatively, the lower and upper bounds can be given while defining the array:
Alternatively, the lower and upper bounds can be given while defining the array:
<lang qbasic> DIM myArray(-10 TO 10) AS INTEGER </lang>
<syntaxhighlight lang=qbasic> DIM myArray(-10 TO 10) AS INTEGER </syntaxhighlight>


Dynamic arrays:
Dynamic arrays:
<lang qbasic> 'Specify that the array is dynamic and not static:
<syntaxhighlight lang=qbasic> 'Specify that the array is dynamic and not static:
'$DYNAMIC
'$DYNAMIC
DIM SHARED myArray(-10 TO 10, 10 TO 30) AS STRING
DIM SHARED myArray(-10 TO 10, 10 TO 30) AS STRING
REDIM SHARED myArray(20, 20) AS STRING
REDIM SHARED myArray(20, 20) AS STRING
myArray(1,1) = "Item1"
myArray(1,1) = "Item1"
myArray(1,2) = "Item2" </lang>
myArray(1,2) = "Item2" </syntaxhighlight>


'''Array Initialization'''
'''Array Initialization'''
Line 1,594: Line 1,594:
BASIC does not generally have option for initializing arrays to other values, so the initializing is usually done at run time.
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:
DATA and READ statements are often used for this purpose:
<lang qbasic> DIM month$(12)
<syntaxhighlight lang=qbasic> DIM month$(12)
DATA January, February, March, April, May, June, July
DATA January, February, March, April, May, June, July
DATA August, September, October, November, December
DATA August, September, October, November, December
FOR m=1 TO 12
FOR m=1 TO 12
READ month$(m)
READ month$(m)
NEXT m </lang>
NEXT m </syntaxhighlight>


{{works with|FreeBASIC}}
{{works with|FreeBASIC}}


FreeBASIC has an option to initialize array while declaring it.
FreeBASIC has an option to initialize array while declaring it.
<lang freebasic> Dim myArray(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}} </lang>
<syntaxhighlight lang=freebasic> Dim myArray(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}} </syntaxhighlight>


<lang basic>10 REM TRANSLATION OF QBASIC STATIC VERSION
<syntaxhighlight lang=basic>10 REM TRANSLATION OF QBASIC STATIC VERSION
20 REM ELEMENT NUMBERS TRADITIONALLY START AT ONE
20 REM ELEMENT NUMBERS TRADITIONALLY START AT ONE
30 DIM A%(11): REM ARRAY OF ELEVEN INTEGER ELEMENTS
30 DIM A%(11): REM ARRAY OF ELEVEN INTEGER ELEMENTS
Line 1,612: Line 1,612:
50 LET A%(11) = 1
50 LET A%(11) = 1
60 PRINT A%(1), A%(11)
60 PRINT A%(1), A%(11)
70 END</lang>
70 END</syntaxhighlight>


{{works with|qbasic}}
{{works with|qbasic}}
Line 1,618: Line 1,618:
===Static===
===Static===


<lang qbasic>DIM staticArray(10) AS INTEGER
<syntaxhighlight lang=qbasic>DIM staticArray(10) AS INTEGER


staticArray(0) = -1
staticArray(0) = -1
staticArray(10) = 1
staticArray(10) = 1


PRINT staticArray(0), staticArray(10)</lang>
PRINT staticArray(0), staticArray(10)</syntaxhighlight>


===Dynamic===
===Dynamic===
Line 1,629: Line 1,629:
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.
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.


<lang qbasic>REDIM dynamicArray(10) AS INTEGER
<syntaxhighlight lang=qbasic>REDIM dynamicArray(10) AS INTEGER


dynamicArray(0) = -1
dynamicArray(0) = -1
Line 1,637: Line 1,637:


dynamicArray(20) = 1
dynamicArray(20) = 1
PRINT dynamicArray(0), dynamicArray(20)</lang>
PRINT dynamicArray(0), dynamicArray(20)</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang basic>10 DIM A%(11): REM ARRAY OF TWELVE INTEGER ELEMENTS
<syntaxhighlight lang=basic>10 DIM A%(11): REM ARRAY OF TWELVE INTEGER ELEMENTS
20 LET A%(0) = -1
20 LET A%(0) = -1
30 LET A%(11) = 1
30 LET A%(11) = 1
40 PRINT A%(0), A%(11)</lang>
40 PRINT A%(0), A%(11)</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
Line 1,649: Line 1,649:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang BASIC256># numeric array
<syntaxhighlight lang=BASIC256># numeric array
dim numbers(10)
dim numbers(10)
for t = 0 to 9
for t = 0 to 9
Line 1,677: Line 1,677:
print numbers[t] + "=" + words$[t]
print numbers[t] + "=" + words$[t]
next t
next t
return</lang>
return</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
Arrays can be approximated, in a style similar to REXX
Arrays can be approximated, in a style similar to REXX


<lang dos>::arrays.cmd
<syntaxhighlight lang=dos>::arrays.cmd
@echo off
@echo off
setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEDELAYEDEXPANSION
Line 1,706: Line 1,706:
echo %1 = %2
echo %1 = %2
goto :eof
goto :eof
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,719: Line 1,719:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> REM Declare arrays, dimension is maximum index:
<syntaxhighlight lang=bbcbasic> REM Declare arrays, dimension is maximum index:
DIM array(6), array%(6), array$(6)
DIM array(6), array%(6), array$(6)
Line 1,735: Line 1,735:
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)
PRINT array%(2) TAB(16) array%(3) TAB(32) array%(4)
PRINT array$(2) TAB(16) array$(3) TAB(32) array$(4)</lang>
PRINT array$(2) TAB(16) array$(3) TAB(32) array$(4)</syntaxhighlight>


=={{header|bc}}==
=={{header|bc}}==
Line 1,742: Line 1,742:


The following is a transcript of an interactive session:
The following is a transcript of an interactive session:
<lang bc>/* Put the value 42 into array g at index 3 */
<syntaxhighlight lang=bc>/* Put the value 42 into array g at index 3 */
g[3] = 42
g[3] = 42
/* Look at some other elements in g */
/* Look at some other elements in g */
Line 1,759: Line 1,759:
123
123
g[3]
g[3]
42</lang>
42</syntaxhighlight>


=={{header|BML}}==
=={{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.
'''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.


<lang bml>
<syntaxhighlight lang=bml>
% Define an array(containing the numbers 1-3) named arr in the group $
% Define an array(containing the numbers 1-3) named arr in the group $
in $ let arr hold 1 2 3
in $ let arr hold 1 2 3
Line 1,776: Line 1,776:
% There is no automatic garbage collection
% There is no automatic garbage collection
delete $arr
delete $arr
</syntaxhighlight>
</lang>


=={{header|Boo}}==
=={{header|Boo}}==
<lang boo>
<syntaxhighlight lang=boo>
myArray as (int) = (1, 2, 3) // Size based on initialization
myArray as (int) = (1, 2, 3) // Size based on initialization
fixedArray as (int) = array(int, 1) // Given size(1 in this case)
fixedArray as (int) = array(int, 1) // Given size(1 in this case)
Line 1,788: Line 1,788:


print myArray[0]
print myArray[0]
</syntaxhighlight>
</lang>


=={{header|BQN}}==
=={{header|BQN}}==
Line 1,794: Line 1,794:


All arrays are variable length, and can contain any types of values.
All arrays are variable length, and can contain any types of values.
<lang bqn># Stranding:
<syntaxhighlight lang=bqn># Stranding:
arr ← 1‿2‿'a'‿+‿5
arr ← 1‿2‿'a'‿+‿5
# General List Syntax:
# General List Syntax:
Line 1,806: Line 1,806:


# Modifying the array(↩):
# Modifying the array(↩):
arr ↩ "hello"⌾(4⊸⊑) arr</lang>
arr ↩ "hello"⌾(4⊸⊑) arr</syntaxhighlight>
<lang bqn>1
<syntaxhighlight lang=bqn>1
⟨ 1 2 'a' + 5 ⟩
⟨ 1 2 'a' + 5 ⟩
⟨ 1 2 'a' + 5 ⟩
⟨ 1 2 'a' + 5 ⟩
+
+
⟨ 1 2 'a' + "hello" ⟩</lang>
⟨ 1 2 'a' + "hello" ⟩</syntaxhighlight>


[https://mlochbaum.github.io/BQN/try.html#code=IyBTdHJhbmRpbmc6CmFyciDihpAgMeKAvzLigL8nYSfigL8r4oC/NQojIEdlbmVyYWwgTGlzdCBTeW50YXg6CmFycjEg4oaQIOKfqDEsMiwnYScsKyw14p+pCuKAolNob3cgYXJyIOKJoSBhcnIxICMgYm90aCBhcnJheXMgYXJlIHRoZSBzYW1lLgrigKJTaG93IGFycgrigKJTaG93IGFycjEKCiMgVGFraW5nIG50aCBlbGVtZW50KOKKkSk6CuKAolNob3cgM+KKkWFycgoKIyBNb2RpZnlpbmcgdGhlIGFycmF5KOKGqSk6CmFyciDihqkgImhlbGxvIuKMvig04oq44oqRKSBhcnIK Try It Here!]
[https://mlochbaum.github.io/BQN/try.html#code=IyBTdHJhbmRpbmc6CmFyciDihpAgMeKAvzLigL8nYSfigL8r4oC/NQojIEdlbmVyYWwgTGlzdCBTeW50YXg6CmFycjEg4oaQIOKfqDEsMiwnYScsKyw14p+pCuKAolNob3cgYXJyIOKJoSBhcnIxICMgYm90aCBhcnJheXMgYXJlIHRoZSBzYW1lLgrigKJTaG93IGFycgrigKJTaG93IGFycjEKCiMgVGFraW5nIG50aCBlbGVtZW50KOKKkSk6CuKAolNob3cgM+KKkWFycgoKIyBNb2RpZnlpbmcgdGhlIGFycmF5KOKGqSk6CmFyciDihqkgImhlbGxvIuKMvig04oq44oqRKSBhcnIK Try It Here!]
Line 1,826: Line 1,826:
To delete and array (and therefore the variable with the array's name), call <code>tbl</code> with a size <code>0</code>.
To delete and array (and therefore the variable with the array's name), call <code>tbl</code> with a size <code>0</code>.


<lang bracmat>( tbl$(mytable,100)
<syntaxhighlight lang=bracmat>( tbl$(mytable,100)
& 5:?(30$mytable)
& 5:?(30$mytable)
& 9:?(31$mytable)
& 9:?(31$mytable)
Line 1,836: Line 1,836:
| out$"mytable is gone"
| out$"mytable is gone"
)
)
);</lang>
);</syntaxhighlight>
{{out}}
{{out}}
<pre>5
<pre>5
Line 1,846: Line 1,846:
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.
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
ARRAY DATA STRUCTURE
Line 1,932: Line 1,932:
return back by finding leftmost null then decrementing pointer
return back by finding leftmost null then decrementing pointer
twice then decrement our NEWVALUE cell
twice then decrement our NEWVALUE cell
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Fixed size static array of integers with initialization:
Fixed size static array of integers with initialization:
<lang c>int myArray2[10] = { 1, 2, 0 }; /* the rest of elements get the value 0 */
<syntaxhighlight 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 */</lang>
float myFloats[] ={1.2, 2.5, 3.333, 4.92, 11.2, 22.0 }; /* automatically sizes */</syntaxhighlight>


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.
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.
<lang c>#define MYFLOAT_SIZE (sizeof(myFloats)/sizeof(myFloats[0]))</lang>
<syntaxhighlight lang=c>#define MYFLOAT_SIZE (sizeof(myFloats)/sizeof(myFloats[0]))</syntaxhighlight>


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.
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.
<lang c>long a2D_Array[3][5]; /* 3 rows, 5 columns. */
<syntaxhighlight lang=c>long a2D_Array[3][5]; /* 3 rows, 5 columns. */
float my2Dfloats[][3] = {
float my2Dfloats[][3] = {
1.0, 2.0, 0.0,
1.0, 2.0, 0.0,
5.0, 1.0, 3.0 };
5.0, 1.0, 3.0 };
#define FLOAT_ROWS (sizeof(my2Dfloats)/sizeof(my2dFloats[0]))</lang>
#define FLOAT_ROWS (sizeof(my2Dfloats)/sizeof(my2dFloats[0]))</syntaxhighlight>


When the size of the array is not known at compile time, arrays may be dynamically
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>.
allocated to the proper size. The <code>malloc()</code>, <code>calloc()</code> and <code>free()</code> functions require the header <code>stdlib.h</code>.
<lang c>int numElements = 10;
<syntaxhighlight lang=c>int numElements = 10;
int *myArray = malloc(sizeof(int) * numElements); /* array of 10 integers */
int *myArray = malloc(sizeof(int) * numElements); /* array of 10 integers */
if ( myArray != NULL ) /* check to ensure allocation succeeded. */
if ( myArray != NULL ) /* check to ensure allocation succeeded. */
Line 1,961: Line 1,961:
/* calloc() additionally pre-initializes to all zeros */
/* calloc() additionally pre-initializes to all zeros */
short *myShorts = calloc( numElements, sizeof(short)); /* array of 10 */
short *myShorts = calloc( numElements, sizeof(short)); /* array of 10 */
if (myShorts != NULL)....</lang>
if (myShorts != NULL)....</syntaxhighlight>


Once allocated, myArray can be used as a normal array.
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:
The first element of a C array is indexed with 0. To set a value:
<lang c>myArray[0] = 1;
<syntaxhighlight lang=c>myArray[0] = 1;
myArray[1] = 3;</lang>
myArray[1] = 3;</syntaxhighlight>


And to retrieve it (e.g. for printing, provided that the <tt>stdio.h</tt> header was included for the printf function)
And to retrieve it (e.g. for printing, provided that the <tt>stdio.h</tt> header was included for the printf function)
<lang c>printf("%d\n", myArray[1]);</lang>
<syntaxhighlight lang=c>printf("%d\n", myArray[1]);</syntaxhighlight>


The <tt>array[index]</tt> syntax can be considered as a shortcut for <tt>*(index + array)</tt> and
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:
thus the square brackets are a commutative binary operator:
<lang c>*(array + index) = 1;
<syntaxhighlight lang=c>*(array + index) = 1;
printf("%d\n", *(array + index));
printf("%d\n", *(array + index));
3[array] = 5;</lang>
3[array] = 5;</syntaxhighlight>


There's no bounds check on the indexes. Negative indexing can be implemented as in the following.
There's no bounds check on the indexes. Negative indexing can be implemented as in the following.
<lang c>#define XSIZE 20
<syntaxhighlight lang=c>#define XSIZE 20
double *kernel = malloc(sizeof(double)*2*XSIZE+1);
double *kernel = malloc(sizeof(double)*2*XSIZE+1);
if (kernel) {
if (kernel) {
Line 1,988: Line 1,988:
free(kernel-XSIZE);
free(kernel-XSIZE);
}
}
}</lang>
}</syntaxhighlight>


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).
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,994: Line 1,994:
Typically dynamic allocation is used and the allocated array is sized to the maximum that might be needed. A additional variable is
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:
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);
int *array = malloc (sizeof(int) * 20);
....
....
array = realloc(array, sizeof(int) * 40);
array = realloc(array, sizeof(int) * 40);
</syntaxhighlight>
</lang>
A Linked List for chars may be implemented like this:
A Linked List for chars may be implemented like this:
<syntaxhighlight lang=C>
<lang C>
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
Line 2,060: Line 2,060:
list->size = 0;
list->size = 0;
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 2,066: Line 2,066:
Example of array of 10 int types:
Example of array of 10 int types:


<lang csharp> int[] numbers = new int[10];</lang>
<syntaxhighlight lang=csharp> int[] numbers = new int[10];</syntaxhighlight>


Example of array of 3 string types:
Example of array of 3 string types:


<lang csharp> string[] words = { "these", "are", "arrays" };</lang>
<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:
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>
<syntaxhighlight lang=csharp> int[] more_numbers = new int[3]{ 21, 14 ,63 };</syntaxhighlight>




Line 2,080: Line 2,080:


The following creates a 3x2 int matrix
The following creates a 3x2 int matrix
<lang csharp> int[,] number_matrix = new int[3,2];</lang>
<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.
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>
<syntaxhighlight lang=csharp> string[,] string_matrix = { {"I","swam"}, {"in","the"}, {"freezing","water"} };</syntaxhighlight>


or
or


<lang csharp> string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} };</lang>
<syntaxhighlight lang=csharp> string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} };</syntaxhighlight>


<lang csharp>int[] array = new int[10];
<syntaxhighlight lang=csharp>int[] array = new int[10];


array[0] = 1;
array[0] = 1;
array[1] = 3;
array[1] = 3;


Console.WriteLine(array[0]);</lang>
Console.WriteLine(array[0]);</syntaxhighlight>


Dynamic
Dynamic


<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;
using System.Collections.Generic;
using System.Collections.Generic;


Line 2,109: Line 2,109:
list[0] = 2;
list[0] = 2;


Console.WriteLine(list[0]);</lang>
Console.WriteLine(list[0]);</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 2,123: Line 2,123:
<code>std::vector<T></code> is a resizable array of <code>T</code> objects.
<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).
The memory for the array will be allocated from the heap (unless a custom allocator is used).
<lang cpp>#include <array>
<syntaxhighlight lang=cpp>#include <array>
#include <vector>
#include <vector>


Line 2,166: Line 2,166:
demonstrate(fixed_size_array);
demonstrate(fixed_size_array);
demonstrate(dynamic_array);
demonstrate(dynamic_array);
}</lang>
}</syntaxhighlight>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
{{works with|Ceylon|1.3.0}}
{{works with|Ceylon|1.3.0}}
<lang ceylon>import ceylon.collection {
<syntaxhighlight lang=ceylon>import ceylon.collection {


ArrayList
ArrayList
Line 2,189: Line 2,189:
list.push("hello again");
list.push("hello again");
print(list);
print(list);
}</lang>
}</syntaxhighlight>


=={{header|ChucK}}==
=={{header|ChucK}}==
<syntaxhighlight lang=c>
<lang c>
int array[0]; // instantiate int array
int array[0]; // instantiate int array
array << 1; // append item
array << 1; // append item
Line 2,202: Line 2,202:
[1,2,3,4,5,6,7] @=> array;
[1,2,3,4,5,6,7] @=> array;
array.popBack(); // Pop last element
array.popBack(); // Pop last element
</syntaxhighlight>
</lang>


=={{header|Clean}}==
=={{header|Clean}}==
Line 2,208: Line 2,208:
===Lazy array===
===Lazy array===
Create a lazy array of strings using an array denotation.
Create a lazy array of strings using an array denotation.
<lang clean>array :: {String}
<syntaxhighlight lang=clean>array :: {String}
array = {"Hello", "World"}</lang>
array = {"Hello", "World"}</syntaxhighlight>
Create a lazy array of floating point values by sharing a single element.
Create a lazy array of floating point values by sharing a single element.
<lang clean>array :: {Real}
<syntaxhighlight lang=clean>array :: {Real}
array = createArray 10 3.1415</lang>
array = createArray 10 3.1415</syntaxhighlight>
Create a lazy array of integers using an array (and also a list) comprehension.
Create a lazy array of integers using an array (and also a list) comprehension.
<lang clean>array :: {Int}
<syntaxhighlight lang=clean>array :: {Int}
array = {x \\ x <- [1 .. 10]}</lang>
array = {x \\ x <- [1 .. 10]}</syntaxhighlight>
===Strict array===
===Strict array===
Create a strict array of integers.
Create a strict array of integers.
<lang clean>array :: {!Int}
<syntaxhighlight lang=clean>array :: {!Int}
array = {x \\ x <- [1 .. 10]}</lang>
array = {x \\ x <- [1 .. 10]}</syntaxhighlight>
===Unboxed array===
===Unboxed array===
Create an unboxed array of characters, also known as <tt>String</tt>.
Create an unboxed array of characters, also known as <tt>String</tt>.
<lang clean>array :: {#Char}
<syntaxhighlight lang=clean>array :: {#Char}
array = {x \\ x <- ['a' .. 'z']}</lang>
array = {x \\ x <- ['a' .. 'z']}</syntaxhighlight>


=={{header|Clipper}}==
=={{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.
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.
<lang visualfoxpro> // Declare and initialize two-dimensional array
<syntaxhighlight lang=visualfoxpro> // Declare and initialize two-dimensional array
Local arr1 := { { "NITEM","N",10,0 }, { "CONTENT","C",60,0} }
Local arr1 := { { "NITEM","N",10,0 }, { "CONTENT","C",60,0} }
// Create an empty array
// Create an empty array
Line 2,237: Line 2,237:


// Array can be dynamically resized:
// Array can be dynamically resized:
arr4 := ASize( arr4, 80 )</lang>
arr4 := ASize( arr4, 80 )</syntaxhighlight>
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
<lang visualfoxpro>// Adding new item to array, its size is incremented
<syntaxhighlight lang=visualfoxpro>// Adding new item to array, its size is incremented
Aadd( arr1, { "LBASE","L",1,0 } )
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:
// 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 )
ADel( arr1, 1 )
// Assigning a value to array item
// Assigning a value to array item
arr3[1,1,1] := 11.4</lang>
arr3[1,1,1] := 11.4</syntaxhighlight>
Retrieve items of an array:
Retrieve items of an array:
<lang visualfoxpro> x := arr3[1,10,2]
<syntaxhighlight 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
// 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:
There is a set of functions to manage arrays in Clipper, including the following:
<lang visualfoxpro>// Fill the 20 items of array with 0, starting from 5-th item:
<syntaxhighlight lang=visualfoxpro>// Fill the 20 items of array with 0, starting from 5-th item:
AFill( arr4, 0, 5, 20 )
AFill( arr4, 0, 5, 20 )
//Copy 10 items from arr4 to arr3[2], starting from the first position:
//Copy 10 items from arr4 to arr3[2], starting from the first position:
Line 2,256: Line 2,256:
//Duplicate the whole or nested array:
//Duplicate the whole or nested array:
arr5 := AClone( arr1 )
arr5 := AClone( arr1 )
arr6 := AClone( arr1[3] )</lang>
arr6 := AClone( arr1[3] )</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>;clojure is a language built with immutable/persistent data structures. there is no concept of changing what a vector/list
<syntaxhighlight lang=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...)
;is, instead clojure creates a new array with an added value using (conj...)
;in the example below the my-list does not change.
;in the example below the my-list does not change.
Line 2,292: Line 2,292:


user=> (conj my-vec 300) ;adding to a vector always adds to the end of the vector
user=> (conj my-vec 300) ;adding to a vector always adds to the end of the vector
[1 2 3 4 5 6 300]</lang>
[1 2 3 4 5 6 300]</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
In COBOL, arrays are called ''tables''. Also, indexes begin from 1.
In COBOL, arrays are called ''tables''. Also, indexes begin from 1.
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang=cobol> IDENTIFICATION DIVISION.
PROGRAM-ID. arrays.
PROGRAM-ID. arrays.


Line 2,334: Line 2,334:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>array1 = []
<syntaxhighlight lang=coffeescript>array1 = []
array1[0] = "Dillenidae"
array1[0] = "Dillenidae"
array1[1] = "animus"
array1[1] = "animus"
Line 2,344: Line 2,344:


array2 = ["Cepphus", "excreta", "Gansu"]
array2 = ["Cepphus", "excreta", "Gansu"]
alert "Value of array2[1]: " + array2[1] # excreta</lang>
alert "Value of array2[1]: " + array2[1] # excreta</syntaxhighlight>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
Creating a one-dimensional Array:
Creating a one-dimensional Array:
<lang cfm><cfset arr1 = ArrayNew(1)></lang>
<syntaxhighlight lang=cfm><cfset arr1 = ArrayNew(1)></syntaxhighlight>


Creating a two-dimensional Array in CFScript:
Creating a two-dimensional Array in CFScript:
<lang cfm><cfscript>
<syntaxhighlight lang=cfm><cfscript>
arr2 = ArrayNew(2);
arr2 = ArrayNew(2);
</cfscript></lang>
</cfscript></syntaxhighlight>
''ColdFusion Arrays are '''NOT''' zero-based, they begin at index '''1'''''
''ColdFusion Arrays are '''NOT''' zero-based, they begin at index '''1'''''


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<lang lisp>(let ((array (make-array 10)))
<syntaxhighlight lang=lisp>(let ((array (make-array 10)))
(setf (aref array 0) 1
(setf (aref array 0) 1
(aref array 1) 3)
(aref array 1) 3)
(print array))</lang>
(print array))</syntaxhighlight>


Dynamic
Dynamic


<lang lisp>(let ((array (make-array 0 :adjustable t :fill-pointer 0)))
<syntaxhighlight lang=lisp>(let ((array (make-array 0 :adjustable t :fill-pointer 0)))
(vector-push-extend 1 array)
(vector-push-extend 1 array)
(vector-push-extend 3 array)
(vector-push-extend 3 array)
(setf (aref array 0) 2)
(setf (aref array 0) 2)
(print array))</lang>
(print array))</syntaxhighlight>


Creates a one-dimensional array of length 10. The initial contents are undefined.
Creates a one-dimensional array of length 10. The initial contents are undefined.
<lang lisp>(make-array 10)</lang>
<syntaxhighlight lang=lisp>(make-array 10)</syntaxhighlight>
Creates a two-dimensional array with dimensions 10x20.
Creates a two-dimensional array with dimensions 10x20.
<lang lisp>(make-array '(10 20))</lang>
<syntaxhighlight lang=lisp>(make-array '(10 20))</syntaxhighlight>
<tt>make-array</tt> may be called with a number of optional arguments.
<tt>make-array</tt> may be called with a number of optional arguments.
<lang lisp>; Makes an array of 20 objects initialized to nil
<syntaxhighlight lang=lisp>; Makes an array of 20 objects initialized to nil
(make-array 20 :initial-element 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
; 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)</lang>
(make-array 4 :element-type 'integer :initial-contents '(1 2 3 4) :adjustable t)</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
Line 2,386: Line 2,386:




<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE TestArray;
MODULE TestArray;
(* Implemented in BlackBox Component Builder *)
(* Implemented in BlackBox Component Builder *)
Line 2,413: Line 2,413:
END DoTwoDim;
END DoTwoDim;


END TestArray.</lang>
END TestArray.</syntaxhighlight>


=={{header|Computer/zero Assembly}}==
=={{header|Computer/zero Assembly}}==
Line 2,422: Line 2,422:
===Fixed-length array===
===Fixed-length array===
We have finished iterating through the array when the next load instruction would be <tt>LDA ary+length(ary)</tt>.
We have finished iterating through the array when the next load instruction would be <tt>LDA ary+length(ary)</tt>.
<lang czasm>load: LDA ary
<syntaxhighlight lang=czasm>load: LDA ary
ADD sum
ADD sum
STA sum
STA sum
Line 2,452: Line 2,452:
8
8
9
9
10</lang>
10</syntaxhighlight>
===Zero-terminated array===
===Zero-terminated array===
<lang czasm>load: LDA ary
<syntaxhighlight lang=czasm>load: LDA ary
BRZ done
BRZ done


Line 2,483: Line 2,483:
9
9
10
10
0</lang>
0</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang crystal>
<syntaxhighlight lang=crystal>
# create an array with one object in it
# create an array with one object in it
a = ["foo"]
a = ["foo"]
Line 2,507: Line 2,507:
%w(one two three) # => ["one", "two", "three"]
%w(one two three) # => ["one", "two", "three"]
%i(one two three) # => [:one, :two, :three]
%i(one two three) # => [:one, :two, :three]
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
<lang d>// All D arrays are capable of bounds checks.
<syntaxhighlight lang=d>// All D arrays are capable of bounds checks.


import std.stdio, core.stdc.stdlib;
import std.stdio, core.stdc.stdlib;
Line 2,550: Line 2,550:
writeln("D) Element 0: ", array4[0]);
writeln("D) Element 0: ", array4[0]);
writeln("D) Element 1: ", array4[1]);
writeln("D) Element 1: ", array4[1]);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>A) Element 0: 1
<pre>A) Element 0: 1
Line 2,561: Line 2,561:
D) Element 1: 3</pre>
D) Element 1: 3</pre>
One more kind of built-in array:
One more kind of built-in array:
<lang d>import std.stdio, core.simd;
<syntaxhighlight lang=d>import std.stdio, core.simd;


void main() {
void main() {
Line 2,571: Line 2,571:
writeln("E) Element 0: ", vector5.array[0]);
writeln("E) Element 0: ", vector5.array[0]);
writeln("E) Element 1: ", vector5.array[1]);
writeln("E) Element 1: ", vector5.array[1]);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>E) Element 0: 1
<pre>E) Element 0: 1
Line 2,577: Line 2,577:


=={{header|Dao}}==
=={{header|Dao}}==
<lang dao># use [] to create numeric arrays of int, float, double or complex types:
<syntaxhighlight lang=dao># use [] to create numeric arrays of int, float, double or complex types:
a = [ 1, 2, 3 ] # a vector
a = [ 1, 2, 3 ] # a vector
b = [ 1, 2; 3, 4 ] # a 2X2 matrix
b = [ 1, 2; 3, 4 ] # a 2X2 matrix
Line 2,586: Line 2,586:
d = a[1]
d = a[1]
e = b[0,1] # first row, second column
e = b[0,1] # first row, second column
f = c[1]</lang>
f = c[1]</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
<lang javascript>
<syntaxhighlight lang=javascript>
main(){
main(){
// Dart uses Lists which dynamically resize by default
// Dart uses Lists which dynamically resize by default
Line 2,632: Line 2,632:
}
}


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,642: Line 2,642:


=={{header|DBL}}==
=={{header|DBL}}==
<lang DBL>;
<syntaxhighlight lang=DBL>;
; Arrays for DBL version 4 by Dario B.
; Arrays for DBL version 4 by Dario B.
;
;
Line 2,693: Line 2,693:
VNUM2(1:5*8)=
VNUM2(1:5*8)=
CLEAR VALP1(1:5*8),VALP2(1:5*10)
CLEAR VALP1(1:5*8),VALP2(1:5*10)
VALP3(1:5*2*10)=</lang>
VALP3(1:5*2*10)=</syntaxhighlight>


=={{header|Delphi}}==
=={{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.
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.
<lang delphi>
<syntaxhighlight lang=delphi>
procedure TForm1.Button1Click(Sender: TObject);
procedure TForm1.Button1Click(Sender: TObject);
var
var
Line 2,733: Line 2,733:
// Displaying both arrays (#13#10 = Carriage Return/Line Feed)
// Displaying both arrays (#13#10 = Carriage Return/Line Feed)
ShowMessage(StaticArrayText + #13#10 + DynamicArrayText);
ShowMessage(StaticArrayText + #13#10 + DynamicArrayText);
end;</lang>
end;</syntaxhighlight>


=={{header|Diego}}==
=={{header|Diego}}==
<lang diego>set_ns(rosettacode);
<syntaxhighlight lang=diego>set_ns(rosettacode);
set_base(0);
set_base(0);


Line 2,852: Line 2,852:
[myArray]_end(); // Retrieve last element in a matrix
[myArray]_end(); // Retrieve last element in a matrix


reset_ns[];</lang>
reset_ns[];</syntaxhighlight>


=={{header|Dragon}}==
=={{header|Dragon}}==
<lang dragon>array = newarray(3) //optionally, replace "newarray(5)" with a brackets list of values like "[1, 2, 3]"
<syntaxhighlight lang=dragon>array = newarray(3) //optionally, replace "newarray(5)" with a brackets list of values like "[1, 2, 3]"
array[0] = 42
array[0] = 42
showln array[2] </lang>
showln array[2] </syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==


<lang delphi>
<syntaxhighlight lang=delphi>
// dynamic array, extensible, this a reference type
// dynamic array, extensible, this a reference type
var d : array of Integer;
var d : array of Integer;
Line 2,876: Line 2,876:
// inline array constructor, works for both static and dynamic arrays
// inline array constructor, works for both static and dynamic arrays
s := [1, 2, 3];
s := [1, 2, 3];
</syntaxhighlight>
</lang>


=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang dyalect>//Dyalect supports dynamic arrays
<syntaxhighlight lang=dyalect>//Dyalect supports dynamic arrays
var empty = []
var empty = []
var xs = [1, 2, 3]
var xs = [1, 2, 3]
Line 2,890: Line 2,890:
//Access array elements
//Access array elements
var x = xs[2]
var x = xs[2]
xs[2] = x * x</lang>
xs[2] = x * x</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{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.
In Déjà Vu, the relevant datatype is called list, which is basically a stack with random element access for getting and setting values.
<lang dejavu>#create a new list
<syntaxhighlight lang=dejavu>#create a new list
local :l []
local :l []


Line 2,914: Line 2,914:
#this prints Boo
#this prints Boo
!print pop-from l
!print pop-from l
</syntaxhighlight>
</lang>


=={{header|E}}==
=={{header|E}}==
Line 2,922: Line 2,922:
Literal lists are <code>ConstList</code>s.
Literal lists are <code>ConstList</code>s.


<lang e>? def empty := []
<syntaxhighlight lang=e>? def empty := []
# value: []
# value: []


Line 2,932: Line 2,932:


? numbers + [4,3,2,1]
? numbers + [4,3,2,1]
# value: [1, 2, 3, 4, 5, 4, 3, 2, 1]</lang>
# value: [1, 2, 3, 4, 5, 4, 3, 2, 1]</syntaxhighlight>


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


<lang e>? var numbers := []
<syntaxhighlight lang=e>? var numbers := []
# value: []
# value: []


Line 2,943: Line 2,943:


? numbers with= 2 # shorthand for same
? numbers with= 2 # shorthand for same
# value: [1, 2]</lang>
# value: [1, 2]</syntaxhighlight>


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


<lang e>? def flex := numbers.diverge()
<syntaxhighlight lang=e>? def flex := numbers.diverge()
# value: [1, 2].diverge()
# value: [1, 2].diverge()


Line 2,958: Line 2,958:


? flex.snapshot()
? flex.snapshot()
# value: [1, 2, -3]</lang>
# value: [1, 2, -3]</syntaxhighlight>


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


<lang e>([0] * 100).diverge(int) # contains 100 zeroes, can only contain integers</lang>
<syntaxhighlight lang=e>([0] * 100).diverge(int) # contains 100 zeroes, can only contain integers</syntaxhighlight>


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]].
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]].
Line 2,977: Line 2,977:
for i range len f[]
for i range len f[]
print f[i]
print f[i]
.</lang>
.</syntaxhighlight>


=={{header|EGL}}==
=={{header|EGL}}==
Line 2,983: Line 2,983:


'''Fixed-length array'''
'''Fixed-length array'''
<lang EGL>
<syntaxhighlight lang=EGL>
array int[10]; //optionally, add a braced list of values. E.g. array int[10]{1, 2, 3};
array int[10]; //optionally, add a braced list of values. E.g. array int[10]{1, 2, 3};
array[1] = 42;
array[1] = 42;
SysLib.writeStdout(array[1]);
SysLib.writeStdout(array[1]);
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,008: Line 3,008:


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang eiffel>
<syntaxhighlight lang=eiffel>
class
class
APPLICATION
APPLICATION
Line 3,042: Line 3,042:
my_static_array: ARRAY [STRING]
my_static_array: ARRAY [STRING]
end
end
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
Line 3,048: Line 3,048:


Static array
Static array
<lang elena> var staticArray := new int[]{1, 2, 3};</lang>
<syntaxhighlight lang=elena> var staticArray := new int[]{1, 2, 3};</syntaxhighlight>
Generic array
Generic array
<lang elena> var array := system'Array.allocate:3;
<syntaxhighlight lang=elena> var array := system'Array.allocate:3;
array[0] := 1;
array[0] := 1;
array[1] := 2;
array[1] := 2;
array[2] := 3;</lang>
array[2] := 3;</syntaxhighlight>
Stack allocated array
Stack allocated array
<lang elena> int stackAllocatedArray[3];
<syntaxhighlight lang=elena> int stackAllocatedArray[3];
stackAllocatedArray[0] := 1;
stackAllocatedArray[0] := 1;
stackAllocatedArray[1] := 2;
stackAllocatedArray[1] := 2;
stackAllocatedArray[2] := 3;</lang>
stackAllocatedArray[2] := 3;</syntaxhighlight>
Dynamic array
Dynamic array
<lang elena> var dynamicArray := new system'collections'ArrayList();
<syntaxhighlight lang=elena> var dynamicArray := new system'collections'ArrayList();
dynamicArray.append:1;
dynamicArray.append:1;
dynamicArray.append:2;
dynamicArray.append:2;
dynamicArray.append:4;
dynamicArray.append:4;


dynamicArray[2] := 3;</lang>
dynamicArray[2] := 3;</syntaxhighlight>
Printing an element
Printing an element
<lang elena> system'console.writeLine(array[0]);
<syntaxhighlight lang=elena> system'console.writeLine(array[0]);
system'console.writeLine(stackAllocatedArray[1]);
system'console.writeLine(stackAllocatedArray[1]);
system'console.writeLine(dynamicArray[2]);</lang>
system'console.writeLine(dynamicArray[2]);</syntaxhighlight>


=={{header|Elixir}}==
=={{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:
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:


<lang elixir>ret = {:ok, "fun", 3.1415}</lang>
<syntaxhighlight lang=elixir>ret = {:ok, "fun", 3.1415}</syntaxhighlight>


Elements of tuples are indexed numerically, starting with zero.
Elements of tuples are indexed numerically, starting with zero.


<lang elixir>elem(ret, 1) == "fun"
<syntaxhighlight lang=elixir>elem(ret, 1) == "fun"
elem(ret, 0) == :ok
elem(ret, 0) == :ok
put_elem(ret, 2, "pi") # => {:ok, "fun", "pi"}
put_elem(ret, 2, "pi") # => {:ok, "fun", "pi"}
ret == {:ok, "fun", 3.1415}</lang>
ret == {:ok, "fun", 3.1415}</syntaxhighlight>


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


<lang elixir>Tuple.append(ret, 3.1415) # => {:ok, "fun", "pie", 3.1415}</lang>
<syntaxhighlight lang=elixir>Tuple.append(ret, 3.1415) # => {:ok, "fun", "pie", 3.1415}</syntaxhighlight>


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


<lang elixir>Tuple.insert_at(ret, 1, "new stuff") # => {:ok, "new stuff", "fun", "pie"}</lang>
<syntaxhighlight lang=elixir>Tuple.insert_at(ret, 1, "new stuff") # => {:ok, "new stuff", "fun", "pie"}</syntaxhighlight>


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:
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:


<lang elixir>[ 1, 2, 3 ]</lang>
<syntaxhighlight lang=elixir>[ 1, 2, 3 ]</syntaxhighlight>


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


<lang elixir>my_list = [1, :two, "three"]
<syntaxhighlight lang=elixir>my_list = [1, :two, "three"]
my_list ++ [4, :five] # => [1, :two, "three", 4, :five]
my_list ++ [4, :five] # => [1, :two, "three", 4, :five]


Line 3,104: Line 3,104:
List.delete(my_list, :two) # => [1, "three"]
List.delete(my_list, :two) # => [1, "three"]
my_list -- ["three", 1] # => [:two]
my_list -- ["three", 1] # => [:two]
my_list # => [1, :two, "three"]</lang>
my_list # => [1, :two, "three"]</syntaxhighlight>


Lists have a ''head'', being the first element, and a ''tail'', which are all the elements of the list following the head.
Lists have a ''head'', being the first element, and a ''tail'', which are all the elements of the list following the head.


<lang elixir>iex(1)> fruit = [:apple, :banana, :cherry]
<syntaxhighlight lang=elixir>iex(1)> fruit = [:apple, :banana, :cherry]
[:apple, :banana, :cherry]
[:apple, :banana, :cherry]
iex(2)> hd(fruit)
iex(2)> hd(fruit)
Line 3,117: Line 3,117:
true
true
iex(5)> tl(fruit) == [:banana, :cherry]
iex(5)> tl(fruit) == [:banana, :cherry]
true</lang>
true</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>
<syntaxhighlight lang=erlang>
%% Create a fixed-size array with entries 0-9 set to 'undefined'
%% Create a fixed-size array with entries 0-9 set to 'undefined'
A0 = array:new(10).
A0 = array:new(10).
Line 3,151: Line 3,151:
{'EXIT',{badarg,_}} = (catch array:set(18, true, A3)).
{'EXIT',{badarg,_}} = (catch array:set(18, true, A3)).
{'EXIT',{badarg,_}} = (catch array:get(18, A3)).
{'EXIT',{badarg,_}} = (catch array:get(18, A3)).
</syntaxhighlight>
</lang>


=={{header|ERRE}}==
=={{header|ERRE}}==
Line 3,204: Line 3,204:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang Euphoria>
<syntaxhighlight lang=Euphoria>
--Arrays task for Rosetta Code wiki
--Arrays task for Rosetta Code wiki
--User:Lnettnay
--User:Lnettnay
Line 3,234: Line 3,234:
end for
end for
? dynarray
? dynarray
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,250: Line 3,250:
=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
'''Fixed-length arrays:'''
'''Fixed-length arrays:'''
<lang fsharp>> Array.create 6 'A';;
<syntaxhighlight lang=fsharp>> Array.create 6 'A';;
val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
> Array.init 8 (fun i -> i * 10) ;;
> Array.init 8 (fun i -> i * 10) ;;
Line 3,261: Line 3,261:
val it : unit = ()
val it : unit = ()
> arr;;
> arr;;
val it : int [] = [|0; 1; 2; 3; 65; 5; 6|]</lang>
val it : int [] = [|0; 1; 2; 3; 65; 5; 6|]</syntaxhighlight>


'''Dynamic arrays:'''
'''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>:
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>:
<lang fsharp>> let arr = new ResizeArray<int>();;
<syntaxhighlight lang=fsharp>> let arr = new ResizeArray<int>();;
val arr : ResizeArray<int>
val arr : ResizeArray<int>
> arr.Add(42);;
> arr.Add(42);;
Line 3,280: Line 3,280:
Parameter name: index ...
Parameter name: index ...
> arr;;
> arr;;
val it : ResizeArray<int> = seq [13]</lang>
val it : ResizeArray<int> = seq [13]</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
Line 3,287: Line 3,287:


Directly in the listener :
Directly in the listener :
<lang factor>{ 1 2 3 }
<syntaxhighlight lang=factor>{ 1 2 3 }
{
{
[ "The initial array: " write . ]
[ "The initial array: " write . ]
Line 3,293: Line 3,293:
[ "Modified array: " write . ]
[ "Modified array: " write . ]
[ "The element we modified: " write [ 1 ] dip nth . ]
[ "The element we modified: " write [ 1 ] dip nth . ]
} cleave</lang>
} cleave</syntaxhighlight>
The initial array: { 1 2 3 }
The initial array: { 1 2 3 }
Modified array: { 1 42 3 }
Modified array: { 1 42 3 }
Line 3,303: Line 3,303:
{ 1 "coucou" f [ ] }
{ 1 "coucou" f [ ] }
Arrays of growable length are called Vectors.
Arrays of growable length are called Vectors.
<lang factor>V{ 1 2 3 }
<syntaxhighlight lang=factor>V{ 1 2 3 }
{
{
[ "The initial vector: " write . ]
[ "The initial vector: " write . ]
[ [ 42 ] dip push ]
[ [ 42 ] dip push ]
[ "Modified vector: " write . ]
[ "Modified vector: " write . ]
} cleave</lang>
} cleave</syntaxhighlight>
The initial vector: V{ 1 2 3 }
The initial vector: V{ 1 2 3 }
Modified vector: V{ 1 2 3 42 }
Modified vector: V{ 1 2 3 42 }
Line 3,373: Line 3,373:
For example, a static array of 10 cells in the dictionary, 5 initialized and 5 uninitialized:
For example, a static array of 10 cells in the dictionary, 5 initialized and 5 uninitialized:


<lang forth>create MyArray 1 , 2 , 3 , 4 , 5 , 5 cells allot
<syntaxhighlight lang=forth>create MyArray 1 , 2 , 3 , 4 , 5 , 5 cells allot
here constant MyArrayEnd
here constant MyArrayEnd


Line 3,379: Line 3,379:
MyArray 7 cells + @ . \ 30
MyArray 7 cells + @ . \ 30


: .array MyArrayEnd MyArray do I @ . cell +loop ;</lang>
: .array MyArrayEnd MyArray do I @ . cell +loop ;</syntaxhighlight>


<lang forth>
<syntaxhighlight lang=forth>
: array ( n -- )
: array ( n -- )
create
create
Line 3,402: Line 3,402:
5fillMyArray
5fillMyArray
.MyArray \ 1 2 3 4 5 0 30 0 0 0
.MyArray \ 1 2 3 4 5 0 30 0 0 0
</syntaxhighlight>
</lang>
<lang forth>
<syntaxhighlight lang=forth>
: array create dup , dup cells here swap 0 fill cells allot ;
: array create dup , dup cells here swap 0 fill cells allot ;
: [size] @ ;
: [size] @ ;
Line 3,419: Line 3,419:
5fillMyArray
5fillMyArray
.MyArray \ 1 2 3 4 5 0 30 0 0 0
.MyArray \ 1 2 3 4 5 0 30 0 0 0
</syntaxhighlight>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 3,425: Line 3,425:


Basic array declaration:
Basic array declaration:
<lang fortran>integer a (10)</lang>
<syntaxhighlight lang=fortran>integer a (10)</syntaxhighlight>
<lang fortran>integer :: a (10)</lang>
<syntaxhighlight lang=fortran>integer :: a (10)</syntaxhighlight>
<lang fortran>integer, dimension (10) :: a</lang>
<syntaxhighlight lang=fortran>integer, dimension (10) :: a</syntaxhighlight>
Arrays are one-based. These declarations are equivalent:
Arrays are one-based. These declarations are equivalent:
<lang fortran>integer, dimension (10) :: a</lang>
<syntaxhighlight lang=fortran>integer, dimension (10) :: a</syntaxhighlight>
<lang fortran>integer, dimension (1 : 10) :: a</lang>
<syntaxhighlight lang=fortran>integer, dimension (1 : 10) :: a</syntaxhighlight>
Other bases can be used:
Other bases can be used:
<lang fortran>integer, dimension (0 : 9) :: a</lang>
<syntaxhighlight lang=fortran>integer, dimension (0 : 9) :: a</syntaxhighlight>
Arrays can have any type (intrinsic or user-defined), e.g.:
Arrays can have any type (intrinsic or user-defined), e.g.:
<lang fortran>real, dimension (10) :: a</lang>
<syntaxhighlight lang=fortran>real, dimension (10) :: a</syntaxhighlight>
<lang fortran>type (my_type), dimension (10) :: a</lang>
<syntaxhighlight lang=fortran>type (my_type), dimension (10) :: a</syntaxhighlight>
Multidimensional array declaration:
Multidimensional array declaration:
<lang fortran>integer, dimension (10, 10) :: a</lang>
<syntaxhighlight lang=fortran>integer, dimension (10, 10) :: a</syntaxhighlight>
<lang fortran>integer, dimension (10, 10, 10) :: a</lang>
<syntaxhighlight lang=fortran>integer, dimension (10, 10, 10) :: a</syntaxhighlight>
Allocatable array declaration:
Allocatable array declaration:
<lang fortran>integer, dimension (:), allocatable :: a</lang>
<syntaxhighlight lang=fortran>integer, dimension (:), allocatable :: a</syntaxhighlight>
<lang fortran>integer, dimension (:, :), allocatable :: a</lang>
<syntaxhighlight lang=fortran>integer, dimension (:, :), allocatable :: a</syntaxhighlight>
Array allocation:
Array allocation:
<lang fortran>allocate (a (10))</lang>
<syntaxhighlight lang=fortran>allocate (a (10))</syntaxhighlight>
<lang fortran>allocate (a (10, 10))</lang>
<syntaxhighlight lang=fortran>allocate (a (10, 10))</syntaxhighlight>
Array deallocation:
Array deallocation:
<lang fortran>deallocate (a)</lang>
<syntaxhighlight lang=fortran>deallocate (a)</syntaxhighlight>
Array initialisation:
Array initialisation:
<lang fortran>integer, dimension (10) :: a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</lang>
<syntaxhighlight lang=fortran>integer, dimension (10) :: a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</syntaxhighlight>
<lang fortran>integer :: i
<syntaxhighlight lang=fortran>integer :: i
integer, dimension (10) :: a = (/(i * i, i = 1, 10)/)</lang>
integer, dimension (10) :: a = (/(i * i, i = 1, 10)/)</syntaxhighlight>
<lang fortran>integer, dimension (10) :: a = 0</lang>
<syntaxhighlight lang=fortran>integer, dimension (10) :: a = 0</syntaxhighlight>
<lang fortran>integer :: i
<syntaxhighlight lang=fortran>integer :: i
integer, dimension (10, 10) :: a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))</lang>
integer, dimension (10, 10) :: a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))</syntaxhighlight>
Constant array declaration:
Constant array declaration:
<lang fortran>integer :: i
<syntaxhighlight lang=fortran>integer :: i
integer, dimension (10), parameter :: a = (/(i * i, i = 1, 10)/)</lang>
integer, dimension (10), parameter :: a = (/(i * i, i = 1, 10)/)</syntaxhighlight>
Element assignment:
Element assignment:
<lang fortran>a (1) = 1</lang>
<syntaxhighlight lang=fortran>a (1) = 1</syntaxhighlight>
<lang fortran>a (1, 1) = 1</lang>
<syntaxhighlight lang=fortran>a (1, 1) = 1</syntaxhighlight>
Array assignment (note that since Fortran 2003 array assignment also allocates or reallocates if necessary):
Array assignment (note that since Fortran 2003 array assignment also allocates or reallocates if necessary):
<lang fortran>a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</lang>
<syntaxhighlight lang=fortran>a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</syntaxhighlight>
<lang fortran>a = (/(i * i, i = 1, 10)/)</lang>
<syntaxhighlight lang=fortran>a = (/(i * i, i = 1, 10)/)</syntaxhighlight>
<lang fortran>a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))</lang>
<syntaxhighlight lang=fortran>a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))</syntaxhighlight>
<lang fortran>a = 0</lang>
<syntaxhighlight lang=fortran>a = 0</syntaxhighlight>
Array section assignment:
Array section assignment:
<lang fortran>a (:) = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</lang>
<syntaxhighlight lang=fortran>a (:) = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</syntaxhighlight>
<lang fortran>a (1 : 5) = (/1, 2, 3, 4, 5/)</lang>
<syntaxhighlight lang=fortran>a (1 : 5) = (/1, 2, 3, 4, 5/)</syntaxhighlight>
<lang fortran>a (: 5) = (/1, 2, 3, 4, 5/)</lang>
<syntaxhighlight lang=fortran>a (: 5) = (/1, 2, 3, 4, 5/)</syntaxhighlight>
<lang fortran>a (6 :) = (/1, 2, 3, 4, 5/)</lang>
<syntaxhighlight lang=fortran>a (6 :) = (/1, 2, 3, 4, 5/)</syntaxhighlight>
<lang fortran>a (1 : 5) = (/(i * i, i = 1, 10)/)</lang>
<syntaxhighlight lang=fortran>a (1 : 5) = (/(i * i, i = 1, 10)/)</syntaxhighlight>
<lang fortran>a (1 : 5)= 0</lang>
<syntaxhighlight lang=fortran>a (1 : 5)= 0</syntaxhighlight>
<lang fortran>a (1, :)= (/(i * i, i = 1, 10)/)</lang>
<syntaxhighlight lang=fortran>a (1, :)= (/(i * i, i = 1, 10)/)</syntaxhighlight>
<lang fortran>a (1 : 5, 1)= (/(i * i, i = 1, 5)/)</lang>
<syntaxhighlight lang=fortran>a (1 : 5, 1)= (/(i * i, i = 1, 5)/)</syntaxhighlight>
Element retrieval:
Element retrieval:
<lang fortran>i = a (1)</lang>
<syntaxhighlight lang=fortran>i = a (1)</syntaxhighlight>
Array section retrieval:
Array section retrieval:
<lang fortran>a = b (1 : 10)</lang>
<syntaxhighlight lang=fortran>a = b (1 : 10)</syntaxhighlight>
Size retrieval:
Size retrieval:
<lang fortran>i = size (a)</lang>
<syntaxhighlight lang=fortran>i = size (a)</syntaxhighlight>
Size along a single dimension retrieval:
Size along a single dimension retrieval:
<lang fortran>i = size (a, 1)</lang>
<syntaxhighlight lang=fortran>i = size (a, 1)</syntaxhighlight>
Bounds retrieval:
Bounds retrieval:
<lang fortran>i_min = lbound (a)</lang>
<syntaxhighlight lang=fortran>i_min = lbound (a)</syntaxhighlight>
<lang fortran>i_max = ubound (a)</lang>
<syntaxhighlight lang=fortran>i_max = ubound (a)</syntaxhighlight>
Bounds of a multidimensional array retrieval:
Bounds of a multidimensional array retrieval:
<lang fortran>a = ubound (b)</lang>
<syntaxhighlight lang=fortran>a = ubound (b)</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Line 3,519: Line 3,519:


'''The default lower bound is always 0'''
'''The default lower bound is always 0'''
<lang FreeBASIC>' compile with: FBC -s console.
<syntaxhighlight lang=FreeBASIC>' compile with: FBC -s console.
' compile with: FBC -s console -exx to have boundary checks.
' compile with: FBC -s console -exx to have boundary checks.


Line 3,600: Line 3,600:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre> The first dimension has a lower bound of 1 and a upper bound of 2
<pre> The first dimension has a lower bound of 1 and a upper bound of 2
Line 3,635: Line 3,635:
=={{header|Frink}}==
=={{header|Frink}}==
In Frink, all arrays are dynamically resizable. Arrays can be created as literals or using <CODE>new array</CODE>
In Frink, all arrays are dynamically resizable. Arrays can be created as literals or using <CODE>new array</CODE>
<lang frink>
<syntaxhighlight lang=frink>
a = new array
a = new array
a@0 = 10
a@0 = 10
Line 3,642: Line 3,642:


b = [1, 2, 3]
b = [1, 2, 3]
</syntaxhighlight>
</lang>


=={{header|Futhark}}==
=={{header|Futhark}}==
Line 3,648: Line 3,648:
Multidimensional regular arrays are a built-in datatype in Futhark. They can be written as array literals:
Multidimensional regular arrays are a built-in datatype in Futhark. They can be written as array literals:


<lang Futhark>
<syntaxhighlight lang=Futhark>
[1, 2, 3]
[1, 2, 3]
</syntaxhighlight>
</lang>


Or created by an assortment of built-in functions:
Or created by an assortment of built-in functions:


<lang Futhark>
<syntaxhighlight lang=Futhark>
replicate 5 3 == [3,3,3,3,3]
replicate 5 3 == [3,3,3,3,3]
iota 5 = [0,1,2,3,4]
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:
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:


<lang Futhark>
<syntaxhighlight lang=Futhark>
fun update(as: *[]int, i: int, x: int): []int =
fun update(as: *[]int, i: int, x: int): []int =
let as[i] = x
let as[i] = x
in 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>.
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>.
Line 3,673: Line 3,673:
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:
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:


<lang gambas>
<syntaxhighlight lang=gambas>
DIM mynumbers AS INTEGER[]
DIM mynumbers AS INTEGER[]
myfruits AS STRING[]
myfruits AS STRING[]
Line 3,682: Line 3,682:
myfruits[0] = "apple"
myfruits[0] = "apple"
myfruits[1] = "banana"
myfruits[1] = "banana"
</syntaxhighlight>
</lang>




Line 3,688: Line 3,688:


'''[https://gambas-playground.proko.eu/?gist=5061d7f882a4768d212080e416c25e27 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=5061d7f882a4768d212080e416c25e27 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang=gambas>Public Sub Main()
Dim sFixedArray As String[] = ["Rosetta", "code", "is", "a", "programming", "chrestomathy", "site"]
Dim sFixedArray As String[] = ["Rosetta", "code", "is", "a", "programming", "chrestomathy", "site"]
Dim sFixedArray1 As New String[10]
Dim sFixedArray1 As New String[10]
Line 3,706: Line 3,706:
Print sFixedArray1[5] & sFixedArray1[6]
Print sFixedArray1[5] & sFixedArray1[6]


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 3,715: Line 3,715:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Arrays are better called lists in GAP. Lists may have elements of mixed types, e$
<syntaxhighlight lang=gap># Arrays are better called lists in GAP. Lists may have elements of mixed types, e$
v := [ 10, 7, "bob", true, [ "inner", 5 ] ];
v := [ 10, 7, "bob", true, [ "inner", 5 ] ];
# [ 10, 7, "bob", true, [ "inner", 5 ] ]
# [ 10, 7, "bob", true, [ "inner", 5 ] ]
Line 3,759: Line 3,759:
Add(v, "added");
Add(v, "added");
v;
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000, 8, 9, "added" ]</lang>
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000, 8, 9, "added" ]</syntaxhighlight>


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>[indent=4]
<syntaxhighlight lang=genie>[indent=4]
/*
/*
Arrays, in Genie
Arrays, in Genie
Line 3,796: Line 3,796:
dyn.add(dyn[0]+dyn[1])
dyn.add(dyn[0]+dyn[1])
stdout.printf("dyn size: %d\n", dyn.size)
stdout.printf("dyn size: %d\n", dyn.size)
stdout.printf("dyn[2] : %d\n", dyn[2])</lang>
stdout.printf("dyn[2] : %d\n", dyn[2])</syntaxhighlight>


{{out}}
{{out}}
Line 3,811: Line 3,811:
====Example of Fixed Length Array====
====Example of Fixed Length Array====
Array containing a space (" "), "A", "B", and "C":
Array containing a space (" "), "A", "B", and "C":
<lang GML>array[0] = ' '
<syntaxhighlight lang=GML>array[0] = ' '
array[1] = 'A'
array[1] = 'A'
array[2] = 'B'
array[2] = 'B'
array[3] = 'C'</lang>
array[3] = 'C'</syntaxhighlight>


====Example of Arbitrary Length Array====
====Example of Arbitrary Length Array====
Array containing the set of all natural numbers from 1 through k:
Array containing the set of all natural numbers from 1 through k:
<lang GML>for(i = 0; i < k; i += 1)
<syntaxhighlight lang=GML>for(i = 0; i < k; i += 1)
array[i] = i + 1</lang>
array[i] = i + 1</syntaxhighlight>


===2-Dimensional Array Examples===
===2-Dimensional Array Examples===
====Example of Fixed Length Array====
====Example of Fixed Length Array====
Array containing the multiplication table of 1 through 4 by 1 through 3:
Array containing the multiplication table of 1 through 4 by 1 through 3:
<lang GML>array[1,1] = 1
<syntaxhighlight lang=GML>array[1,1] = 1
array[1,2] = 2
array[1,2] = 2
array[1,3] = 3
array[1,3] = 3
Line 3,835: Line 3,835:
array[3,2] = 6
array[3,2] = 6
array[3,3] = 9
array[3,3] = 9
array[3,4] = 12</lang>
array[3,4] = 12</syntaxhighlight>


====Example of Arbitrary Length Array====
====Example of Arbitrary Length Array====
Array containing the multiplication table of 1 through k by 1 through h:
Array containing the multiplication table of 1 through k by 1 through h:
<lang GML>for(i = 1; i <= k; i += 1)
<syntaxhighlight lang=GML>for(i = 1; i <= k; i += 1)
for(j = 1; j <= h; j += 1)
for(j = 1; j <= h; j += 1)
array[i,j] = i * j</lang>
array[i,j] = i * j</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 3,906: Line 3,906:
// the cap()=10 array is no longer referenced
// the cap()=10 array is no longer referenced
// and would be garbage collected eventually.
// and would be garbage collected eventually.
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>len(a) = 5
<pre>len(a) = 5
Line 3,927: Line 3,927:
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.
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.


<lang golfscript>[1 2 3]:a; # numeric only array, assigned to a and then dropped
<syntaxhighlight 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]
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 0= puts # pick element at index 0 (stack: 0)
a 10+puts # append 10 to the end of a
a 10+puts # append 10 to the end of a
10 a+puts # prepend 10 to a</lang>
10 a+puts # prepend 10 to a</syntaxhighlight>


Append and prepend works for integers or arrays only, since only in these cases the result is coerced to an array.
Append and prepend works for integers or arrays only, since only in these cases the result is coerced to an array.
Line 3,937: Line 3,937:
=={{header|Groovy}}==
=={{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.
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.
<lang groovy>def aa = [ 1, 25, 31, -3 ] // list
<syntaxhighlight lang=groovy>def aa = [ 1, 25, 31, -3 ] // list
def a = [0] * 100 // list of 100 zeroes
def a = [0] * 100 // list of 100 zeroes
def b = 1..9 // range notation
def b = 1..9 // range notation
Line 3,956: Line 3,956:
d.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }
d.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }
println()
println()
e.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }</lang>
e.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }</syntaxhighlight>


{{out}}
{{out}}
Line 3,972: Line 3,972:


Here is a more interesting example showing a function that creates and returns a square identity matrix of order N:
Here is a more interesting example showing a function that creates and returns a square identity matrix of order N:
<lang groovy>def identity = { n ->
<syntaxhighlight lang=groovy>def identity = { n ->
(1..n).collect { i -> (1..n).collect { j -> i==j ? 1.0 : 0.0 } }
(1..n).collect { i -> (1..n).collect { j -> i==j ? 1.0 : 0.0 } }
}</lang>
}</syntaxhighlight>


Test program:
Test program:
<lang groovy>def i2 = identity(2)
<syntaxhighlight lang=groovy>def i2 = identity(2)
def i15 = identity(15)
def i15 = identity(15)


Line 3,983: Line 3,983:
i2.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }
i2.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }
println()
println()
i15.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }</lang>
i15.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }</syntaxhighlight>


{{out}}
{{out}}
Line 4,007: Line 4,007:
Groovy, like every other C-derived language in the known universe, uses ZERO-based array/list indexing.
Groovy, like every other C-derived language in the known universe, uses ZERO-based array/list indexing.


<lang groovy>def strings = ['Mary', 'had', 'a', 'little', 'lamb', ". It's", 'fleece', 'was', 'white', 'as', 'snow']
<syntaxhighlight lang=groovy>def strings = ['Mary', 'had', 'a', 'little', 'lamb', ". It's", 'fleece', 'was', 'white', 'as', 'snow']


println strings
println strings
Line 4,017: Line 4,017:
strings[10] = 'strawberries'
strings[10] = 'strawberries'


println strings</lang>
println strings</syntaxhighlight>


{{out}}
{{out}}
Line 4,026: Line 4,026:
Negative indices are valid. They indicate indexing from the end of the list towards the start.
Negative indices are valid. They indicate indexing from the end of the list towards the start.


<lang groovy>println strings[-1]</lang>
<syntaxhighlight lang=groovy>println strings[-1]</syntaxhighlight>


{{out}}
{{out}}
Line 4,034: Line 4,034:
Groovy lists can be resequenced and subsequenced by providing lists or ranges of indices in place of a single index.
Groovy lists can be resequenced and subsequenced by providing lists or ranges of indices in place of a single index.


<lang groovy>println strings[0, 7, 2, 3, 8]
<syntaxhighlight lang=groovy>println strings[0, 7, 2, 3, 8]
println strings[0..4]
println strings[0..4]
println strings[0..3, -5]</lang>
println strings[0..3, -5]</syntaxhighlight>


{{out}}
{{out}}
Line 4,048: Line 4,048:
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:
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:


<lang GUISS>Start,Programs,Lotus 123,Type:Bob[downarrow],Kat[downarrow],Sarah[downarrow]</lang>
<syntaxhighlight lang=GUISS>Start,Programs,Lotus 123,Type:Bob[downarrow],Kat[downarrow],Sarah[downarrow]</syntaxhighlight>


=={{header|GW-BASIC}}==
=={{header|GW-BASIC}}==
Line 4,055: Line 4,055:
(GW-BASIC User's Guide)
(GW-BASIC User's Guide)


<lang qbasic>10 DATA 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
<syntaxhighlight 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
20 DIM A(9) ' Array with size 10 (9 is maximum subscript), all elements are set to 0
30 FOR I = 0 TO 9
30 FOR I = 0 TO 9
Line 4,063: Line 4,063:
70 A(4) = 400 ' Set 4th element of array
70 A(4) = 400 ' Set 4th element of array
80 PRINT A(4)
80 PRINT A(4)
</syntaxhighlight>
</lang>


=={{header|Halon}}==
=={{header|Halon}}==
<lang halon>$array = [];
<syntaxhighlight lang=halon>$array = [];
$array[] = 1;
$array[] = 1;
Line 4,074: Line 4,074:
echo $array[0];
echo $array[0];
echo $array["key"];</lang>
echo $array["key"];</syntaxhighlight>


=={{header|Harbour}}==
=={{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.
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.
<lang visualfoxpro> // Declare and initialize two-dimensional array
<syntaxhighlight lang=visualfoxpro> // Declare and initialize two-dimensional array
local arr1 := { { "NITEM", "N", 10, 0 }, { "CONTENT", "C", 60, 0 } }
local arr1 := { { "NITEM", "N", 10, 0 }, { "CONTENT", "C", 60, 0 } }
// Create an empty array
// Create an empty array
Line 4,088: Line 4,088:


// Array can be dynamically resized:
// Array can be dynamically resized:
arr4 := ASize( arr4, 80 )</lang>
arr4 := ASize( arr4, 80 )</syntaxhighlight>
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
<lang visualfoxpro>// Adding new item to array, its size is incremented
<syntaxhighlight lang=visualfoxpro>// Adding new item to array, its size is incremented
AAdd( arr1, { "LBASE", "L", 1, 0 } )
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:
// 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 )
ADel( arr1, 1 )
// Assigning a value to array item
// Assigning a value to array item
arr3[ 1, 1, 1 ] := 11.4</lang>
arr3[ 1, 1, 1 ] := 11.4</syntaxhighlight>
Retrieve items of an array:
Retrieve items of an array:
<lang visualfoxpro> x := arr3[ 1, 10, 2 ]
<syntaxhighlight 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
// 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:
There is a set of functions to manage arrays in Clipper, including the following:
<lang visualfoxpro>// Fill the 20 items of array with 0, starting from 5-th item:
<syntaxhighlight lang=visualfoxpro>// Fill the 20 items of array with 0, starting from 5-th item:
AFill( arr4, 0, 5, 20 )
AFill( arr4, 0, 5, 20 )
// Copy 10 items from arr4 to arr3[ 2 ], starting from the first position:
// Copy 10 items from arr4 to arr3[ 2 ], starting from the first position:
Line 4,107: Line 4,107:
// Duplicate the whole or nested array:
// Duplicate the whole or nested array:
arr5 := AClone( arr1 )
arr5 := AClone( arr1 )
arr6 := AClone( arr1[ 3 ] )</lang>
arr6 := AClone( arr1[ 3 ] )</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
You can read all about Haskell arrays [http://haskell.org/haskellwiki/Arrays here]. The following example is taken from that page:
You can read all about Haskell arrays [http://haskell.org/haskellwiki/Arrays here]. The following example is taken from that page:
<lang haskell>import Data.Array.IO
<syntaxhighlight lang=haskell>import Data.Array.IO


main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)
main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)
Line 4,117: Line 4,117:
writeArray arr 1 64
writeArray arr 1 64
b <- readArray arr 1
b <- readArray arr 1
print (a,b)</lang>
print (a,b)</syntaxhighlight>


=={{header|hexiscript}}==
=={{header|hexiscript}}==
<lang hexiscript>let a arr 2 # fixed size
<syntaxhighlight lang=hexiscript>let a arr 2 # fixed size
let a[0] 123 # index starting at 0
let a[0] 123 # index starting at 0
let a[1] "test" # can hold different types
let a[1] "test" # can hold different types


println a[1]</lang>
println a[1]</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>REAL :: n = 3, Astat(n), Bdyn(1, 1)
<syntaxhighlight lang=hicest>REAL :: n = 3, Astat(n), Bdyn(1, 1)


Astat(2) = 2.22222222
Astat(2) = 2.22222222
Line 4,137: Line 4,137:


ALIAS(Astat, n-1, last2ofAstat, 2)
ALIAS(Astat, n-1, last2ofAstat, 2)
WRITE(ClipBoard) last2ofAstat ! 2.22222222 0 </lang>
WRITE(ClipBoard) last2ofAstat ! 2.22222222 0 </syntaxhighlight>


=={{header|HolyC}}==
=={{header|HolyC}}==
<lang holyc>// Create an array of fixed size
<syntaxhighlight lang=holyc>// Create an array of fixed size
U8 array[10] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
U8 array[10] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;


Line 4,147: Line 4,147:


// Access an element
// Access an element
Print("%d\n", array[0]);</lang>
Print("%d\n", array[0]);</syntaxhighlight>


==Icon and Unicon==
==Icon and Unicon==
==={{header|Icon}}===
==={{header|Icon}}===
<lang icon>record aThing(a, b, c) # arbitrary object (record or class) for illustration
<syntaxhighlight lang=icon>record aThing(a, b, c) # arbitrary object (record or class) for illustration


procedure main()
procedure main()
Line 4,248: Line 4,248:
S := A[-8 -: -3] # S is [30, 40, 50]
S := A[-8 -: -3] # S is [30, 40, 50]
S := A[-5 +: -3] # S is [30, 40, 50]
S := A[-5 +: -3] # S is [30, 40, 50]
end</lang>
end</syntaxhighlight>


==={{header|Unicon}}===
==={{header|Unicon}}===
This Icon solution works in Unicon.
This Icon solution works in Unicon.
<lang unicon># Unicon provides a number of extensions
<syntaxhighlight lang=unicon># Unicon provides a number of extensions
# insert and delete work on lists allowing changes in the middle
# insert and delete work on lists allowing changes in the middle
# possibly others
# possibly others
</syntaxhighlight>
</lang>
{{improve|Unicon|Need code examples for these extensions}}
{{improve|Unicon|Need code examples for these extensions}}


=={{header|i}}==
=={{header|i}}==
<lang i>main
<syntaxhighlight lang=i>main
//Fixed-length arrays.
//Fixed-length arrays.
f $= array.integer[1]()
f $= array.integer[1]()
Line 4,269: Line 4,269:
d[+] $= 2
d[+] $= 2
print(d[1])
print(d[1])
}</lang>
}</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
<lang Io>foo := list("foo", "bar", "baz")
<syntaxhighlight lang=Io>foo := list("foo", "bar", "baz")
foo at(1) println // bar
foo at(1) println // bar
foo append("Foobarbaz")
foo append("Foobarbaz")
foo println
foo println
foo atPut(2, "barbaz") // baz becomes barbaz</lang>
foo atPut(2, "barbaz") // baz becomes barbaz</syntaxhighlight>


<pre>Io> foo := list("foo", "bar", "baz")
<pre>Io> foo := list("foo", "bar", "baz")
Line 4,295: Line 4,295:
=={{header|J}}==
=={{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.
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.
<lang j> 1 NB. a stand-alone scalar value is an array without any axis
<syntaxhighlight lang=j> 1 NB. a stand-alone scalar value is an array without any axis
1
1
NB. invoking any array produces that array as the result
NB. invoking any array produces that array as the result
Line 4,322: Line 4,322:
Xbcde
Xbcde
fXhij
fXhij
klXno</lang>
klXno</syntaxhighlight>
Because arrays are so important in J, a large portion of the language applies to this topic.
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.
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.


<lang J> A=: 7 11
<syntaxhighlight lang=J> A=: 7 11
B=: A, 9 5
B=: A, 9 5
B
B
7 11 9 5
7 11 9 5
A
A
7 11</lang>
7 11</syntaxhighlight>


Thus, in recent versions of J, special syntax was introduced to refer to a value while discarding the reference: <lang J> A=: 2 4 6 8
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=: A_:, 1 3 9 5
B
B
2 4 6 8 1 3 9 5
2 4 6 8 1 3 9 5
A
A
|value error: A</lang>
|value error: A</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<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>int[] array = new int[10]; //optionally, replace "new int[10]" with a braced list of ints like "{1, 2, 3}"
array[0] = 42;
array[0] = 42;
System.out.println(array[3]);</lang>
System.out.println(array[3]);</syntaxhighlight>


Dynamic arrays can be made using <code>List</code>s:
Dynamic arrays can be made using <code>List</code>s:


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


=={{header|JavaScript}}==
=={{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.
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.
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.
<lang javascript>// Create a new array with length 0
<syntaxhighlight lang=javascript>// Create a new array with length 0
var myArray = new Array();
var myArray = new Array();


Line 4,378: Line 4,378:
// Elisions are supported, but are buggy in some implementations
// Elisions are supported, but are buggy in some implementations
var y = [0,1,,]; // length 3, or 4 in buggy implementations
var y = [0,1,,]; // length 3, or 4 in buggy implementations
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{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.
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.<lang jq># Create a new array with length 0
There are, however, some interesting extensions, e.g. <tt>[][4] = null</tt> creates an array of length 5 as explained below.<syntaxhighlight lang=jq># Create a new array with length 0
[]
[]


Line 4,418: Line 4,418:
a[1:] # => [1,2,3,4]
a[1:] # => [1,2,3,4]
a[2:4] # => [2,3]
a[2:4] # => [2,3]
a[4:2] # null</lang>
a[4:2] # null</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript, with the differences that Jsi treats ''typeof [elements]'' as "array", not "object".
From Javascript, with the differences that Jsi treats ''typeof [elements]'' as "array", not "object".
<lang javascript>/* Arrays in Jsi */
<syntaxhighlight lang=javascript>/* Arrays in Jsi */
// Create a new array with length 0
// Create a new array with length 0
var myArray = new Array();
var myArray = new Array();
Line 4,474: Line 4,474:
myArray3.length ==> 4
myArray3.length ==> 4
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 4,515: Line 4,515:


=={{header|KonsolScript}}==
=={{header|KonsolScript}}==
<lang KonsolScript>//creates an array of length 3
<syntaxhighlight lang=KonsolScript>//creates an array of length 3
Array:New array[3]:Number;
Array:New array[3]:Number;


Line 4,525: Line 4,525:
array[0] = 5; //assign value
array[0] = 5; //assign value
Konsol:Log(array[0]) //retrieve value and display
Konsol:Log(array[0]) //retrieve value and display
}</lang>
}</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>fun main(x: Array<String>) {
<syntaxhighlight lang=scala>fun main(x: Array<String>) {
var a = arrayOf(1, 2, 3, 4)
var a = arrayOf(1, 2, 3, 4)
println(a.asList())
println(a.asList())
Line 4,534: Line 4,534:
println(a.asList())
println(a.asList())
println(a.reversedArray().asList())
println(a.reversedArray().asList())
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 2, 3, 4]
<pre>[1, 2, 3, 4]
Line 4,544: Line 4,544:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang=scheme>
// Create a new array with length 0
// Create a new array with length 0
{def myArray1 {A.new}}
{def myArray1 {A.new}}
Line 4,569: Line 4,569:


and so on...
and so on...
</syntaxhighlight>
</lang>


=={{header|lang5}}==
=={{header|lang5}}==
<lang lang5>[]
<syntaxhighlight lang=lang5>[]
1 append
1 append
['foo 'bar] append
['foo 'bar] append
2 reshape
2 reshape
0 remove 2 swap 2 compress collapse .</lang>
0 remove 2 swap 2 compress collapse .</syntaxhighlight>


=={{header|langur}}==
=={{header|langur}}==
Langur uses 1-based indexing.
Langur uses 1-based indexing.


<lang langur>var .a1 = [1, 2, 3, "abc"]
<syntaxhighlight lang=langur>var .a1 = [1, 2, 3, "abc"]
val .a2 = series 4..10
val .a2 = series 4..10
val .a3 = .a1 ~ .a2
val .a3 = .a1 ~ .a2
Line 4,604: Line 4,604:
writeln ".a2[5; 0]: ", .a2[5; 0]
writeln ".a2[5; 0]: ", .a2[5; 0]
writeln ".a2[10; 0]: ", .a2[10; 0]
writeln ".a2[10; 0]: ", .a2[10; 0]
writeln()</lang>
writeln()</syntaxhighlight>


{{out}}
{{out}}
Line 4,628: Line 4,628:
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.
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.


<lang Lasso>// Create a new empty array
<syntaxhighlight lang=Lasso>// Create a new empty array
local(array1) = array
local(array1) = array
Line 4,660: Line 4,660:


// Insert item at specific position
// Insert item at specific position
#array1->insert('0',1) // 0, a, c, c, z</lang>
#array1->insert('0',1) // 0, a, c, c, z</syntaxhighlight>


=== Static Arrays ===
=== 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.
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.


<lang Lasso>// Create a staticarray containing 5 items
<syntaxhighlight lang=Lasso>// Create a staticarray containing 5 items
local(mystaticArray) = staticarray('a','b','c','d','e')
local(mystaticArray) = staticarray('a','b','c','d','e')


Line 4,675: Line 4,675:


// Create an empty static array with a length of 32
// Create an empty static array with a length of 32
local(mystaticArray) = staticarray_join(32,void)</lang>
local(mystaticArray) = staticarray_join(32,void)</syntaxhighlight>


=={{header|Latitude}}==
=={{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.
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.
<lang Latitude>;; Construct an array.
<syntaxhighlight lang=Latitude>;; Construct an array.
foo := [1, 2, 3].
foo := [1, 2, 3].


Line 4,705: Line 4,705:
println: foo popBack. ;; 3
println: foo popBack. ;; 3
println: foo popFront. ;; "front"
println: foo popFront. ;; "front"
println: foo. ;; [1, 99]</lang>
println: foo. ;; [1, 99]</syntaxhighlight>


=={{header|LFE}}==
=={{header|LFE}}==


Using the LFE REPL, you can explore arrays in the following manner:
Using the LFE REPL, you can explore arrays in the following manner:
<lang lisp>
<syntaxhighlight lang=lisp>
; Create a fixed-size array with entries 0-9 set to 'undefined'
; Create a fixed-size array with entries 0-9 set to 'undefined'
> (set a0 (: array new 10))
> (set a0 (: array new 10))
Line 4,763: Line 4,763:
in (array get 2)
in (array get 2)


</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Line 4,776: Line 4,776:
DATA is READ into variables. It cannot be READ directly into arrays.
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.
<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)
dim Array(10)


Line 4,791: Line 4,791:
print Array( 0), Array( 10)
print Array( 0), Array( 10)


</syntaxhighlight>
</lang>


=={{header|LIL}}==
=={{header|LIL}}==
Line 4,810: Line 4,810:
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.
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.


<lang tcl># (not) Arrays, in LIL
<syntaxhighlight lang=tcl># (not) Arrays, in LIL
set a [list abc def ghi]
set a [list abc def ghi]
set b [list 4 5 6]
set b [list 4 5 6]
Line 4,818: Line 4,818:
append b [list 7 8 9]
append b [list 7 8 9]
print [count $b]
print [count $b]
print $b</lang>
print $b</syntaxhighlight>


{{out}}
{{out}}
Line 4,833: Line 4,833:


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>a = [1,2] -- or: a = list(1,2)
<syntaxhighlight lang=lingo>a = [1,2] -- or: a = list(1,2)
put a[2] -- or: put a.getAt(2)
put a[2] -- or: put a.getAt(2)
-- 2
-- 2
Line 4,847: Line 4,847:
a.sort()
a.sort()
put a
put a
-- [3, 5]</lang>
-- [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:
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:


<lang lingo>ba = bytearray(2, 255) -- initialized with size 2 and filled with 0xff
<syntaxhighlight lang=lingo>ba = bytearray(2, 255) -- initialized with size 2 and filled with 0xff
put ba
put ba
-- <ByteArrayObject length = 2 ByteArray = 0xff, 0xff >
-- <ByteArrayObject length = 2 ByteArray = 0xff, 0xff >
Line 4,861: Line 4,861:
ba[1] = 5
ba[1] = 5
put ba
put ba
-- <ByteArrayObject length = 3 ByteArray = 0x5, 0x2, 0x3 ></lang>
-- <ByteArrayObject length = 3 ByteArray = 0x5, 0x2, 0x3 ></syntaxhighlight>


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>+ a : ARRAY(INTEGER);
<syntaxhighlight lang=Lisaac>+ a : ARRAY(INTEGER);
a := ARRAY(INTEGER).create 0 to 9;
a := ARRAY(INTEGER).create 0 to 9;
a.put 1 to 0;
a.put 1 to 0;
a.put 3 to 1;
a.put 3 to 1;
a.item(1).print;</lang>
a.item(1).print;</syntaxhighlight>


=={{header|Little}}==
=={{header|Little}}==
Arrays in Little are list of values of the same type and they grow dynamically.
Arrays in Little are list of values of the same type and they grow dynamically.
<lang C>String fruit[] = {"apple", "orange", "Pear"}</lang>
<syntaxhighlight lang=C>String fruit[] = {"apple", "orange", "Pear"}</syntaxhighlight>


They are zero-indexed. You can use END to get the last element of an array:
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[0]);
puts(fruit[1]);
puts(fruit[1]);
puts(fruit[END]);
puts(fruit[END]);
fruit[END+1] = "banana";</lang>
fruit[END+1] = "banana";</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>array 5 ; default origin is 1, every item is empty
<syntaxhighlight lang=logo>array 5 ; default origin is 1, every item is empty
(array 5 0) ; custom origin
(array 5 0) ; custom origin
make "a {1 2 3 4 5} ; array literal
make "a {1 2 3 4 5} ; array literal
setitem 1 :a "ten ; Logo is dynamic; arrays can contain different types
setitem 1 :a "ten ; Logo is dynamic; arrays can contain different types
print item 1 :a ; ten</lang>
print item 1 :a ; ten</syntaxhighlight>


=={{header|LOLCODE}}==
=={{header|LOLCODE}}==
<lang LOLCODE>HAI 1.4
<syntaxhighlight lang=LOLCODE>HAI 1.4
BTW declaring array
BTW declaring array
I HAS A array ITZ A BUKKIT
I HAS A array ITZ A BUKKIT
Line 4,906: Line 4,906:
VISIBLE array'Z three
VISIBLE array'Z three
VISIBLE array'Z string
VISIBLE array'Z string
KTHXBYE</lang>
KTHXBYE</syntaxhighlight>


=={{header|LSE64}}==
=={{header|LSE64}}==
<lang lse64>10 myArray :array
<syntaxhighlight lang=lse64>10 myArray :array
0 array 5 [] ! # store 0 at the sixth cell in the array
0 array 5 [] ! # store 0 at the sixth cell in the array
array 5 [] @ # contents of sixth cell in array</lang>
array 5 [] @ # contents of sixth cell in array</syntaxhighlight>


=={{header|LSL}}==
=={{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#.
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#.
<lang LSL>
<syntaxhighlight lang=LSL>
default {
default {
state_entry() {
state_entry() {
Line 4,943: Line 4,943:
llSay(0, "Deserialize a string CSV List\n(note that all elements are now string datatype)\nList=["+llList2CSV(lst)+"]\n");
llSay(0, "Deserialize a string CSV List\n(note that all elements are now string datatype)\nList=["+llList2CSV(lst)+"]\n");
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,975: Line 4,975:
=={{header|Lua}}==
=={{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.
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.
<lang lua>l = {}
<syntaxhighlight lang=lua>l = {}
l[1] = 1 -- Index starts with 1, not 0.
l[1] = 1 -- Index starts with 1, not 0.
l[0] = 'zero' -- But you can use 0 if you want
l[0] = 'zero' -- But you can use 0 if you want
Line 4,981: Line 4,981:
l.a = 3 -- Treated as l['a']. Any object can be used as index
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
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</lang>
for i,v in next,l do print (i,v) end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 4,987: Line 4,987:
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.
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.


<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module CheckArray {
Module CheckArray {
\\ Array with parenthesis in name
\\ Array with parenthesis in name
Line 5,075: Line 5,075:
}
}
CheckArray
CheckArray
</syntaxhighlight>
</lang>
===Passing Arrays By Reference===
===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.
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.
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Dim a(10)=1
Dim a(10)=1
Print a() ' 1 1 1 1 1 1 1 1 1 1
Print a() ' 1 1 1 1 1 1 1 1 1 1
Line 5,092: Line 5,092:
A++
A++
End Sub
End Sub
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>#defining an array of a certain length
<syntaxhighlight lang=maple>#defining an array of a certain length
a := Array (1..5);
a := Array (1..5);
a := [ 0 0 0 0 0 ]
a := [ 0 0 0 0 0 ]
Line 5,111: Line 5,111:
a := [ 9 2 3 4 5 6 ]
a := [ 9 2 3 4 5 6 ]
a[7] := 7;
a[7] := 7;
Error, Array index out of range</lang>
Error, Array index out of range</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>a = Array[Sin, 10]
<syntaxhighlight lang=Mathematica>a = Array[Sin, 10]
a[[1]]
a[[1]]
Delete[a, 2]</lang>
Delete[a, 2]</syntaxhighlight>
{{out}}
{{out}}
<pre>{Sin[1],Sin[2],Sin[3],Sin[4],Sin[5],Sin[6],Sin[7],Sin[8],Sin[9],Sin[10]}
<pre>{Sin[1],Sin[2],Sin[3],Sin[4],Sin[5],Sin[6],Sin[7],Sin[8],Sin[9],Sin[10]}
Line 5,125: Line 5,125:
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.
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.


<lang MATLAB>>> a = [1 2 35] %Declaring a vector (i.e. one-dimensional array)
<syntaxhighlight lang=MATLAB>>> a = [1 2 35] %Declaring a vector (i.e. one-dimensional array)


a =
a =
Line 5,185: Line 5,185:


2 35 10
2 35 10
7 9 42</lang>
7 9 42</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>/* Declare an array, subscripts run from 0 to max value */
<syntaxhighlight lang=maxima>/* Declare an array, subscripts run from 0 to max value */
array(a, flonum, 20, 20, 3)$
array(a, flonum, 20, 20, 3)$


Line 5,212: Line 5,212:


listarray(b);
listarray(b);
/* [1000, 3/4] */</lang>
/* [1000, 3/4] */</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
Line 5,218: Line 5,218:
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'.
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'.


<lang Mercury>:- module array_example.
<syntaxhighlight lang=Mercury>:- module array_example.
:- interface.
:- interface.
:- import_module io.
:- import_module io.
Line 5,273: Line 5,273:
else
else
true
true
).</lang>
).</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
Line 5,301: Line 5,301:


Example:
Example:
<lang MiniScript>arr = ["a", 1, 3]
<syntaxhighlight lang=MiniScript>arr = ["a", 1, 3]
print arr[0]
print arr[0]


arr.push "x"
arr.push "x"
print arr.pop</lang>
print arr.pop</syntaxhighlight>


=={{header|MIPS Assembly}}==
=={{header|MIPS Assembly}}==
<lang mips>
<syntaxhighlight lang=mips>
.data
.data
array: .word 1, 2, 3, 4, 5, 6, 7, 8, 9 # creates an array of 9 32 Bit words.
array: .word 1, 2, 3, 4, 5, 6, 7, 8, 9 # creates an array of 9 32 Bit words.
Line 5,322: Line 5,322:
li $v0, 10 # end program
li $v0, 10 # end program
syscall
syscall
</syntaxhighlight>
</lang>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
Line 5,328: Line 5,328:


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>VAR staticArray: ARRAY [1..10] OF INTEGER;</lang>
<syntaxhighlight lang=modula3>VAR staticArray: ARRAY [1..10] OF INTEGER;</syntaxhighlight>
Defines a static array of 10 elements, indexed 1 through 10.
Defines a static array of 10 elements, indexed 1 through 10.


Static arrays can also be given initial values:
Static arrays can also be given initial values:
<lang modula3>VAR staticArray := ARRAY [1..10] OF INTEGER {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
<syntaxhighlight lang=modula3>VAR staticArray := ARRAY [1..10] OF INTEGER {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
VAR staticArray2 := ARRAY [1..10] OF INTEGER {1, ..} (* Initialize all elements to 1. *)</lang>
VAR staticArray2 := ARRAY [1..10] OF INTEGER {1, ..} (* Initialize all elements to 1. *)</syntaxhighlight>


Open (dynamic) arrays can be be defined by creating a reference to an array of an unspecified size:
Open (dynamic) arrays can be be defined by creating a reference to an array of an unspecified size:
<lang modula3>TYPE TOpenIntArray = REF ARRAY OF INTEGER;
<syntaxhighlight lang=modula3>TYPE TOpenIntArray = REF ARRAY OF INTEGER;
VAR openArray: TOpenIntArray;</lang>
VAR openArray: TOpenIntArray;</syntaxhighlight>
Defines an open array of a currently unknown size.
Defines an open array of a currently unknown size.


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.
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.
The allocation is performed on the heap and all elements are initialized to 0:
The allocation is performed on the heap and all elements are initialized to 0:
<lang modula3>openArray := NEW(TOpenIntArray, 10);</lang>
<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.
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:
Retrieval or insertion of elements and determining array bounds is performed using the same built-in functions regardless of the array kind. Though open arrays must first be de-referenced when passing them to such functions. Assuming we have made the declarations above, we can do the following:
<lang modula3> VAR
<syntaxhighlight lang=modula3> VAR
staticArraySize := NUMBER(staticArray);
staticArraySize := NUMBER(staticArray);
staticArrayElement := staticArray[4];
staticArrayElement := staticArray[4];


openArraySize := NUMBER(openArray^); (* Note the dereference. *)
openArraySize := NUMBER(openArray^); (* Note the dereference. *)
openArrayElement := openArray[9];</lang>
openArrayElement := openArray[9];</syntaxhighlight>


<lang modula3>staticArray[4] := 100;
<syntaxhighlight lang=modula3>staticArray[4] := 100;
openArray[1] := 200;</lang>
openArray[1] := 200;</syntaxhighlight>


=={{header|Monte}}==
=={{header|Monte}}==


<lang Monte>var myArray := ['a', 'b', 'c','d']</lang>
<syntaxhighlight lang=Monte>var myArray := ['a', 'b', 'c','d']</syntaxhighlight>


To retrieve a value:
To retrieve a value:


<lang Monte>traceln(myArray[0])</lang>
<syntaxhighlight lang=Monte>traceln(myArray[0])</syntaxhighlight>


To change a value:
To change a value:


<lang Monte>myArray := myArray.with(3, 'z')</lang>
<syntaxhighlight lang=Monte>myArray := myArray.with(3, 'z')</syntaxhighlight>


Now myArray is ['a','b','c','z'].
Now myArray is ['a','b','c','z'].


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>// create a fixed-length array (length 10)
<syntaxhighlight lang=Nanoquery>// create a fixed-length array (length 10)
arr = array(10)
arr = array(10)


Line 5,388: Line 5,388:


// display the list
// display the list
println l</lang>
println l</syntaxhighlight>
{{out}}
{{out}}
<pre>hello, world!
<pre>hello, world!
Line 5,394: Line 5,394:


=={{header|Neko}}==
=={{header|Neko}}==
<lang Neko>var myArray = $array(1);
<syntaxhighlight lang=Neko>var myArray = $array(1);


$print(myArray[0]);</lang>
$print(myArray[0]);</syntaxhighlight>


{{out}}
{{out}}
Line 5,402: Line 5,402:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang=Nemerle>using System;
using System.Console;
using System.Console;
using System.Collections;
using System.Collections;
Line 5,421: Line 5,421:
foreach (i in dynamic) Write($"$i\t"); // Nemerle isn't great about displaying arrays, it's better with lists though
foreach (i in dynamic) Write($"$i\t"); // Nemerle isn't great about displaying arrays, it's better with lists though
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{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]]).
'''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]]).
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang=NetRexx>/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 5,458: Line 5,458:
loop x_ = 1 to cymru[0] by 1
loop x_ = 1 to cymru[0] by 1
say x_':' cymru[x_]
say x_':' cymru[x_]
end x_</lang>
end x_</syntaxhighlight>


{{out}}
{{out}}
Line 5,475: Line 5,475:
=={{header|NewLISP}}==
=={{header|NewLISP}}==
This creates an array of 5 elements, initialized to <code>nil</code>:
This creates an array of 5 elements, initialized to <code>nil</code>:
<lang lisp>(array 5)
<syntaxhighlight lang=lisp>(array 5)
→ (nil nil nil nil nil)</lang>
→ (nil nil nil nil nil)</syntaxhighlight>
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.
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.
<lang lisp>(set 'myarray (array 3 4 (sequence 1 12)))
<syntaxhighlight lang=lisp>(set 'myarray (array 3 4 (sequence 1 12)))
→ ((1 2 3 4) (5 6 7 8) (9 10 11 12))</lang>
→ ((1 2 3 4) (5 6 7 8) (9 10 11 12))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>var # fixed size arrays
<syntaxhighlight lang=nim>var # fixed size arrays
x = [1,2,3,4,5,6,7,8,9,10] # type and size automatically inferred
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
y: array[1..5, int] = [1,2,3,4,5] # starts at 1 instead of 0
Line 5,503: Line 5,503:
a.add(200) # append another element
a.add(200) # append another element
echo a.pop() # pop last item, removing and returning it
echo a.pop() # pop last item, removing and returning it
echo a</lang>
echo a</syntaxhighlight>


=={{header|NS-HUBASIC}}==
=={{header|NS-HUBASIC}}==
<lang NS-HUBASIC>10 DIM A(1)
<syntaxhighlight lang=NS-HUBASIC>10 DIM A(1)
20 A(1)=10
20 A(1)=10
30 PRINT A(1)</lang>
30 PRINT A(1)</syntaxhighlight>


=={{header|NSIS}}==
=={{header|NSIS}}==
Line 5,515: Line 5,515:
NSIS does not have native support for arrays. Array support is provided by the [http://nsis.sourceforge.net/Arrays_in_NSIS NSISArray] plugin.
NSIS does not have native support for arrays. Array support is provided by the [http://nsis.sourceforge.net/Arrays_in_NSIS NSISArray] plugin.
</div>
</div>
<lang nsis>
<syntaxhighlight lang=nsis>
!include NSISArray.nsh
!include NSISArray.nsh
Function ArrayTest
Function ArrayTest
Line 5,529: Line 5,529:
Pop $0
Pop $0
FunctionEnd
FunctionEnd
</syntaxhighlight>
</lang>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE Arrays;
MODULE Arrays;
IMPORT
IMPORT
Line 5,569: Line 5,569:
Dynamic
Dynamic
END Arrays.
END Arrays.
</syntaxhighlight>
</lang>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang=objeck>
bundle Default {
bundle Default {
class Arithmetic {
class Arithmetic {
Line 5,583: Line 5,583:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<lang objc>// NSArrays are ordered collections of NSObject subclasses only.
<syntaxhighlight lang=objc>// NSArrays are ordered collections of NSObject subclasses only.


// Create an array of NSString objects.
// Create an array of NSString objects.
Line 5,609: Line 5,609:
// No nil termination is then needed.
// No nil termination is then needed.
NSArray *thirdArray = @[ @"Hewey", @"Louie", @"Dewey", @1, @2, @3 ];
NSArray *thirdArray = @[ @"Hewey", @"Louie", @"Dewey", @1, @2, @3 ];
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
in the toplevel:
in the toplevel:
<lang ocaml># Array.make 6 'A' ;;
<syntaxhighlight lang=ocaml># Array.make 6 'A' ;;
- : char array = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
- : char array = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]


Line 5,629: Line 5,629:


# arr ;;
# arr ;;
- : int array = [|0; 1; 2; 3; 65; 5; 6|]</lang>
- : int array = [|0; 1; 2; 3; 65; 5; 6|]</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 5,636: Line 5,636:
To create a mutable array, #new is used.
To create a mutable array, #new is used.


<lang Oforth>[ "abd", "def", "ghi" ] at( 3 ) .
<syntaxhighlight lang=Oforth>[ "abd", "def", "ghi" ] at( 3 ) .


Array new dup addAll( [1, 2, 3] ) dup put( 2, 8.1 ) .
Array new dup addAll( [1, 2, 3] ) dup put( 2, 8.1 ) .
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,659: Line 5,659:
The last element in a vector is indexed by minus one, and the first element is indexed by minus 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.


<lang scheme>
<syntaxhighlight lang=scheme>
; making a vector
; making a vector
> #(1 2 3 4 5)
> #(1 2 3 4 5)
Line 5,768: Line 5,768:
[7 8 3]])
[7 8 3]])
#false
#false
</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
ooRexx arrays hold object references. Arrays will automatically increase in size if needed.
ooRexx arrays hold object references. Arrays will automatically increase in size if needed.
<lang ooRexx> a = .array~new -- create a zero element array
<syntaxhighlight lang=ooRexx> a = .array~new -- create a zero element array
b = .array~new(10) -- create an array with initial size of 10
b = .array~new(10) -- create an array with initial size of 10
c = .array~of(1, 2, 3) -- create a 3 element array holding objects 1, 2, and 3
c = .array~of(1, 2, 3) -- create a 3 element array holding objects 1, 2, and 3
a[3] = "Fred" -- assign an item
a[3] = "Fred" -- assign an item
b[2] = a[3] -- retrieve an item from the array
b[2] = a[3] -- retrieve an item from the array
c~append(4) -- adds to end. c[4] == 4 now</lang>
c~append(4) -- adds to end. c[4] == 4 now</syntaxhighlight>


ooRexx provides a built-in array class that provides one- and more dimensional arrays
ooRexx provides a built-in array class that provides one- and more dimensional arrays
Line 5,796: Line 5,796:
to all compound variables with that stem.
to all compound variables with that stem.


<lang ooRexx>
<syntaxhighlight lang=ooRexx>
XXX.='*'
XXX.='*'
Say 'xxx.1='xxx.1 -- shows xxx.1=*
Say 'xxx.1='xxx.1 -- shows xxx.1=*
Line 5,802: Line 5,802:
xxx.u='Joe'
xxx.u='Joe'
Say 'xxx.u='xxx.17 -- shows xxx.u=Joe
Say 'xxx.u='xxx.17 -- shows xxx.u=Joe
</syntaxhighlight>
</lang>
ooRexx introduces a notation a.[x,y] where x and y can actually be expressions.
ooRexx introduces a notation a.[x,y] where x and y can actually be expressions.


Line 5,821: Line 5,821:
must not exceed 250 bytes no longer applies to ooRexx and Regina.
must not exceed 250 bytes no longer applies to ooRexx and Regina.
XXX.u.v...='something'
XXX.u.v...='something'
<lang ooRexx>u=17
<syntaxhighlight lang=ooRexx>u=17
v='John Doe'
v='John Doe'
XXX.u.v...='some value'
XXX.u.v...='some value'
z='17.John Doe...'
z='17.John Doe...'
Say xxx.z shows 'some value'</lang>
Say xxx.z shows 'some value'</syntaxhighlight>


When using a stem for storing structured data, as in
When using a stem for storing structured data, as in
<lang ooRexx>person.first='Walter'
<syntaxhighlight lang=ooRexx>person.first='Walter'
person.last='Pachl'</lang>
person.last='Pachl'</syntaxhighlight>
it is advisable to use constant symbols such as 0first and 0last in the tail
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.
since an accidental use of the variables first or last would render confusion.


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<lang oxygenbasic>
<syntaxhighlight lang=oxygenbasic>


'CREATING A STATIC ARRAY
'CREATING A STATIC ARRAY
Line 5,858: Line 5,858:
print f(2) 'value set to 0.0
print f(2) 'value set to 0.0
redim float f(0) 'release allocated memory '
redim float f(0) 'release allocated memory '
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==


<lang oz>declare
<syntaxhighlight lang=oz>declare
Arr = {Array.new 1 %% lowest index
Arr = {Array.new 1 %% lowest index
10 %% highest index
10 %% highest index
Line 5,869: Line 5,869:
{Show Arr.1}
{Show Arr.1}
Arr.1 := 64
Arr.1 := 64
{Show Arr.1}</lang>
{Show Arr.1}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>v=[];
<syntaxhighlight lang=parigp>v=[];
v=concat(v,7);
v=concat(v,7);
v[1]</lang>
v[1]</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
A modification of the Delphi example:
A modification of the Delphi example:
<lang pascal>
<syntaxhighlight lang=pascal>
Program ArrayDemo;
Program ArrayDemo;
uses
uses
Line 5,912: Line 5,912:
writeln(DynamicArrayText);
writeln(DynamicArrayText);
end.
end.
</syntaxhighlight>
</lang>


=={{header|Perl}}==
=={{header|Perl}}==
Line 5,918: Line 5,918:
In-line
In-line


<lang perl> my @empty;
<syntaxhighlight lang=perl> my @empty;
my @empty_too = ();
my @empty_too = ();
Line 5,926: Line 5,926:
my $aref = ['This', 'That', 'And', 'The', 'Other'];
my $aref = ['This', 'That', 'And', 'The', 'Other'];
print $aref->[2]; # And
print $aref->[2]; # And
</syntaxhighlight>
</lang>


Dynamic
Dynamic


<lang perl>my @arr;
<syntaxhighlight lang=perl>my @arr;


push @arr, 1;
push @arr, 1;
Line 5,937: Line 5,937:
$arr[0] = 2;
$arr[0] = 2;


print $arr[0];</lang>
print $arr[0];</syntaxhighlight>


Two-dimensional
Two-dimensional


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


=={{header|Phix}}==
=={{header|Phix}}==
Line 5,956: Line 5,956:
without any need to worry about memory management issues.
without any need to worry about memory management issues.


<!--<lang Phix>-->
<!--<syntaxhighlight lang=Phix>-->
<span style="color: #000080;font-style:italic;">-- simple one-dimensional arrays:</span>
<span style="color: #000080;font-style:italic;">-- simple one-dimensional arrays:</span>
<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>
<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>
Line 6,031: Line 6,031:
<span style="color: #0000FF;">?</span><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;">s2</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s2</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


{{out}}
{{out}}
Line 6,045: Line 6,045:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang=Phixmonti>include ..\Utilitys.pmt


0 tolist /# create an empty array/list. '( )' is equivalent #/
0 tolist /# create an empty array/list. '( )' is equivalent #/
Line 6,059: Line 6,059:
3 2 slice /# extract the subarray/sublist [ 2 "Hello" ] #/
3 2 slice /# extract the subarray/sublist [ 2 "Hello" ] #/


pstack /# show the content of the stack #/ </lang>
pstack /# show the content of the stack #/ </syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
===Writing To An Array===
===Writing To An Array===
====Single Dimension====
====Single Dimension====
<lang php>$NumberArray = array(0, 1, 2, 3, 4, 5, 6);
<syntaxhighlight lang=php>$NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];</lang>
$simpleForm = ['apple', 'orange'];</syntaxhighlight>


====Multi-Dimensional====
====Multi-Dimensional====
<lang php>$MultiArray = array(
<syntaxhighlight lang=php>$MultiArray = array(
array(0, 0, 0, 0, 0, 0),
array(0, 0, 0, 0, 0, 0),
array(1, 1, 1, 1, 1, 1),
array(1, 1, 1, 1, 1, 1),
array(2, 2, 2, 2, 2, 2),
array(2, 2, 2, 2, 2, 2),
array(3, 3, 3, 3, 3, 3)
array(3, 3, 3, 3, 3, 3)
);</lang>
);</syntaxhighlight>


====Array push====
====Array push====


<lang php>$arr = ['apple', 'orange'];
<syntaxhighlight lang=php>$arr = ['apple', 'orange'];
array_push($arr, 'pear');
array_push($arr, 'pear');
print implode(',', $arr); // Returns apple,orange,pear</lang>
print implode(',', $arr); // Returns apple,orange,pear</syntaxhighlight>


===Reading From An Array===
===Reading From An Array===
====Single Dimension====
====Single Dimension====
Read the 5th value in the array:
Read the 5th value in the array:
<lang php>echo $NumberArray[5]; // Returns 5
<syntaxhighlight lang=php>echo $NumberArray[5]; // Returns 5
echo $LetterArray[5]; // Returns f</lang>
echo $LetterArray[5]; // Returns f</syntaxhighlight>
====Multi-Dimensional====
====Multi-Dimensional====
Read the 2nd line, column 5
Read the 2nd line, column 5
<lang php>echo $MultiArray[1][5]; // 2</lang>
<syntaxhighlight lang=php>echo $MultiArray[1][5]; // 2</syntaxhighlight>
===Print a whole array===
===Print a whole array===
This is useful while developing to view the contents of an array:
This is useful while developing to view the contents of an array:
<lang php>print_r($MultiArray);</lang>
<syntaxhighlight lang=php>print_r($MultiArray);</syntaxhighlight>
Which would give us:
Which would give us:
<lang php>Array(
<syntaxhighlight lang=php>Array(
0 => array(
0 => array(
0 => 0
0 => 0
Line 6,127: Line 6,127:
5 => 3
5 => 3
)
)
)</lang>
)</syntaxhighlight>
=== Set custom keys for values===
=== Set custom keys for values===
This example starts the indexing from 1 instead of 0
This example starts the indexing from 1 instead of 0
<lang php>$StartIndexAtOne = array(1 => "A", "B", "C", "D");</lang>
<syntaxhighlight lang=php>$StartIndexAtOne = array(1 => "A", "B", "C", "D");</syntaxhighlight>
This example shows how you can apply any key you want
This example shows how you can apply any key you want
<lang php>$CustomKeyArray = array("d" => "A", "c" => "B", "b" =>"C", "a" =>"D");</lang>
<syntaxhighlight lang=php>$CustomKeyArray = array("d" => "A", "c" => "B", "b" =>"C", "a" =>"D");</syntaxhighlight>


To read the 3rd value of the second array:
To read the 3rd value of the second array:
<lang php>echo $CustomKeyArray["b"]; // Returns C</lang>
<syntaxhighlight lang=php>echo $CustomKeyArray["b"]; // Returns C</syntaxhighlight>


===Other Examples===
===Other Examples===
Create a blank array:
Create a blank array:
<lang php>$BlankArray = array();</lang>
<syntaxhighlight lang=php>$BlankArray = array();</syntaxhighlight>


Set a value for the next key in the array:
Set a value for the next key in the array:
<lang php>$BlankArray[] = "Not Blank Anymore";</lang>
<syntaxhighlight lang=php>$BlankArray[] = "Not Blank Anymore";</syntaxhighlight>


Assign a value to a certain key:
Assign a value to a certain key:
<lang php>$AssignArray["CertainKey"] = "Value";</lang>
<syntaxhighlight lang=php>$AssignArray["CertainKey"] = "Value";</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
Line 6,151: Line 6,151:


Here are some examples how to use arrays.
Here are some examples how to use arrays.
<lang Picat>import util.
<syntaxhighlight lang=Picat>import util.


go =>
go =>
Line 6,196: Line 6,196:


nl.
nl.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 6,218: Line 6,218:


{{trans|Prolog}}
{{trans|Prolog}}
<lang Picat>listvariant :-
<syntaxhighlight lang=Picat>listvariant :-
List = new_list(5), % create a list of length 5
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(1,List,a), % put an a at position 1 , nth/3 uses indexing from 1
Line 6,231: Line 6,231:
Value = List3[1], % get the value at position 1
Value = List3[1], % get the value at position 1
println(value=Value). % will print out a
println(value=Value). % will print out a
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 6,244: Line 6,244:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
PicoLisp has no built-in array data type. Lists are used instead.
PicoLisp has no built-in array data type. Lists are used instead.
<lang PicoLisp>(setq A '((1 2 3) (a b c) ((d e) NIL 777))) # Create a 3x3 structure
<syntaxhighlight lang=PicoLisp>(setq A '((1 2 3) (a b c) ((d e) NIL 777))) # Create a 3x3 structure
(mapc println A) # Show it</lang>
(mapc println A) # Show it</syntaxhighlight>
{{out}}
{{out}}
<pre>(1 2 3)
<pre>(1 2 3)
Line 6,251: Line 6,251:
((d e) NIL 777)</pre>
((d e) NIL 777)</pre>
Replace 'b' with 'B' in middle row:
Replace 'b' with 'B' in middle row:
<lang PicoLisp>(set (nth A 2 2) 'B)
<syntaxhighlight lang=PicoLisp>(set (nth A 2 2) 'B)
(mapc println A)</lang>
(mapc println A)</syntaxhighlight>
{{out}}
{{out}}
<pre>(1 2 3)
<pre>(1 2 3)
Line 6,258: Line 6,258:
((d e) NIL 777)</pre>
((d e) NIL 777)</pre>
Insert '1' in front of the middle row:
Insert '1' in front of the middle row:
<lang PicoLisp>(push (cdr A) 1)
<syntaxhighlight lang=PicoLisp>(push (cdr A) 1)
(mapc println A)</lang>
(mapc println A)</syntaxhighlight>
{{out}}
{{out}}
<pre>(1 2 3)
<pre>(1 2 3)
Line 6,265: Line 6,265:
((d e) NIL 777)</pre>
((d e) NIL 777)</pre>
Append '9' to the middle row:
Append '9' to the middle row:
<lang PicoLisp>(queue (cdr A) 9)
<syntaxhighlight lang=PicoLisp>(queue (cdr A) 9)
(mapc println A)</lang>
(mapc println A)</syntaxhighlight>
{{out}}
{{out}}
<pre>(1 2 3)
<pre>(1 2 3)
Line 6,273: Line 6,273:


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>int main(){
<syntaxhighlight lang=pike>int main(){
// Initial array, few random elements.
// Initial array, few random elements.
array arr = ({3,"hi",84.2});
array arr = ({3,"hi",84.2});
Line 6,280: Line 6,280:


write(arr[5] + "\n"); // And finally print element 5.
write(arr[5] + "\n"); // And finally print element 5.
}</lang>
}</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>/* Example of an array having fixed dimensions */
<syntaxhighlight lang=pli>/* Example of an array having fixed dimensions */
declare A(10) float initial (1, 9, 4, 6, 7, 2, 5, 8, 3, 10);
declare A(10) float initial (1, 9, 4, 6, 7, 2, 5, 8, 3, 10);


Line 6,303: Line 6,303:
C = 0;
C = 0;
c(7) = 12;
c(7) = 12;
put (C(9));</lang>
put (C(9));</syntaxhighlight>


=={{header|Plain English}}==
=={{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.
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.


<lang plainenglish>To run:
<syntaxhighlight lang=plainenglish>To run:
Start up.
Start up.
Write "Creating an array of 100 numbers..." on the console.
Write "Creating an array of 100 numbers..." on the console.
Line 6,352: Line 6,352:
Put the number array's first element pointer into a number pointer.
Put the number array's first element pointer into a number pointer.
Add the offset to the number pointer.
Add the offset to the number pointer.
Put the number into the number pointer's target.</lang>
Put the number into the number pointer's target.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,366: Line 6,366:


Arrays are homogenous.
Arrays are homogenous.
<lang Pony>use "assert" // due to the use of Fact
<syntaxhighlight lang=Pony>use "assert" // due to the use of Fact


- - -
- - -
Line 6,382: Line 6,382:
Fact(s == 3) // size of array 'other' is 3
Fact(s == 3) // size of array 'other' is 3
other(1) = 40 // 'other' now is [10, 40, 30]
other(1) = 40 // 'other' now is [10, 40, 30]
end</lang>
end</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
Line 6,402: Line 6,402:


x 1 get
x 1 get
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Empty array:
Empty array:
<lang powershell>$a = @()</lang>
<syntaxhighlight lang=powershell>$a = @()</syntaxhighlight>
Array initialized with only one member:
Array initialized with only one member:
<lang powershell>$a = ,2
<syntaxhighlight lang=powershell>$a = ,2
$a = @(2) # alternative</lang>
$a = @(2) # alternative</syntaxhighlight>
Longer arrays can simply be created by separating the values with commas:
Longer arrays can simply be created by separating the values with commas:
<lang powershell>$a = 1,2,3</lang>
<syntaxhighlight lang=powershell>$a = 1,2,3</syntaxhighlight>
A value can be appended to an array using the <code>+=</code> operator:
A value can be appended to an array using the <code>+=</code> operator:
<lang powershell>$a += 5</lang>
<syntaxhighlight lang=powershell>$a += 5</syntaxhighlight>
Since arrays are immutable this simply creates a new array containing one more member.
Since arrays are immutable this simply creates a new array containing one more member.


Values can be retrieved using a fairly standard indexing syntax:
Values can be retrieved using a fairly standard indexing syntax:
<lang powershell>$a[1]</lang>
<syntaxhighlight lang=powershell>$a[1]</syntaxhighlight>
Similarly, those values can also be replaced:
Similarly, those values can also be replaced:
<lang powershell>$a[1] = 42</lang>
<syntaxhighlight lang=powershell>$a[1] = 42</syntaxhighlight>
The range operator <code>..</code> can be used to create contiguous ranges of integers as arrays:
The range operator <code>..</code> can be used to create contiguous ranges of integers as arrays:
<lang powershell>$r = 1..100</lang>
<syntaxhighlight lang=powershell>$r = 1..100</syntaxhighlight>
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:
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:
<lang powershell>$r[0..9+25..27+80,85,90]</lang>
<syntaxhighlight lang=powershell>$r[0..9+25..27+80,85,90]</syntaxhighlight>
Indexing from the end of the array can be done with negative numbers:
Indexing from the end of the array can be done with negative numbers:
<lang powershell>$r[-1] # last index</lang>
<syntaxhighlight lang=powershell>$r[-1] # last index</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 6,434: Line 6,434:
retrieve and set elements.
retrieve and set elements.


<lang prolog>
<syntaxhighlight lang=prolog>
singleassignment:-
singleassignment:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
functor(Array,array,100), % create a term with 100 free Variables as arguments
Line 6,444: Line 6,444:
arg(4 ,Array,Value2), % get the value at position 4 which is a free Variable
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
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
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.
programming languages, setarg/3 can be used.


<lang prolog>
<syntaxhighlight lang=prolog>
destructive:-
destructive:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
functor(Array,array,100), % create a term with 100 free Variables as arguments
Line 6,458: Line 6,458:
arg(1 ,Array,Value1), % get the value at position 1
arg(1 ,Array,Value1), % get the value at position 1
print(Value1),nl. % will print Value1 and therefore c followed by a newline
print(Value1),nl. % will print Value1 and therefore c followed by a newline
</syntaxhighlight>
</lang>


Lists can be used as arrays.
Lists can be used as arrays.


<lang prolog>
<syntaxhighlight lang=prolog>
listvariant:-
listvariant:-
length(List,100), % create a list of length 100
length(List,100), % create a list of length 100
Line 6,472: Line 6,472:
nth1(1 ,List3,Value), % get the value at position 1
nth1(1 ,List3,Value), % get the value at position 1
print(Value),nl. % will print out a
print(Value),nl. % will print out a
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Line 6,478: Line 6,478:
'''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.
'''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.


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


=={{header|Python}}==
=={{header|Python}}==
Python lists are dynamically resizeable.
Python lists are dynamically resizeable.
<lang python>array = []
<syntaxhighlight lang=python>array = []


array.append(1)
array.append(1)
Line 6,511: Line 6,511:
array[0] = 2
array[0] = 2


print array[0]</lang>
print array[0]</syntaxhighlight>


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


<lang python>myArray = [0] * size</lang>
<syntaxhighlight lang=python>myArray = [0] * size</syntaxhighlight>


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


<lang python>myArray = [[0]* width] * height # DOES NOT WORK AS INTENDED!!!</lang>
<syntaxhighlight lang=python>myArray = [[0]* width] * height # DOES NOT WORK AS INTENDED!!!</syntaxhighlight>


This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of 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.
This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of 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.
Line 6,525: Line 6,525:
To initialize a list of lists one could use a pair of nested list comprehensions like so:
To initialize a list of lists one could use a pair of nested list comprehensions like so:


<lang python>myArray = [[0 for x in range(width)] for y in range(height)]</lang>
<syntaxhighlight lang=python>myArray = [[0 for x in range(width)] for y in range(height)]</syntaxhighlight>


That is equivalent to:
That is equivalent to:


<lang python>myArray = list()
<syntaxhighlight lang=python>myArray = list()
for x in range(height):
for x in range(height):
myArray.append([0] * width)</lang>
myArray.append([0] * width)</syntaxhighlight>


To retrieve an element in an array, use any of the following methods:
To retrieve an element in an array, use any of the following methods:


<lang python>
<syntaxhighlight lang=python>
# Retrieve an element directly from the array.
# Retrieve an element directly from the array.
item = array[index]
item = array[index]
Line 6,545: Line 6,545:
# Using a negative element counts from the end of the list.
# Using a negative element counts from the end of the list.
item = array[-1] # Retrieve last element in a list.
item = array[-1] # Retrieve last element in a list.
</syntaxhighlight>
</lang>


Python produces an IndexError when accessing elements out of range:
Python produces an IndexError when accessing elements out of range:
<lang python>
<syntaxhighlight lang=python>
try:
try:
# This will cause an exception, which will then be caught.
# This will cause an exception, which will then be caught.
Line 6,555: Line 6,555:
# Print the exception.
# Print the exception.
print e
print e
</syntaxhighlight>
</lang>


=={{header|QB64}}==
=={{header|QB64}}==
<lang QB64>
<syntaxhighlight lang=QB64>
'Task
'Task
'Show basic array syntax in your language.
'Show basic array syntax in your language.
Line 6,676: Line 6,676:




</syntaxhighlight>
</lang>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 6,749: Line 6,749:
Dynamic
Dynamic


<lang R>arr <- array(1)
<syntaxhighlight lang=R>arr <- array(1)


arr <- append(arr,3)
arr <- append(arr,3)
Line 6,755: Line 6,755:
arr[1] <- 2
arr[1] <- 2


print(arr[1])</lang>
print(arr[1])</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang Racket>#lang racket
<syntaxhighlight lang=Racket>#lang racket


;; import dynamic arrays
;; import dynamic arrays
Line 6,770: Line 6,770:
(gvector-ref gv 0) ; 1
(gvector-ref gv 0) ; 1
(gvector-add! gv 5) ; increase size
(gvector-add! gv 5) ; increase size
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 6,776: Line 6,776:
At its most basic, an array in Raku is quite similar to an array in Perl 5.
At its most basic, an array in Raku is quite similar to an array in Perl 5.


<lang perl6>my @arr;
<syntaxhighlight lang=perl6>my @arr;
push @arr, 1;
push @arr, 1;
Line 6,783: Line 6,783:
@arr[0] = 2;
@arr[0] = 2;
say @arr[0];</lang>
say @arr[0];</syntaxhighlight>


===Some further exposition:===
===Some further exposition:===
Line 6,854: Line 6,854:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>
<syntaxhighlight lang=REBOL>
a: [] ; Empty.
a: [] ; Empty.
b: ["foo"] ; Pre-initialized.
b: ["foo"] ; Pre-initialized.
</syntaxhighlight>
</lang>


Inserting and appending.
Inserting and appending.


<lang REBOL>
<syntaxhighlight lang=REBOL>
append a ["up" "down"] ; -> ["up" "down"]
append a ["up" "down"] ; -> ["up" "down"]
insert a [left right] ; -> [left right "up" "down"]
insert a [left right] ; -> [left right "up" "down"]
</syntaxhighlight>
</lang>


Getting specific values.
Getting specific values.


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


Getting subsequences. REBOL allows relative motion through a block (list).
Getting subsequences. REBOL allows relative motion through a block (list).
Line 6,879: Line 6,879:
you can even assign to it without destroying the list.
you can even assign to it without destroying the list.


<lang REBOL>
<syntaxhighlight lang=REBOL>
a ; -> [left right "up" "down"]
a ; -> [left right "up" "down"]
next a ; -> [right "up" "down"]
next a ; -> [right "up" "down"]
Line 6,890: Line 6,890:
copy/part a 2 ; -> [left right]
copy/part a 2 ; -> [left right]
copy/part skip a 2 2 ; -> ["up" "down"]
copy/part skip a 2 2 ; -> ["up" "down"]
</syntaxhighlight>
</lang>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>arr1: [] ;create empty array
<syntaxhighlight lang=Red>arr1: [] ;create empty array
arr2: ["apple" "orange" 1 2 3] ;create an array with data
arr2: ["apple" "orange" 1 2 3] ;create an array with data
>> insert arr1 "blue"
>> insert arr1 "blue"
Line 6,906: Line 6,906:
== "black"
== "black"
>> pick arr1 2
>> pick arr1 2
== "black"</lang>
== "black"</syntaxhighlight>
A vector! is a high-performance series! of items.
A vector! is a high-performance series! of items.
The items in a vector! must all have the same type.
The items in a vector! must all have the same type.
The allowable item types are: integer! float! char! percent!
The allowable item types are: integer! float! char! percent!
Vectors of string! are not allowed.
Vectors of string! are not allowed.
<lang Red>>> vec1: make vector! [ 20 30 70]
<syntaxhighlight lang=Red>>> vec1: make vector! [ 20 30 70]
== make vector! [20 30 70]
== make vector! [20 30 70]
>> vec1/2
>> vec1/2
Line 6,926: Line 6,926:
*** Script Error: invalid argument: 3.0
*** Script Error: invalid argument: 3.0
*** Where: append
*** Where: append
*** Stack:</lang>
*** Stack:</syntaxhighlight>


=={{header|ReScript}}==
=={{header|ReScript}}==


<lang ReScript>let arr = [1, 2, 3]
<syntaxhighlight lang=ReScript>let arr = [1, 2, 3]


let _ = Js.Array2.push(arr, 4)
let _ = Js.Array2.push(arr, 4)
Line 6,936: Line 6,936:
arr[3] = 5
arr[3] = 5


Js.log(Js.Int.toString(arr[3]))</lang>
Js.log(Js.Int.toString(arr[3]))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,947: Line 6,947:
Retro has a vocabulary for creating and working with arrays.
Retro has a vocabulary for creating and working with arrays.


<lang Retro>
<syntaxhighlight lang=Retro>
needs array'
needs array'


Line 6,982: Line 6,982:
( Create a quote from the values in an array )
( Create a quote from the values in an array )
d ^array'toQuote
d ^array'toQuote
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
Line 6,989: Line 6,989:


===simple arrays===
===simple arrays===
<lang rexx>/*REXX program demonstrates a simple array usage. */
<syntaxhighlight lang=rexx>/*REXX program demonstrates a simple array usage. */
a.='not found' /*value for all a.xxx (so far).*/
a.='not found' /*value for all a.xxx (so far).*/
do j=1 to 100 /*start at 1, define 100 elements*/
do j=1 to 100 /*start at 1, define 100 elements*/
Line 6,997: Line 6,997:
say 'element 50 is:' a.50
say 'element 50 is:' a.50
say 'element 3000 is:' a.3000
say 'element 3000 is:' a.3000
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,005: Line 7,005:


===simple arrays, mimic other languages===
===simple arrays, mimic other languages===
<lang rexx>/*REXX program demonstrates array usage with mimicry. */
<syntaxhighlight lang=rexx>/*REXX program demonstrates array usage with mimicry. */
a. = 'not found' /*value for all a.xxx (so far). */
a. = 'not found' /*value for all a.xxx (so far). */
do j=1 to 100 /*start at 1, define 100 elements*/
do j=1 to 100 /*start at 1, define 100 elements*/
Line 7,015: Line 7,015:
exit /*stick a fork in it, we're done.*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────A subroutine────────────────────────*/
/*──────────────────────────────────A subroutine────────────────────────*/
a: _a_ = arg(1); return a._a_</lang>
a: _a_ = arg(1); return a._a_</syntaxhighlight>
<pre>
<pre>
element 50 is: -5000
element 50 is: -5000
Line 7,022: Line 7,022:


===simple arrays, assigned default===
===simple arrays, assigned default===
<lang rexx>/*REXX program demonstrates array usage with mimicry. */
<syntaxhighlight lang=rexx>/*REXX program demonstrates array usage with mimicry. */
a. = 00 /*value for all a.xxx (so far). */
a. = 00 /*value for all a.xxx (so far). */
do j=1 to 100 /*start at 1, define 100 elements*/
do j=1 to 100 /*start at 1, define 100 elements*/
Line 7,032: Line 7,032:
exit /*stick a fork in it, we're done.*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────A subroutine────────────────────────*/
/*──────────────────────────────────A subroutine────────────────────────*/
a: _a_ = arg(1); return a._a_</lang>
a: _a_ = arg(1); return a._a_</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,040: Line 7,040:


===arrays with non-unity index start===
===arrays with non-unity index start===
<lang rexx>/*REXX program demonstrates array usage (with elements out-of-range).*/
<syntaxhighlight lang=rexx>/*REXX program demonstrates array usage (with elements out-of-range).*/
array. = 'out of range' /*define ALL elements to this. */
array. = 'out of range' /*define ALL elements to this. */


Line 7,049: Line 7,049:
say g "squared is:" array.g
say g "squared is:" array.g
say 7000 "squared is:" array.7000
say 7000 "squared is:" array.7000
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,057: Line 7,057:


===arrays, disjoint===
===arrays, disjoint===
<lang rexx>/*REXX program demonstrates disjointed array usage. */
<syntaxhighlight lang=rexx>/*REXX program demonstrates disjointed array usage. */
yr. = 'year not supported' /*value for all yr.xxx (so far).*/
yr. = 'year not supported' /*value for all yr.xxx (so far).*/


Line 7,073: Line 7,073:
year=1744
year=1744
say 'DOB' year "is:" yr.year
say 'DOB' year "is:" yr.year
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,081: Line 7,081:


===sparse arrays and special indices===
===sparse arrays and special indices===
<lang rexx>/*REXX program demonstrates array usage: sparse and disjointed. */
<syntaxhighlight lang=rexx>/*REXX program demonstrates array usage: sparse and disjointed. */
yyy = -55 /*REXX must use this mechanism···*/
yyy = -55 /*REXX must use this mechanism···*/
a.yyy = 1e9 /*··· when assigning neg indices.*/
a.yyy = 1e9 /*··· when assigning neg indices.*/
Line 7,107: Line 7,107:
│ identify stemmed arrays (the period). │
│ identify stemmed arrays (the period). │
└────────────────────────────────────────────────────────────────────┘*/
└────────────────────────────────────────────────────────────────────┘*/
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
Line 7,113: Line 7,113:
Dynamic
Dynamic


<lang ring># create an array with one string in it
<syntaxhighlight lang=ring># create an array with one string in it
a = ['foo']
a = ['foo']


Line 7,123: Line 7,123:


# retrieve an element
# retrieve an element
see a[1]</lang>
see a[1]</syntaxhighlight>


=={{header|RLaB}}==
=={{header|RLaB}}==
<lang RLaB>
<syntaxhighlight lang=RLaB>
// 1-D (row- or column-vectors)
// 1-D (row- or column-vectors)
// Static:
// Static:
Line 7,158: Line 7,158:




</syntaxhighlight>
</lang>


=={{header|Robotic}}==
=={{header|Robotic}}==
Robotic does not natively support arrays of any kind.
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.
However, using [https://www.digitalmzx.net/wiki/index.php?title=Counter_interpolation Counter Interpolation], we can create a simple (faux) array.
<lang robotic>
<syntaxhighlight lang=robotic>
set "index" to 0
set "index" to 0
. "Assign random values to array"
. "Assign random values to array"
Line 7,173: Line 7,173:
* "Value of index 50 is ('array('50')')."
* "Value of index 50 is ('array('50')')."
end
end
</syntaxhighlight>
</lang>


You can even create multi-dimensional arrays using the Counter Interpolation method.
You can even create multi-dimensional arrays using the Counter Interpolation method.
<lang robotic>
<syntaxhighlight lang=robotic>
set "xx" to 0
set "xx" to 0
set "yy" to 0
set "yy" to 0
Line 7,190: Line 7,190:
* "Value of 16,16 is ('array('16'),('16')')."
* "Value of 16,16 is ('array('16'),('16')')."
end
end
</syntaxhighlight>
</lang>


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.
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.
Line 7,198: Line 7,198:
{{works with|ILE RPG}}
{{works with|ILE RPG}}


<lang rpg>
<syntaxhighlight lang=rpg>
//-Static array
//-Static array
//--def of 10 el array of integers, initialised to zeros
//--def of 10 el array of integers, initialised to zeros
Line 7,226: Line 7,226:
/end-free
/end-free
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 7,232: Line 7,232:
Dynamic
Dynamic


<lang ruby># create an array with one object in it
<syntaxhighlight lang=ruby># create an array with one object in it
a = ['foo']
a = ['foo']


Line 7,251: Line 7,251:


# retrieve an element
# retrieve an element
puts a[0]</lang>
puts a[0]</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>print "Enter array 1 greater than 0"; : input a1
<syntaxhighlight lang=runbasic>print "Enter array 1 greater than 0"; : input a1
print "Enter array 2 greater than 0"; : input a2
print "Enter array 2 greater than 0"; : input a2
Line 7,262: Line 7,262:
chrArray$(1,1) = "Hello"
chrArray$(1,1) = "Hello"
numArray(1,1) = 987.2
numArray(1,1) = 987.2
print chrArray$(1,1);" ";numArray(1,1)</lang>
print chrArray$(1,1);" ";numArray(1,1)</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Line 7,270: Line 7,270:
By default, arrays are immutable unless defined otherwise.
By default, arrays are immutable unless defined otherwise.


<lang rust>let a = [1, 2, 3]; // immutable array
<syntaxhighlight lang=rust>let a = [1, 2, 3]; // immutable array
let mut m = [1, 2, 3]; // mutable array
let mut m = [1, 2, 3]; // mutable array
let zeroes = [0; 200]; // creates an array of 200 zeroes</lang>
let zeroes = [0; 200]; // creates an array of 200 zeroes</syntaxhighlight>


To get the length and iterate,
To get the length and iterate,


<lang rust>let a = [1, 2, 3];
<syntaxhighlight lang=rust>let a = [1, 2, 3];
a.len();
a.len();
for e in a.iter() {
for e in a.iter() {
e;
e;
}</lang>
}</syntaxhighlight>


Accessing a particular element uses subscript notation, starting from 0.
Accessing a particular element uses subscript notation, starting from 0.


<lang rust>let names = ["Graydon", "Brian", "Niko"];
<syntaxhighlight lang=rust>let names = ["Graydon", "Brian", "Niko"];
names[1]; // second element</lang>
names[1]; // second element</syntaxhighlight>


Dynamic arrays in Rust are called vectors.
Dynamic arrays in Rust are called vectors.


<lang rust>let v = vec![1, 2, 3];</lang>
<syntaxhighlight lang=rust>let v = vec![1, 2, 3];</syntaxhighlight>


However, this defines an immutable vector. To add elements to a vector, we need to define v to be mutable.
However, this defines an immutable vector. To add elements to a vector, we need to define v to be mutable.


<lang rust>let mut v = vec![1, 2, 3];
<syntaxhighlight lang=rust>let mut v = vec![1, 2, 3];
v.push(4);
v.push(4);
v.len(); // 4</lang>
v.len(); // 4</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>-- a is an array of INTs
<syntaxhighlight lang=sather>-- a is an array of INTs
a :ARRAY{INT};
a :ARRAY{INT};
-- create an array of five "void" elements
-- create an array of five "void" elements
Line 7,309: Line 7,309:
b[1] := c; -- syntactic sugar for b.aset(1, c)
b[1] := c; -- syntactic sugar for b.aset(1, c)
-- append another array
-- append another array
b := b.append(|5.5|);</lang>
b := b.append(|5.5|);</syntaxhighlight>


=={{header|Scala}}==
=={{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.
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.
<lang scala>// Create a new integer array with capacity 10
<syntaxhighlight lang=scala>// Create a new integer array with capacity 10
val a = new Array[Int](10)
val a = new Array[Int](10)


Line 7,323: Line 7,323:


// Retrieve item at element 2
// Retrieve item at element 2
val c = b(2)</lang>
val c = b(2)</syntaxhighlight>
Dynamic arrays can be made using <code>ArrayBuffer</code>s:
Dynamic arrays can be made using <code>ArrayBuffer</code>s:
<lang scala>val a = new collection.mutable.ArrayBuffer[Int]
<syntaxhighlight lang=scala>val a = new collection.mutable.ArrayBuffer[Int]
a += 5 // Append value 5 to the end of the list
a += 5 // Append value 5 to the end of the list
a(0) = 6 // Assign value 6 to element 0</lang>
a(0) = 6 // Assign value 6 to element 0</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Lists are more often used in Scheme than vectors.
Lists are more often used in Scheme than vectors.


<lang scheme>(let ((array #(1 2 3 4 5)) ; vector literal
<syntaxhighlight lang=scheme>(let ((array #(1 2 3 4 5)) ; vector literal
(array2 (make-vector 5)) ; default is unspecified
(array2 (make-vector 5)) ; default is unspecified
(array3 (make-vector 5 0))) ; default 0
(array3 (make-vector 5 0))) ; default 0
(vector-set! array 0 3)
(vector-set! array 0 3)
(vector-ref array 0)) ; 3</lang>
(vector-ref array 0)) ; 3</syntaxhighlight>


=={{header|Scratch}}==
=={{header|Scratch}}==
Line 7,348: Line 7,348:
Every type, which can be mapped to integer, can be used as index type.
Every type, which can be mapped to integer, can be used as index type.


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";


const type: charArray is array [char] string; # Define an array type for arrays with char index.
const type: charArray is array [char] string; # Define an array type for arrays with char index.
Line 7,382: Line 7,382:
array1 := array3[2 len 4]; # Assign a slice of four elements beginning with the second element.
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.
array1 := array3 & array6; # Concatenate two arrays and assign the result to array1.
end func;</lang>
end func;</syntaxhighlight>


=={{header|Self}}==
=={{header|Self}}==
Line 7,390: Line 7,390:
Creating simple vectors:
Creating simple vectors:
<lang self>vector copySize: 100</lang>
<syntaxhighlight lang=self>vector copySize: 100</syntaxhighlight>
<lang self>vector copySize: 100 FillingWith: anObject</lang>
<syntaxhighlight lang=self>vector copySize: 100 FillingWith: anObject</syntaxhighlight>


A polymorphic vector:
A polymorphic vector:
<lang self>(1 & 'Hello' & 2.0 & someObject) asVector</lang>
<syntaxhighlight lang=self>(1 & 'Hello' & 2.0 & someObject) asVector</syntaxhighlight>


Using a vector:
Using a vector:
<lang self>|v|
<syntaxhighlight lang=self>|v|
"creates an vector that holds up to 20 elements"
"creates an vector that holds up to 20 elements"
v: vector copySize: 20.
v: vector copySize: 20.
Line 7,405: Line 7,405:
(v at: 9) printLine.
(v at: 9) printLine.
"put 100 as second value"
"put 100 as second value"
vat: 1 Put: 100.</lang>
vat: 1 Put: 100.</syntaxhighlight>


Enumeration:
Enumeration:
<lang self>v do: [:each | each printLine].
<syntaxhighlight lang=self>v do: [:each | each printLine].
v copy mapBy: [:each | each squared].
v copy mapBy: [:each | each squared].
v copy filterBy: [:each | each > 10].</lang>
v copy filterBy: [:each | each > 10].</syntaxhighlight>


Using a squence:
Using a squence:
<lang self>|s|
<syntaxhighlight lang=self>|s|
"creates a new sequence"
"creates a new sequence"
s: sequence copyRemoveAll.
s: sequence copyRemoveAll.
Line 7,423: Line 7,423:
s removeFirst.
s removeFirst.
"Check size"
"Check size"
s size printLine.</lang>
s size printLine.</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>// Initial creation of an array
<syntaxhighlight lang=sensetalk>// Initial creation of an array
set a to (1, 2, 3)
set a to (1, 2, 3)


Line 7,454: Line 7,454:
// Changing the values in the array
// Changing the values in the array
set the third item of a to "abc"
set the third item of a to "abc"
put a -- (2, 3, "abc", 6)</lang>
put a -- (2, 3, "abc", 6)</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby># create an empty array
<syntaxhighlight lang=ruby># create an empty array
var arr = [];
var arr = [];


Line 7,485: Line 7,485:


# retrieve an element
# retrieve an element
say arr[-1]; #=> 'baz'</lang>
say arr[-1]; #=> 'baz'</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang=simula>BEGIN
PROCEDURE STATIC;
PROCEDURE STATIC;
Line 7,523: Line 7,523:
DYNAMIC(5)
DYNAMIC(5)
END ARRAYS.
END ARRAYS.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 7,530: Line 7,530:
</pre>
</pre>
One can write an ArrayList class like Java has in package java.util.
One can write an ArrayList class like Java has in package java.util.
<lang simula>BEGIN
<syntaxhighlight lang=simula>BEGIN


CLASS ITEM;;
CLASS ITEM;;
Line 7,675: Line 7,675:


END;
END;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>EXPAND TO CAPACITY 20
<pre>EXPAND TO CAPACITY 20
Line 7,763: Line 7,763:


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>slate[1]> #x := ##(1 2 3).
<syntaxhighlight lang=slate>slate[1]> #x := ##(1 2 3).
{1. 2. 3}
{1. 2. 3}
slate[2]> x
slate[2]> x
Line 7,776: Line 7,776:
1
1
slate[7]> x at: 0.
slate[7]> x at: 0.
1</lang>
1</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 7,787: Line 7,787:
Literal Arrays (Array constants):
Literal Arrays (Array constants):
<lang smalltalk>#(1 2 3 'four' 5.0 true false nil (10 20) $a)</lang>
<syntaxhighlight lang=smalltalk>#(1 2 3 'four' 5.0 true false nil (10 20) $a)</syntaxhighlight>
a polymorphic array containing integers, a string, a float, booleans, a nil, another array with integers and a character constant.
a polymorphic array containing integers, a string, a float, booleans, a nil, another array with integers and a character constant.


Programatic use:
Programatic use:
<lang smalltalk>|array|
<syntaxhighlight lang=smalltalk>|array|
"creates an array that holds up to 20 elements"
"creates an array that holds up to 20 elements"
array := Array new: 20 .
array := Array new: 20 .
Line 7,802: Line 7,802:
array := Array withAll: #('an' 'apple' 'a' 'day' 'keeps' 'the' 'doctor' 'away').
array := Array withAll: #('an' 'apple' 'a' 'day' 'keeps' 'the' 'doctor' 'away').
"Replacing apple with orange"
"Replacing apple with orange"
array at: 2 put: 'orange'.</lang>
array at: 2 put: 'orange'.</syntaxhighlight>


<lang smalltalk>"assigning values to an array"
<syntaxhighlight lang=smalltalk>"assigning values to an array"
"suppose array is bound to an array of 20 values"
"suppose array is bound to an array of 20 values"
array at: 5 put: 'substitute fifth element'.
array at: 5 put: 'substitute fifth element'.
Line 7,810: Line 7,810:
[ array at: 21 put: 'error' ]
[ array at: 21 put: 'error' ]
on: SystemExceptions.IndexOutOfRange
on: SystemExceptions.IndexOutOfRange
do: [ :sig | 'Out of range!' displayNl ].</lang>
do: [ :sig | 'Out of range!' displayNl ].</syntaxhighlight>


<lang smalltalk>"retrieving a value from an array"
<syntaxhighlight lang=smalltalk>"retrieving a value from an array"
#($a $b $c) at: 2</lang>
#($a $b $c) at: 2</syntaxhighlight>


Enumeration:
Enumeration:
<lang smalltalk>array do:[:each | each printOn: aStream ]
<syntaxhighlight lang=smalltalk>array do:[:each | each printOn: aStream ]
array collect:[:each | each squared|
array collect:[:each | each squared|
array select:[:each | each > 10]</lang>
array select:[:each | each > 10]</syntaxhighlight>


{{works with|Pharo}}
{{works with|Pharo}}
Line 7,824: Line 7,824:
{{works with|Squeak}}
{{works with|Squeak}}
Constructing an Array from evaluated expressions:
Constructing an Array from evaluated expressions:
<lang smalltalk>{ Time now . 10 . Date today . 'foo' }</lang>
<syntaxhighlight lang=smalltalk>{ Time now . 10 . Date today . 'foo' }</syntaxhighlight>
this construct evaluates each expression and creates a 4-element array containing a time, int, date and string object.
this construct evaluates each expression and creates a 4-element array containing a time, int, date and string object.


OrderedCollection:
OrderedCollection:
<lang smalltalk>oc := OrderedCollection withAll: #(4 5 6).
<syntaxhighlight lang=smalltalk>oc := OrderedCollection withAll: #(4 5 6).
oc add:1. oc add:2. oc add:3.
oc add:1. oc add:2. oc add:3.
foo := oc removeFirst.
foo := oc removeFirst.
Line 7,840: Line 7,840:
oc findFirst:[:el | el isString]
oc findFirst:[:el | el isString]
"hundreds of other methods skipped here.."
"hundreds of other methods skipped here.."
</syntaxhighlight>
</lang>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
SNOBOL4 supports multi-dimensional arrays and array initialization.
SNOBOL4 supports multi-dimensional arrays and array initialization.
<lang SNOBOL4> ar = ARRAY("3,2") ;* 3 rows, 2 columns
<syntaxhighlight lang=SNOBOL4> ar = ARRAY("3,2") ;* 3 rows, 2 columns
fill i = LT(i, 3) i + 1 :F(display)
fill i = LT(i, 3) i + 1 :F(display)
ar<i,1> = i
ar<i,1> = i
Line 7,853: Line 7,853:
OUTPUT = "Row " ar<j,1> ": " ar<j,2>
OUTPUT = "Row " ar<j,1> ": " ar<j,2>
+ :S(display)
+ :S(display)
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,862: Line 7,862:


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>a[1] = 2.5
<syntaxhighlight lang=spl>a[1] = 2.5
a[2] = 3
a[2] = 3
a[3] = "Result is "
a[3] = "Result is "
#.output(a[3],a[1]+a[2])</lang>
#.output(a[3],a[1]+a[2])</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,901: Line 7,901:
done: ; program continues</pre>
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.
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.
<lang ssem>10101000000000100000000000000000 0. -21 to c
<syntaxhighlight lang=ssem>10101000000000100000000000000000 0. -21 to c
11101000000000010000000000000000 1. Sub. 23
11101000000000010000000000000000 1. Sub. 23
00101000000001100000000000000000 2. c to 20
00101000000001100000000000000000 2. c to 20
Line 7,927: Line 7,927:
01000000000000000000000000000000 24. 2
01000000000000000000000000000000 24. 2
11000000000000000000000000000000 25. 3
11000000000000000000000000000000 25. 3
00100000000000000000000000000000 26. 4</lang>
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.
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}}==
=={{header|Standard ML}}==
<lang Standard ML>
<syntaxhighlight lang=Standard ML>
(* create first array and assign elements *)
(* create first array and assign elements *)
-val first = Array.tabulate (10,fn x=>x+10) ;
-val first = Array.tabulate (10,fn x=>x+10) ;
Line 7,943: Line 7,943:
-Array.sub(second,4);
-Array.sub(second,4);
val it = 14: int
val it = 14: int
</syntaxhighlight>
</lang>
=={{header|Stata}}==
=={{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.
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.
Line 7,957: Line 7,957:


=== Matrix command ===
=== Matrix command ===
<lang stata>matrix a = 2,9,4\7,5,3\6,1,8
<syntaxhighlight lang=stata>matrix a = 2,9,4\7,5,3\6,1,8
display det(a)
display det(a)
matrix svd u d v = a
matrix svd u d v = a
Line 7,964: Line 7,964:
* store the u and v matrices in the current dataset
* store the u and v matrices in the current dataset
svmat u
svmat u
svmat v</lang>
svmat v</syntaxhighlight>


=== Mata ===
=== Mata ===
<lang stata>mata
<syntaxhighlight lang=stata>mata
a = 2,9,4\7,5,3\6,1,8
a = 2,9,4\7,5,3\6,1,8
det(a)
det(a)
Line 7,973: Line 7,973:
// Notice that to reconstruct the matrix, v is not transposed here,
// Notice that to reconstruct the matrix, v is not transposed here,
// while it is with -matrix svd- in Stata.
// while it is with -matrix svd- in Stata.
u*diag(s)*v</lang>
u*diag(s)*v</syntaxhighlight>


=={{header|Suneido}}==
=={{header|Suneido}}==
<lang Suneido>array = Object('zero', 'one', 'two')
<syntaxhighlight lang=Suneido>array = Object('zero', 'one', 'two')
array.Add('three')
array.Add('three')
array.Add('five', at: 5)
array.Add('five', at: 5)
array[4] = 'four'
array[4] = 'four'
Print(array[3]) --> 'three'</lang>
Print(array[3]) --> 'three'</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>// Arrays are typed in Swift, however, using the Any object we can add any type. Swift does not support fixed length arrays
<syntaxhighlight lang=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]()
var anyArray = [Any]()
anyArray.append("foo") // Adding to an Array
anyArray.append("foo") // Adding to an Array
anyArray.append(1) // ["foo", 1]
anyArray.append(1) // ["foo", 1]
anyArray.removeAtIndex(1) // Remove object
anyArray.removeAtIndex(1) // Remove object
anyArray[0] = "bar" // ["bar"]</lang>
anyArray[0] = "bar" // ["bar"]</syntaxhighlight>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang=tailspin>
// arrays are created as literals, by simply listing elements, or by a generator expression, or a combination.
// 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];
def a: [1, 2, 3..7:2, 11];
Line 8,016: Line 8,016:
// A mutable array can be appended
// A mutable array can be appended
5 -> \(@: [1,2]; $ -> ..|@: $; $@ ! \) -> !OUT::write
5 -> \(@: [1,2]; $ -> ..|@: $; $@ ! \) -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 8,028: Line 8,028:
=={{header|Tcl}}==
=={{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.)
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.)
<lang tcl>set ary {}
<syntaxhighlight lang=tcl>set ary {}


lappend ary 1
lappend ary 1
Line 8,035: Line 8,035:
lset ary 0 2
lset ary 0 2


puts [lindex $ary 0]</lang>
puts [lindex $ary 0]</syntaxhighlight>
Note also that serialization is automatic on treating as a string:
Note also that serialization is automatic on treating as a string:
<lang tcl>puts $ary; # Print the whole array</lang>
<syntaxhighlight lang=tcl>puts $ary; # Print the whole array</syntaxhighlight>


=={{header|Tern}}==
=={{header|Tern}}==
Arrays and lists are synonymous in Tern.
Arrays and lists are synonymous in Tern.
<lang tern>let list = [1, 22, 3, 24, 35, 6];
<syntaxhighlight lang=tern>let list = [1, 22, 3, 24, 35, 6];


for(i in list) {
for(i in list) {
println(i);
println(i);
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 8,060: Line 8,060:
<br>'''List'''<br>
<br>'''List'''<br>
One dimensional arrays are lists, they can be set as a whole with the syntax:
One dimensional arrays are lists, they can be set as a whole with the syntax:
<lang ti83b>{1,2,3,4,5}→L1</lang>
<syntaxhighlight lang=ti83b>{1,2,3,4,5}→L1</syntaxhighlight>
using only numerical values separated by commas and enclosed by curly braces.<br>
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
Lists can be accessed as a whole using L1-L6 or a custom list name
Line 8,066: Line 8,066:
You can also retrieve a single value from a list using the name of the list and
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.
the position of the value, which starts at 1 on the left.
<lang ti83b>{1,2,3,4,5}→L1
<syntaxhighlight lang=ti83b>{1,2,3,4,5}→L1
Disp L1(3)
Disp L1(3)
0→L1(4)</lang>
0→L1(4)</syntaxhighlight>
This would return 3 and set the fourth list element to 0.
This would return 3 and set the fourth list element to 0.
<br>You can dynamically define or delete lists by:
<br>You can dynamically define or delete lists by:
<lang ti83b>20→dim(L1)
<syntaxhighlight lang=ti83b>20→dim(L1)
DelVar L1
DelVar L1
5→dim(∟MYLIST)
5→dim(∟MYLIST)
DelVar ∟MYLIST</lang>
DelVar ∟MYLIST</syntaxhighlight>
'''Matrix'''<br>
'''Matrix'''<br>
Two dimensional arrays are matrices. Similar, set them and retrieve numbers using the syntax:
Two dimensional arrays are matrices. Similar, set them and retrieve numbers using the syntax:
<lang ti83b>[[11,21,31,41][12,22,32,42][13,23,33,43]]→[A]
<syntaxhighlight lang=ti83b>[[11,21,31,41][12,22,32,42][13,23,33,43]]→[A]
Disp [A](1,3)
Disp [A](1,3)
0→[A](4,2)</lang>
0→[A](4,2)</syntaxhighlight>
This would return 13 and set the element (4,2) to 0.
This would return 13 and set the element (4,2) to 0.
<br>You can dynamically define or delete matrices by:
<br>You can dynamically define or delete matrices by:
<lang ti83b>{5,5}→dim([A])
<syntaxhighlight lang=ti83b>{5,5}→dim([A])
DelVar [A]</lang>
DelVar [A]</syntaxhighlight>


=={{header|TorqueScript}}==
=={{header|TorqueScript}}==
Arrays in TorqueScript:
Arrays in TorqueScript:


<lang TorqueScript>
<syntaxhighlight lang=TorqueScript>
$array[0] = "hi";
$array[0] = "hi";
$array[1] = "hello";
$array[1] = "hello";


for(%i=0;%i<2;%i++)
for(%i=0;%i<2;%i++)
echo($array[%i]);</lang>
echo($array[%i]);</syntaxhighlight>


=> hi
=> hi
Line 8,099: Line 8,099:
=> hello
=> hello


<lang TorqueScript>
<syntaxhighlight lang=TorqueScript>
$array["Greet",0] = "hi";
$array["Greet",0] = "hi";
$array["Greet",1] = "hello";
$array["Greet",1] = "hello";


for(%i=0;%i<2;%i++)
for(%i=0;%i<2;%i++)
echo($array["Greet",%i]);</lang>
echo($array["Greet",%i]);</syntaxhighlight>


=> hi
=> hi
Line 8,117: Line 8,117:
Vectors can be created as empty containers, or they can be initialized with some values at the time of creation.
Vectors can be created as empty containers, or they can be initialized with some values at the time of creation.


<lang Scheme>module1 : {
<syntaxhighlight lang=Scheme>module1 : {
v1: Vector<Int>(),
v1: Vector<Int>(),
v2: Vector<String>(),
v2: Vector<String>(),
Line 8,125: Line 8,125:
v5: [1.0, 2.5, 8.6], // Vector<Double>
v5: [1.0, 2.5, 8.6], // Vector<Double>
v6: ["one","two","three"] // Vector<String>
v6: ["one","two","three"] // Vector<String>
}</lang>
}</syntaxhighlight>


Individual elements in a vector can be read, appended, and deleted.
Individual elements in a vector can be read, appended, and deleted.


<lang Scheme>(with v [1,2,3]
<syntaxhighlight lang=Scheme>(with v [1,2,3]
(textout (get v 1)) // <= 2
(textout (get v 1)) // <= 2
(erase v 1)
(erase v 1)
Line 8,135: Line 8,135:
(append v 7)
(append v 7)
(textout v) // <= [1, 3, 7]
(textout v) // <= [1, 3, 7]
)</lang>
)</syntaxhighlight>


All standard container operations can be applied to vectors:
All standard container operations can be applied to vectors:


<lang Scheme>(with v [3,1,5,2,4]
<syntaxhighlight lang=Scheme>(with v [3,1,5,2,4]
(textout (reverse v)) // <= [4, 2, 5, 1, 3]
(textout (reverse v)) // <= [4, 2, 5, 1, 3]
(textout (sort v)) // <= [1, 2, 3, 4, 5]
(textout (sort v)) // <= [1, 2, 3, 4, 5]
(textout (shuffle v)) // <= [5, 3, 4, 1, 2]
(textout (shuffle v)) // <= [5, 3, 4, 1, 2]
)</lang>
)</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
Line 8,210: Line 8,210:
A complete program which turns comma-separated into tab-separated,
A complete program which turns comma-separated into tab-separated,
where the first and last field from each line are exchanged:
where the first and last field from each line are exchanged:
<lang txr>@(collect)
<syntaxhighlight lang=txr>@(collect)
@line
@line
@(bind f @(split-str line ","))
@(bind f @(split-str line ","))
Line 8,216: Line 8,216:
@{f[-1]}@\t@{f[1..-1] "\t"}@\t@{f[0]}
@{f[-1]}@\t@{f[1..-1] "\t"}@\t@{f[0]}
@(end)
@(end)
@(end)</lang>
@(end)</syntaxhighlight>


====Other Kinds of Objects====
====Other Kinds of Objects====
Line 8,226: Line 8,226:
=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
uBasic/4tH has only one single, global array of 256 integers. Since it's fixed, it can't be declared.
uBasic/4tH has only one single, global array of 256 integers. Since it's fixed, it can't be declared.
<lang>Let @(0) = 5 : Print @(0)</lang>
<lang>Let @(0) = 5 : Print @(0)</syntaxhighlight>


=={{header|Unicon}}==
=={{header|Unicon}}==
Unicon's arrays are provided by the list type, which is a hybrid list/array type.
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).
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).
<lang>L := list(100); L[12] := 7; a := array(100, 0.0); a[3] +:= a[1]+a[2]</lang>
<lang>L := list(100); L[12] := 7; a := array(100, 0.0); a[3] +:= a[1]+a[2]</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Line 8,241: Line 8,241:


To create an array:
To create an array:
<lang bash>alist=( item1 item2 item3 ) # creates a 3 item array called "alist"
<syntaxhighlight lang=bash>alist=( item1 item2 item3 ) # creates a 3 item array called "alist"
declare -a list2 # declare an empty list called "list2"
declare -a list2 # declare an empty list called "list2"
declare -a list3[0] # empty list called "list3"; the subscript is ignored
declare -a list3[0] # empty list called "list3"; the subscript is ignored


# create a 4 item list, with a specific order
# create a 4 item list, with a specific order
list5=([3]=apple [2]=cherry [1]=banana [0]=strawberry)</lang>
list5=([3]=apple [2]=cherry [1]=banana [0]=strawberry)</syntaxhighlight>
To obtain the number of items in an array:
To obtain the number of items in an array:
<lang bash>count=${#alist[*]}
<syntaxhighlight lang=bash>count=${#alist[*]}
echo "The number of items in alist is ${#alist[*]}"</lang>
echo "The number of items in alist is ${#alist[*]}"</syntaxhighlight>
To iterate up over the items in the array:
To iterate up over the items in the array:
<lang bash>x=0
<syntaxhighlight lang=bash>x=0
while [[ $x < ${#alist[*]} ]]; do
while [[ $x < ${#alist[*]} ]]; do
echo "Item $x = ${alist[$x]}"
echo "Item $x = ${alist[$x]}"
: $((x++))
: $((x++))
done</lang>
done</syntaxhighlight>
To iterate down over theitems in an array:
To iterate down over theitems in an array:
<lang bash>x=${#alist[*]} # start with the number of items in the array
<syntaxhighlight lang=bash>x=${#alist[*]} # start with the number of items in the array
while [[ $x > 0 ]]; do # while there are items left
while [[ $x > 0 ]]; do # while there are items left
: $((x--)) # decrement first, because indexing is zero-based
: $((x--)) # decrement first, because indexing is zero-based
echo "Item $x = ${alist[$x]}" # show the current item
echo "Item $x = ${alist[$x]}" # show the current item
done</lang>
done</syntaxhighlight>
To append to an array, use the current number of items in the array as the next index:
To append to an array, use the current number of items in the array as the next index:
<lang bash>alist[${#alist[*]}]=new_item</lang>
<syntaxhighlight lang=bash>alist[${#alist[*]}]=new_item</syntaxhighlight>
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:
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:
<lang bash># shell function to append values to an array
<syntaxhighlight lang=bash># shell function to append values to an array
# push LIST VALUES ...
# push LIST VALUES ...
push() {
push() {
Line 8,274: Line 8,274:


push alist "one thing to add"
push alist "one thing to add"
push alist many words to add</lang>
push alist many words to add</syntaxhighlight>
To delete a single array item, the first item:
To delete a single array item, the first item:
<lang bash>unset alist[0]</lang>
<syntaxhighlight lang=bash>unset alist[0]</syntaxhighlight>
To delete and return the last item in an array (e.g., "pop" function):
To delete and return the last item in an array (e.g., "pop" function):
<lang bash># pop ARRAY -- pop the last item on ARRAY and output it
<syntaxhighlight lang=bash># pop ARRAY -- pop the last item on ARRAY and output it


pop() {
pop() {
Line 8,300: Line 8,300:
c
c
pop alist
pop alist
No items in alist</lang>
No items in alist</syntaxhighlight>
To delete all the items in an array:
To delete all the items in an array:
<lang bash>unset alist[*]</lang>
<syntaxhighlight lang=bash>unset alist[*]</syntaxhighlight>
To delete the array itself (and all items in it, of course):
To delete the array itself (and all items in it, of course):
<lang bash>unset alist</lang>
<syntaxhighlight lang=bash>unset alist</syntaxhighlight>


=={{header|உயிர்/Uyir}}==
=={{header|உயிர்/Uyir}}==
<lang உயிர்/Uyir>
<syntaxhighlight lang=உயிர்/Uyir>
இருபரிமாணணி வகை எண் அணி {3, 3};
இருபரிமாணணி வகை எண் அணி {3, 3};
இருபரிமாணணி2 வகை எண் அணி {3} அணி {3};
இருபரிமாணணி2 வகை எண் அணி {3} அணி {3};
Line 8,317: Line 8,317:
செவ்வகணி = அணி { அணி {10, 22, 43}, அணி {31, 58, 192}, அணி {46, 73, 65} };
செவ்வகணி = அணி { அணி {10, 22, 43}, அணி {31, 58, 192}, அணி {46, 73, 65} };
முக்கோண்ணி = அணி { அணி {1}, அணி {2, 3}, அணி {4, 5, 6}, அணி {7, 8, 9, 1, 2} };
முக்கோண்ணி = அணி { அணி {1}, அணி {2, 3}, அணி {4, 5, 6}, அணி {7, 8, 9, 1, 2} };
</syntaxhighlight>
</lang>


=={{header|Vala}}==
=={{header|Vala}}==
Non-dynamic arrays:
Non-dynamic arrays:
<lang vala>
<syntaxhighlight lang=vala>
int[] array = new int[10];
int[] array = new int[10];


Line 8,328: Line 8,328:


stdout.printf("%d\n", array[0]);
stdout.printf("%d\n", array[0]);
</syntaxhighlight>
</lang>


{{libheader|Gee}}
{{libheader|Gee}}
Dynamic Arrays with Gee:
Dynamic Arrays with Gee:
<lang vala>
<syntaxhighlight lang=vala>
var array = new ArrayList<int> ();
var array = new ArrayList<int> ();


Line 8,341: Line 8,341:


stdout.printf("%d\n", array[0]);
stdout.printf("%d\n", array[0]);
</syntaxhighlight>
</lang>


=={{header|VBA}}==
=={{header|VBA}}==
The Option Base statement is used at the module level to declare the default lower bound for array subscripts.
The Option Base statement is used at the module level to declare the default lower bound for array subscripts.
<lang vb>Option Base {0|1} </lang>
<syntaxhighlight lang=vb>Option Base {0|1} </syntaxhighlight>
<lang vb>Sub matrix()
<syntaxhighlight lang=vb>Sub matrix()
'create an array,
'create an array,
Dim a(3) As Integer
Dim a(3) As Integer
Line 8,374: Line 8,374:
Debug.Print d(i)
Debug.Print d(i)
Next i
Next i
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 4 9 1 4 9 1 4 9 16 </pre>
<pre> 1 4 9 1 4 9 1 4 9 16 </pre>


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang vb>'Arrays - VBScript - 08/02/2021
<syntaxhighlight lang=vb>'Arrays - VBScript - 08/02/2021


'create a static array
'create a static array
Line 8,423: Line 8,423:
'Multi-Dimensional arrays
'Multi-Dimensional arrays
'The following creates a 5x4 matrix
'The following creates a 5x4 matrix
Dim mat(4,3) </lang>
Dim mat(4,3) </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 8,434: Line 8,434:


=={{header|VHDL}}==
=={{header|VHDL}}==
<lang VHDL>
<syntaxhighlight lang=VHDL>
entity Array_Test is
entity Array_Test is
end entity Array_Test;
end entity Array_Test;
Line 8,492: Line 8,492:


end architecture Example;
end architecture Example;
</syntaxhighlight>
</lang>


=={{header|Vim Script}}==
=={{header|Vim Script}}==
Lists can be used for dynamic arrays. Indexing starts at 0.
Lists can be used for dynamic arrays. Indexing starts at 0.
<lang vim>" Creating a dynamic array with some initial values
<syntaxhighlight lang=vim>" Creating a dynamic array with some initial values
let array = [3, 4]
let array = [3, 4]


Line 8,514: Line 8,514:
call insert(array, 3, 2)
call insert(array, 3, 2)


echo array</lang>
echo array</syntaxhighlight>


{{Out}}
{{Out}}
Line 8,520: Line 8,520:


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>'Example of array of 10 int types:
<syntaxhighlight lang=vbnet>'Example of array of 10 int types:
Dim numbers As Integer() = New Integer(9) {}
Dim numbers As Integer() = New Integer(9) {}
'Example of array of 4 string types:
'Example of array of 4 string types:
Line 8,550: Line 8,550:
list.Add(3)
list.Add(3)
list(0) = 2
list(0) = 2
Console.WriteLine(list(0))</lang>
Console.WriteLine(list(0))</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang go>// Arrays, in V
<syntaxhighlight lang=go>// Arrays, in V
// Tectonics: v run arrays.v
// Tectonics: v run arrays.v
module main
module main
Line 8,606: Line 8,606:
println("array4: $array4")
println("array4: $array4")
println("array5: $array5")
println("array5: $array5")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 8,627: Line 8,627:


=={{header|Wee Basic}}==
=={{header|Wee Basic}}==
<lang Wee Basic>dim array$(2)
<syntaxhighlight lang=Wee Basic>dim array$(2)
let array$(1)="Hello!"
let array$(1)="Hello!"
let array$(2)="Goodbye!"
let array$(2)="Goodbye!"
print 1 array$(1)</lang>
print 1 array$(1)</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var arr = []
<syntaxhighlight lang=ecmascript>var arr = []
arr.add(1)
arr.add(1)
arr.add(2)
arr.add(2)
Line 8,646: Line 8,646:
arr[-1] = 0
arr[-1] = 0
arr.insert(-1, 0) // [0, 0, 1, 0, 0]
arr.insert(-1, 0) // [0, 0, 1, 0, 0]
arr.removeAt(2) // [0, 0, 0, 0]</lang>
arr.removeAt(2) // [0, 0, 0, 0]</syntaxhighlight>


=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
<lang asm>
<syntaxhighlight lang=asm>
section .text
section .text
global _start
global _start
Line 8,728: Line 8,728:
resd 1
resd 1
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.
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".
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".
Line 8,734: Line 8,734:
=={{header|XBS}}==
=={{header|XBS}}==
Arrays in [[XBS]] are very similar to [[JavaScript]].
Arrays in [[XBS]] are very similar to [[JavaScript]].
<lang XBS>set Array = ["Hello","World"];
<syntaxhighlight lang=XBS>set Array = ["Hello","World"];
log(Array[0]);
log(Array[0]);
Array.push("Test");
Array.push("Test");
log(?Array);
log(?Array);
log(Array[?Array-1]);</lang>
log(Array[?Array-1]);</syntaxhighlight>


=={{header|XLISP}}==
=={{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):
Like some other languages, XLISP refers to one-dimensional arrays as vectors. Examples of vector and array syntax, from a REPL (interactive session):
<lang scheme>[1] (define a (make-vector 10)) ; vector of 10 elements initialized to the empty list
<syntaxhighlight lang=scheme>[1] (define a (make-vector 10)) ; vector of 10 elements initialized to the empty list


A
A
Line 8,765: Line 8,765:
[8] (array-ref d 1 2 3) ; and get the value of d_1,2,3
[8] (array-ref d 1 2 3) ; and get the value of d_1,2,3


10</lang>
10</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang=XPL0>include c:\cxpl\codes;
char A(10); \creates a static array of 10 bytes, pointed to by "A"
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
char B; \declares a variable for a pointer to a dynamic array
Line 8,775: Line 8,775:
B(7):= 28;
B(7):= 28;
IntOut(0, A(3)+B(7)); \displays 42
IntOut(0, A(3)+B(7)); \displays 42
]</lang>
]</syntaxhighlight>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>dim a(10) // create a numeric array with 11 elements, from 0 to 10
<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)
// 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
print arraysize(a(), 1) // this function return the element's higher number of an array
Line 8,805: Line 8,805:
print arraysize(a$(), 1)
print arraysize(a$(), 1)


print a$(5) // show the content of an element of the array. Now is empty</lang>
print a$(5) // show the content of an element of the array. Now is empty</syntaxhighlight>


=={{header|Z80 Assembly}}==
=={{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.
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.
<lang z80>Array: ;an array located in RAM. Its values can be updated freely.
<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
byte 0,0,0,0,0
byte 0,0,0,0,0
byte 0,0,0,0,0</lang>
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>
<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>
Line 8,821: Line 8,821:


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:
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:
<lang z80>Array:
<syntaxhighlight lang=z80>Array:
byte 0,0,0,0,0
byte 0,0,0,0,0
byte 0,0,20,0,0
byte 0,0,20,0,0
byte 0,0,0,0,0
byte 0,0,0,0,0
byte 0,0,0,0,0</lang>
byte 0,0,0,0,0</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.
<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 hl,Array ;hl points to the 0th element of row 0.
Line 8,839: Line 8,839:
ld a,20 ;get the value 20 which we want to store here
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
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.)</lang>
; 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.
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.
Line 8,848: Line 8,848:
In the example below, we wish to load the 13th (zero-indexed) element from the array MyTable.
In the example below, we wish to load the 13th (zero-indexed) element from the array MyTable.


<lang z80>LD H,>MyTable ;works out to be LD h,4 thanks to our alignment below.
<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
;>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 L,13 ;this was a lot faster than doing LD HL,&0400 and adding the desired index later.
Line 8,860: Line 8,860:
byte 3,6,9,12,15
byte 3,6,9,12,15
byte 4,8,12,16,20
byte 4,8,12,16,20
byte 5,10,15,20,25</lang>
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.
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:
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:
<lang z80>org &0400
<syntaxhighlight lang=z80>org &0400
word &8000,&8327,&864e,&8973,&8c98,&8fba,&92da,&95f7
word &8000,&8327,&864e,&8973,&8c98,&8fba,&92da,&95f7
word &9911,&9c27,&9f38,&a244,&a54c,&a84d,&ab48,&ae3c
word &9911,&9c27,&9f38,&a244,&a54c,&a84d,&ab48,&ae3c
word &b12a,&b40f,&b6ed,&b9c2,&bc8e,&bf50,&c209,&c4b7
word &b12a,&b40f,&b6ed,&b9c2,&bc8e,&bf50,&c209,&c4b7
word &c75b,&c9f4,&cc81,&cf02,&d177,&d3e0,&d63b,&d889</lang>
word &c75b,&c9f4,&cc81,&cf02,&d177,&d3e0,&d63b,&d889</syntaxhighlight>


You can instead store it like this:
You can instead store it like this:
<lang z80>org &0400
<syntaxhighlight lang=z80>org &0400
byte <&8000,<&8327,<&864e,<&8973,<&8c98,<&8fba,<&92da,<&95f7
byte <&8000,<&8327,<&864e,<&8973,<&8c98,<&8fba,<&92da,<&95f7
byte <&9911,<&9c27,<&9f38,<&a244,<&a54c,<&a84d,<&ab48,<&ae3c
byte <&9911,<&9c27,<&9f38,<&a244,<&a54c,<&a84d,<&ab48,<&ae3c
Line 8,881: Line 8,881:
byte >&9911,>&9c27,>&9f38,>&a244,>&a54c,>&a84d,>&ab48,>&ae3c
byte >&9911,>&9c27,>&9f38,>&a244,>&a54c,>&a84d,>&ab48,>&ae3c
byte >&b12a,>&b40f,>&b6ed,>&b9c2,>&bc8e,>&bf50,>&c209,>&c4b7
byte >&b12a,>&b40f,>&b6ed,>&b9c2,>&bc8e,>&bf50,>&c209,>&c4b7
byte >&c75b,>&c9f4,>&cc81,>&cf02,>&d177,>&d3e0,>&d63b,>&d889</lang>
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.
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".
So let's say we want to read the last entry in "the table".
<lang z80>LD h,&04 ;load high byte of address &0400
<syntaxhighlight lang=z80>LD h,&04 ;load high byte of address &0400
LD L,&1F ;desired index
LD L,&1F ;desired index
ld a,(hl)
ld a,(hl)
Line 8,892: Line 8,892:
inc h ;LD h,&05. We can keep L the same since the index is the same.
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!
;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.</lang>
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.
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.
Line 8,898: Line 8,898:
=={{header|zkl}}==
=={{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.
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.
<lang zkl>var array=List(); // array of size 0
<syntaxhighlight 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=(0).pump(10,List().write,5).copy(); // [writable] array of size 10 filled with 5
array[3]=4;
array[3]=4;
array[3] //-->4
array[3] //-->4
array+9; //append a 9 to the end, same as array.append(9)</lang>
array+9; //append a 9 to the end, same as array.append(9)</syntaxhighlight>


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang pascal>
<syntaxhighlight lang=pascal>
var
var
a: array 10 of integer;
a: array 10 of integer;
da: array * of cardinal;
da: array * of cardinal;
</syntaxhighlight>
</lang>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 DIM a(5)
<syntaxhighlight lang=zxbasic>10 DIM a(5)
20 LET a(2)=128
20 LET a(2)=128
30 PRINT a(2)</lang>
30 PRINT a(2)</syntaxhighlight>


{{omit from|X86-64 Assembly|the same as X86, Just R based registers(eax,rax)}}
{{omit from|X86-64 Assembly|the same as X86, Just R based registers(eax,rax)}}