Arrays: Difference between revisions

1,096 bytes added ,  1 year ago
m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1:
{{task|Basic language learning}} [[Category:Simple]]
{{task|Basic language learning}}
 
This task is about arrays.
Line 31:
{{trans|Python}}
 
<syntaxhighlight lang="11l">[Int] array
array.append(1)
array.append(3)
Line 55:
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Arrays 04/09/2015
ARRAYS PROLOG
* we use TA array with 1 as origin. So TA(1) to TA(20)
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.
 
<syntaxhighlight lang="6502asm">Array:
db 5,10,15,20,25,30,35,40,45,50</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="c"> char foo()
{
char array[5] = {3,6,9,12,15};
Line 105:
 
would (theoretically) compile to the following in 6502 Assembly:
<syntaxhighlight lang="6502asm">
foo:
LDX #2 ;load the desired index
Line 116:
One important thing to note is a hardware bug involving <code>LDA $??,x</code>. If the sum of $?? and x would exceed 255, instead of continuing past $100, the CPU will actually wrap around back to $00. This does not happen with absolute addressing modes or indexed indirect with Y. Here's an example:
 
<syntaxhighlight lang="6502asm">LDX #$80
LDA $80,x ;evaluates to LDA $00
LDA $0480,x ;evaluates to LDA $0500</syntaxhighlight>
Line 124:
===Arrays of 16-Bit Data===
You can have arrays of 16-bit data as well as 8-bit ones. There are a few ways to do this, and we'll go over the "naive" way first:
<syntaxhighlight lang="6502">wordArray:
dw $ABCD,$BEEF,$CAFE,$DADA</syntaxhighlight>
 
The 6502 is little-endian, so the above would be exactly the same as the following:
<syntaxhighlight lang="6502">wordArray:
db $CD,$AB,$EF,$BE,$FE,$CA,$DA,$DA</syntaxhighlight>
 
To properly index a 16-bit array that's formatted as in the above example, you'll need to double your index. In this example, we'll be loading the offset of <code>$BEEF</code>:
<syntaxhighlight lang="6502">LDX #2 ;load the 1st (zero-indexed) WORD from the array (which is why this is 2 not 1)
LDA wordArray,X ;evaluates to LDA #$EF
STA $00 ;store in a zero page temporary variable
Line 143:
 
However, if you split the word table into two byte tables, you can actually get more bang for your buck, and it takes the same amount of memory no matter which way you store the data.
<syntaxhighlight lang="6502asm">wordArray_Lo:
db $CD,$EF,$FE,$DA
 
Line 151:
If both wordArray_Lo and wordArray_Hi were 256 bytes each, you'd be able to index both of them no problem, where you wouldn't be able to do that if it were one array. Let's try loading <code>$BEEF</code> again:
 
<syntaxhighlight lang="6502">LDX #1 ;with split arrays we DON'T need to double our index.
LDA wordArray_Lo,x ;evaluates to LDA #$EF
STA $00
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.
In the first section I had this example of an array:
<syntaxhighlight lang="6502asm">Array:
db 5,10,15,20,25,30,35,40,45,50</syntaxhighlight>
 
In the eyes of the CPU, this is the same as ANY of the following:
<syntaxhighlight lang="6502asm">Array:
db 5
db 10
Line 178:
db 50</syntaxhighlight>
 
<syntaxhighlight lang="6502asm">Array:
db 5,10
db 15,20
Line 187:
or any other way to write it you can imagine. All that matters is the order of the bytes in the array - as long as that is the same you can write it however you want. It's best to write it in the way it's meant to be interpreted, however. But in order to explain that to the computer you'll need a little bit of finesse. Let's pretend that the "correct" interpretation is this 5 by 2 array:
 
<syntaxhighlight lang="6502asm">Array:
db 5,10
db 15,20
Line 195:
 
For this example, we want row 3 and column 1 (zero-indexed for both) which means we want to load 40.
<syntaxhighlight lang="6502">
LDA #3 ;desired row
ASL A ;Times 2 bytes per row (if the array's row size wasn't a multiple of 2 we'd need to actually do multiplication)
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.
 
<syntaxhighlight lang="68000devpac">MOVE.L #$00100000,A0 ;define an array at memory address $100000</syntaxhighlight>
 
Defining an array in ROM (or RAM if you're making a program that is loaded from disk) is very simple:
<syntaxhighlight lang="68000devpac">;8-bit data
MyArray:
DC.B 1,2,3,4,5
Line 235:
 
Strings are also arrays and most assemblers accept single or double quotes. The following are equivalent:
<syntaxhighlight lang="68000devpac">MyString:
DC.B "Hello World",0
even
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.
 
<syntaxhighlight lang="68000devpac">myArray equ $240000
 
LEA myArray,A0 ;load the base address of the array into A0
Line 264:
 
This is the equivalent of the [[C]] code:
<syntaxhighlight lang=C"c">int myArray[];
myArray[3] = 23;</syntaxhighlight>
 
Loading an element is very similar to storing it.
 
<syntaxhighlight lang="68000devpac">myArray equ $240000
 
;load element 4
Line 280:
Inserting an element at a desired position is a bit more tricky. First of all, an array has no "end" in hardware. So how do you know where to stop? For this example, assume this array is currently contains 6 total elements (0,1,2,3,4,5) and we want to extend it.
 
<syntaxhighlight lang="68000devpac">myArray equ $240000
 
;insert a new element into the 2nd slot and push everything behind it back.
Line 318:
<li>In external RAM - element retrieval/altering is most efficiently done sequentially, necessary for large arrays or peripherals</ul>
Dynamic (resizable) arrays are possible to implement, but are error-prone since bounds checking must be done by the programmer.
<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)
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 414:
 
Arrays are declared using JSON syntax, and are dynamic (but not sparse)
<syntaxhighlight lang="forth">
[ 1 , 2 ,3 ] \ an array holding three numbers
1 a:@ \ this will be '2', the element at index 1
Line 433:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program areaString64.s */
Line 583:
=={{header|ABAP}}==
There are no real arrays in ABAP but a construct called internal tables.
<syntaxhighlight lang=ABAP"abap">
TYPES: tty_int TYPE STANDARD TABLE OF i
WITH NON-UNIQUE DEFAULT KEY.
Line 610:
 
=={{header|ACL2}}==
<syntaxhighlight lang=Lisp"lisp">;; Create an array and store it in array-example
(assign array-example
(compress1 'array-example
Line 627:
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">PROC Main()
BYTE i
 
Line 710:
 
=={{header|ActionScript}}==
<syntaxhighlight lang=ActionScript"actionscript">//creates an array of length 10
var array1:Array = new Array(10);
//creates an array with the values 1, 2
Line 728:
 
=={{header|Ada}}==
<syntaxhighlight lang=Ada"ada">procedure Array_Test is
 
A, B : array (1..20) of Integer;
Line 775:
=={{header|Aikido}}==
Aikido arrays (or vectors) are dynamic and not fixed in size. They can hold a set of any defined value.
<syntaxhighlight lang="aikido">
var arr1 = [1,2,3,4] // initialize with array literal
var arr2 = new [10] // empty array of 10 elements (each element has value none)
Line 799:
=={{header|Aime}}==
The aime ''list'' is a heterogeneous, dynamic sequence. No special creation procedure, only declaration is needed:
<syntaxhighlight lang="aime">list l;</syntaxhighlight>
Values (numbers, strings, collections, functions, etc) can be added in a type generic fashion:
<syntaxhighlight lang="aime">l_append(l, 3);
l_append(l, "arrays");
l_append(l, pow);</syntaxhighlight>
The insertion position can be specified:
<syntaxhighlight lang="aime">l_push(l, 3, .5);
l_push(l, 4, __type(l));</syntaxhighlight>
More aptly, values (of selected types) can be inserted in a type specific fashion:
<syntaxhighlight lang="aime">l_p_integer(l, 5, -1024);
l_p_real(l, 6, 88);</syntaxhighlight>
Similarly, values can be retrieved in a type generic fashion:
<syntaxhighlight lang="aime">l_query(l, 5);</syntaxhighlight>
or is type specific fashion:
<syntaxhighlight lang="aime">l_q_real(l, 6);
l_q_text(l, 1);</syntaxhighlight>
 
=={{header|ALGOL 60}}==
{{trans|Simula}}
<syntaxhighlight lang="algol60">begin
comment arrays - Algol 60;
 
Line 858:
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">PROC array_test = VOID:
(
[1:20]INT a;
Line 882:
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% declare an array %
integer array a ( 1 :: 10 );
Line 902:
 
=={{header|AmigaE}}==
<syntaxhighlight lang="amigae">DEF ai[100] : ARRAY OF CHAR, -> static
da: PTR TO CHAR,
la: PTR TO CHAR
Line 921:
 
=={{header|AntLang}}==
<syntaxhighlight lang=AntLang"antlang">/ Create an immutable sequence (array)
arr: <1;2;3>
 
Line 936:
 
=={{header|Apex}}==
<syntaxhighlight lang="apex">Integer[] array = new Integer[10]; // optionally, append a braced list of Integers like "{1, 2, 3}"
array[0] = 42;
System.debug(array[0]); // Prints 42</syntaxhighlight>
Dynamic arrays can be made using <code>List</code>s. <code>List</code>s and array can be used interchangeably in Apex, e.g. any method that accepts a <code>List<String></code> will also accept a <code>String[]</code>
<syntaxhighlight lang="apex">List <Integer> aList = new List <Integer>(); // optionally add an initial size as an argument
aList.add(5);// appends to the end of the list
aList.add(1, 6);// assigns the element at index 1
Line 947:
=={{header|APL}}==
Arrays in APL are one dimensional matrices, defined by seperating variables with spaces. For example:
<syntaxhighlight lang="apl">+/ 1 2 3</syntaxhighlight>
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}}==
Line 958:
=={{header|AppleScript}}==
AppleScript arrays are called lists:
<syntaxhighlight lang="applescript"> set empty to {}
set ints to {1, 2, 3}</syntaxhighlight>
 
Lists can contain any objects including other lists:
<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:
 
<syntaxhighlight lang="applescript">set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
set beginning of any to false
set end of any to Wednesday
Line 974:
Or a new list containing the items can be created through concatenation:
 
<syntaxhighlight lang="applescript">set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
set any to false & any & Wednesday
--> {false, 1, "foo", 2.57, missing value, {1, 2, 3}, Wednesday}</syntaxhighlight>
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:
 
<syntaxhighlight lang="applescript">set any to {1, "foo", 2.57, missing value, {1, 2, 3}}
item -1 of any --> {1, 2, 3}
items 1 thru 3 of any --> {1, "foo", 2.57}</syntaxhighlight>
Line 990:
If required, items can be specified by class instead of the generic 'item' …
 
<syntaxhighlight lang="applescript">set any to {false, 1, "foo", 2.57, missing value, {1, 2, 3}, Wednesday}
number 2 of any -- 2.57 (ie. the second number in the list)</syntaxhighlight>
 
… and some fairly complex range specifiers are possible:
 
<syntaxhighlight lang="applescript">set any to {false, 1, "foo", 2.57, missing value, 5, 4, 12.0, 38, {1, 2, 3}, 7, Wednesday}
integers from text 1 to list 1 of any --> {5, 4, 38}</syntaxhighlight>
 
The length of a list can be determined in any of three ways, although only the first two below are now recommended:
 
<syntaxhighlight lang="applescript">count any -- Command.
length of any -- Property.
number of any -- Property.</syntaxhighlight>
Line 1,006:
The number of items of a specific class can also be obtained:
 
<syntaxhighlight lang="applescript">count any's reals
length of any's integers</syntaxhighlight>
 
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:
 
<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.
 
Line 1,056:
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
<syntaxhighlight lang=Argile"argile">use std, array
(:::::::::::::::::
Line 1,089:
 
{{works with|Argile|1.1.0}}
<syntaxhighlight lang=Argile"argile">use std, array
let x = @["foo" "bar" "123"]
print x[2]
Line 1,096:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
/* ARM assembly Raspberry PI */
/* program areaString.s */
Line 1,287:
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">; empty array
arrA: []
Line 1,313:
{{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.
<syntaxhighlight lang=AHK"ahk">myArray := Object() ; could use JSON-syntax sugar like {key: value}
myArray[1] := "foo"
myArray[2] := "bar"
Line 1,323:
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.
<syntaxhighlight lang=AutoHotkey"autohotkey">arrayX0 = 4 ; length
arrayX1 = first
arrayX2 = second
Line 1,337:
=={{header|AutoIt}}==
Create an userdefined array.
<syntaxhighlight lang=AutoIt"autoit">
#include <Array.au3> ;Include extended Array functions (_ArrayDisplay)
 
Line 1,356:
=={{header|Avail}}==
Avail supports tuples as its primary ordered collection.
<syntaxhighlight lang=Avail"avail">tup ::= <"aardvark", "cat", "dog">;</syntaxhighlight>
 
Tuple indices (officially referred to as "subscripts") are 1-based. One can provide an alternative if there is no element at a subscript using an else clause.
<syntaxhighlight lang=Avail"avail"><"pinch", "tsp", "tbsp", "cup">[4] \\ "cup"
<3, 2, 1>[100] else [0]</syntaxhighlight>
 
Tuples are immutable, however one can quickly create a new tuple with a specified element replaced.
<syntaxhighlight lang=Avail"avail"><"sheep", "wheat", "wood", "brick", "stone">[5] → "ore"</syntaxhighlight>
 
=={{header|AWK}}==
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.
 
<syntaxhighlight lang="awk">BEGIN {
# to make an array, assign elements to it
array[1] = "first"
Line 1,425:
 
=={{header|Axe}}==
<syntaxhighlight lang="axe">1→{L₁}
2→{L₁+1}
3→{L₁+2}
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:
 
<syntaxhighlight lang="babel">[1 2 3]</syntaxhighlight>
 
<syntaxhighlight lang="babel">[ptr 1 2 3]</syntaxhighlight>
 
 
===Get a single array element===
 
<syntaxhighlight lang="babel">[1 2 3] 1 th ;</syntaxhighlight>
 
{{Out}}
Line 1,456:
Changing a value-array element:
 
<syntaxhighlight lang="babel">[1 2 3] dup 1 7 set ;
</syntaxhighlight>
 
Line 1,464:
Changing a pointer-array element:
 
<syntaxhighlight lang="babel">[ptr 1 2 3] dup 1 [ptr 7] set ;</syntaxhighlight>
 
{{Out}}
Line 1,471:
===Select a range of an array===
 
<syntaxhighlight lang="babel">[ptr 1 2 3 4 5 6] 1 3 slice ;</syntaxhighlight>
 
{{Out}}
Line 1,480:
You can concatenate arrays of same type:
 
<syntaxhighlight lang="babel">[1 2 3] [4] cat</syntaxhighlight>
 
<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.
Line 1,490:
Convert a value-array to a list of values:
 
<syntaxhighlight lang="babel">[1 2 3] ar2ls lsnum !</syntaxhighlight>
 
{{Out}}
Line 1,497:
Convert a list of values to a value-array:
 
<syntaxhighlight lang="babel">(1 2 3) ls2lf ;</syntaxhighlight>
 
{{Out}}
Line 1,504:
Convert a pointer-array to a list of pointers:
 
<syntaxhighlight lang="babel">[ptr 'foo' 'bar' 'baz'] ar2ls lsstr !</syntaxhighlight>
 
{{Out}}
Line 1,511:
Convert a list of pointers to a pointer-array:
 
<syntaxhighlight lang="babel">(1 2 3) bons ;</syntaxhighlight>
 
{{Out}}
Line 1,522:
Note: We need to use quotes in DATA
 
<syntaxhighlight lang="qbasic">
DATA "January", "February", "March", "April", "May", "June", "July"
DATA "August", "September", "October", "November", "December"
Line 1,535:
 
2.) A modern BaCon approach to do arrays using strings
<syntaxhighlight lang="qbasic">
DECLARE A$[11] = {"January", "February", "March", "April", "May", \
"June", "July", "August", "September", "October", "November", "December"} TYPE STRING
Line 1,551:
name this '''split.bac'''
 
<syntaxhighlight lang="qbasic">
SPLIT ARGUMENT$ BY " " TO TOK$ SIZE len_array
 
Line 1,561:
in the terminal
<syntaxhighlight lang="bash">
./split January February March April May June July August September October November December
</syntaxhighlight>
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.
<syntaxhighlight lang="qbasic"> OPTION BASE 1
DIM myArray(100) AS INTEGER </syntaxhighlight>
 
Alternatively, the lower and upper bounds can be given while defining the array:
<syntaxhighlight lang="qbasic"> DIM myArray(-10 TO 10) AS INTEGER </syntaxhighlight>
 
Dynamic arrays:
<syntaxhighlight lang="qbasic"> 'Specify that the array is dynamic and not static:
'$DYNAMIC
DIM SHARED myArray(-10 TO 10, 10 TO 30) AS STRING
Line 1,594:
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:
<syntaxhighlight lang="qbasic"> DIM month$(12)
DATA January, February, March, April, May, June, July
DATA August, September, October, November, December
Line 1,604:
 
FreeBASIC has an option to initialize array while declaring it.
<syntaxhighlight lang="freebasic"> Dim myArray(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}} </syntaxhighlight>
 
<syntaxhighlight lang="basic">10 REM TRANSLATION OF QBASIC STATIC VERSION
20 REM ELEMENT NUMBERS TRADITIONALLY START AT ONE
30 DIM A%(11): REM ARRAY OF ELEVEN INTEGER ELEMENTS
Line 1,618:
===Static===
 
<syntaxhighlight lang="qbasic">DIM staticArray(10) AS INTEGER
 
staticArray(0) = -1
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.
 
<syntaxhighlight lang="qbasic">REDIM dynamicArray(10) AS INTEGER
 
dynamicArray(0) = -1
Line 1,640:
 
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="basic">10 DIM A%(11): REM ARRAY OF TWELVE INTEGER ELEMENTS
20 LET A%(0) = -1
30 LET A%(11) = 1
Line 1,649:
 
=={{header|BASIC256}}==
<syntaxhighlight lang=BASIC256"basic256"># numeric array
dim numbers(10)
for t = 0 to 9
Line 1,682:
Arrays can be approximated, in a style similar to REXX
 
<syntaxhighlight lang="dos">::arrays.cmd
@echo off
setlocal ENABLEDELAYEDEXPANSION
Line 1,719:
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> REM Declare arrays, dimension is maximum index:
DIM array(6), array%(6), array$(6)
Line 1,742:
 
The following is a transcript of an interactive session:
<syntaxhighlight lang="bc">/* Put the value 42 into array g at index 3 */
g[3] = 42
/* Look at some other elements in g */
Line 1,764:
'''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.
 
<syntaxhighlight lang="bml">
% Define an array(containing the numbers 1-3) named arr in the group $
in $ let arr hold 1 2 3
Line 1,779:
 
=={{header|Boo}}==
<syntaxhighlight lang="boo">
myArray as (int) = (1, 2, 3) // Size based on initialization
fixedArray as (int) = array(int, 1) // Given size(1 in this case)
Line 1,794:
 
All arrays are variable length, and can contain any types of values.
<syntaxhighlight lang="bqn"># Stranding:
arr ← 1‿2‿'a'‿+‿5
# General List Syntax:
Line 1,807:
# Modifying the array(↩):
arr ↩ "hello"⌾(4⊸⊑) arr</syntaxhighlight>
<syntaxhighlight lang="bqn">1
⟨ 1 2 'a' + 5 ⟩
⟨ 1 2 'a' + 5 ⟩
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>.
 
<syntaxhighlight lang="bracmat">( tbl$(mytable,100)
& 5:?(30$mytable)
& 9:?(31$mytable)
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.
 
<syntaxhighlight lang="bf">
===========[
ARRAY DATA STRUCTURE
Line 1,936:
=={{header|C}}==
Fixed size static array of integers with initialization:
<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 */</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.
<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.
<syntaxhighlight lang="c">long a2D_Array[3][5]; /* 3 rows, 5 columns. */
float my2Dfloats[][3] = {
1.0, 2.0, 0.0,
Line 1,951:
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>.
<syntaxhighlight lang="c">int numElements = 10;
int *myArray = malloc(sizeof(int) * numElements); /* array of 10 integers */
if ( myArray != NULL ) /* check to ensure allocation succeeded. */
Line 1,966:
 
The first element of a C array is indexed with 0. To set a value:
<syntaxhighlight lang="c">myArray[0] = 1;
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)
<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
thus the square brackets are a commutative binary operator:
<syntaxhighlight lang="c">*(array + index) = 1;
printf("%d\n", *(array + index));
3[array] = 5;</syntaxhighlight>
 
There's no bounds check on the indexes. Negative indexing can be implemented as in the following.
<syntaxhighlight lang="c">#define XSIZE 20
double *kernel = malloc(sizeof(double)*2*XSIZE+1);
if (kernel) {
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
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">
int *array = malloc (sizeof(int) * 20);
....
Line 2,000:
</syntaxhighlight>
A Linked List for chars may be implemented like this:
<syntaxhighlight lang=C"c">
#include <stdlib.h>
#include <stdio.h>
Line 2,066:
Example of array of 10 int types:
 
<syntaxhighlight lang="csharp"> int[] numbers = new int[10];</syntaxhighlight>
 
Example of array of 3 string types:
 
<syntaxhighlight lang="csharp"> string[] words = { "these", "are", "arrays" };</syntaxhighlight>
 
You can also declare the size of the array and initialize the values at the same time:
 
<syntaxhighlight lang="csharp"> int[] more_numbers = new int[3]{ 21, 14 ,63 };</syntaxhighlight>
 
 
Line 2,080:
 
The following creates a 3x2 int matrix
<syntaxhighlight lang="csharp"> int[,] number_matrix = new int[3,2];</syntaxhighlight>
 
As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces.
 
<syntaxhighlight lang="csharp"> string[,] string_matrix = { {"I","swam"}, {"in","the"}, {"freezing","water"} };</syntaxhighlight>
 
or
 
<syntaxhighlight lang="csharp"> string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} };</syntaxhighlight>
 
<syntaxhighlight lang="csharp">int[] array = new int[10];
 
array[0] = 1;
Line 2,099:
Dynamic
 
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 2,123:
<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).
<syntaxhighlight lang="cpp">#include <array>
#include <vector>
 
Line 2,170:
=={{header|Ceylon}}==
{{works with|Ceylon|1.3.0}}
<syntaxhighlight lang="ceylon">import ceylon.collection {
 
ArrayList
Line 2,192:
 
=={{header|ChucK}}==
<syntaxhighlight lang="c">
int array[0]; // instantiate int array
array << 1; // append item
Line 2,208:
===Lazy array===
Create a lazy array of strings using an array denotation.
<syntaxhighlight lang="clean">array :: {String}
array = {"Hello", "World"}</syntaxhighlight>
Create a lazy array of floating point values by sharing a single element.
<syntaxhighlight lang="clean">array :: {Real}
array = createArray 10 3.1415</syntaxhighlight>
Create a lazy array of integers using an array (and also a list) comprehension.
<syntaxhighlight lang="clean">array :: {Int}
array = {x \\ x <- [1 .. 10]}</syntaxhighlight>
===Strict array===
Create a strict array of integers.
<syntaxhighlight lang="clean">array :: {!Int}
array = {x \\ x <- [1 .. 10]}</syntaxhighlight>
===Unboxed array===
Create an unboxed array of characters, also known as <tt>String</tt>.
<syntaxhighlight lang="clean">array :: {#Char}
array = {x \\ x <- ['a' .. 'z']}</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="visualfoxpro"> // Declare and initialize two-dimensional array
Local arr1 := { { "NITEM","N",10,0 }, { "CONTENT","C",60,0} }
// Create an empty array
Line 2,239:
arr4 := ASize( arr4, 80 )</syntaxhighlight>
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
<syntaxhighlight lang="visualfoxpro">// Adding new item to array, its size is incremented
Aadd( arr1, { "LBASE","L",1,0 } )
// Delete the first item of arr3, The size of arr3 remains the same, all items are shifted to one position, the last item is replaced by Nil:
Line 2,246:
arr3[1,1,1] := 11.4</syntaxhighlight>
Retrieve items of an array:
<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
</syntaxhighlight>
There is a set of functions to manage arrays in Clipper, including the following:
<syntaxhighlight lang="visualfoxpro">// Fill the 20 items of array with 0, starting from 5-th item:
AFill( arr4, 0, 5, 20 )
//Copy 10 items from arr4 to arr3[2], starting from the first position:
Line 2,259:
 
=={{header|Clojure}}==
<syntaxhighlight lang=Clojure"clojure">;clojure is a language built with immutable/persistent data structures. there is no concept of changing what a vector/list
;is, instead clojure creates a new array with an added value using (conj...)
;in the example below the my-list does not change.
Line 2,296:
=={{header|COBOL}}==
In COBOL, arrays are called ''tables''. Also, indexes begin from 1.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. arrays.
 
Line 2,337:
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">array1 = []
array1[0] = "Dillenidae"
array1[1] = "animus"
Line 2,348:
=={{header|ColdFusion}}==
Creating a one-dimensional Array:
<syntaxhighlight lang="cfm"><cfset arr1 = ArrayNew(1)></syntaxhighlight>
 
Creating a two-dimensional Array in CFScript:
<syntaxhighlight lang="cfm"><cfscript>
arr2 = ArrayNew(2);
</cfscript></syntaxhighlight>
Line 2,358:
=={{header|Common Lisp}}==
 
<syntaxhighlight lang="lisp">(let ((array (make-array 10)))
(setf (aref array 0) 1
(aref array 1) 3)
Line 2,365:
Dynamic
 
<syntaxhighlight lang="lisp">(let ((array (make-array 0 :adjustable t :fill-pointer 0)))
(vector-push-extend 1 array)
(vector-push-extend 3 array)
Line 2,372:
 
Creates a one-dimensional array of length 10. The initial contents are undefined.
<syntaxhighlight lang="lisp">(make-array 10)</syntaxhighlight>
Creates a two-dimensional array with dimensions 10x20.
<syntaxhighlight lang="lisp">(make-array '(10 20))</syntaxhighlight>
<tt>make-array</tt> may be called with a number of optional arguments.
<syntaxhighlight lang="lisp">; Makes an array of 20 objects initialized to nil
(make-array 20 :initial-element nil)
; Makes an integer array of 4 elements containing 1 2 3 and 4 initially which can be resized
Line 2,386:
 
 
<syntaxhighlight lang="oberon2">
MODULE TestArray;
(* Implemented in BlackBox Component Builder *)
Line 2,422:
===Fixed-length array===
We have finished iterating through the array when the next load instruction would be <tt>LDA ary+length(ary)</tt>.
<syntaxhighlight lang="czasm">load: LDA ary
ADD sum
STA sum
Line 2,454:
10</syntaxhighlight>
===Zero-terminated array===
<syntaxhighlight lang="czasm">load: LDA ary
BRZ done
 
Line 2,486:
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">
# create an array with one object in it
a = ["foo"]
Line 2,510:
 
=={{header|D}}==
<syntaxhighlight lang="d">// All D arrays are capable of bounds checks.
 
import std.stdio, core.stdc.stdlib;
Line 2,561:
D) Element 1: 3</pre>
One more kind of built-in array:
<syntaxhighlight lang="d">import std.stdio, core.simd;
 
void main() {
Line 2,577:
 
=={{header|Dao}}==
<syntaxhighlight lang="dao"># use [] to create numeric arrays of int, float, double or complex types:
a = [ 1, 2, 3 ] # a vector
b = [ 1, 2; 3, 4 ] # a 2X2 matrix
Line 2,589:
 
=={{header|Dart}}==
<syntaxhighlight lang="javascript">
main(){
// Dart uses Lists which dynamically resize by default
Line 2,642:
 
=={{header|DBL}}==
<syntaxhighlight lang=DBL"dbl">;
; Arrays for DBL version 4 by Dario B.
;
Line 2,697:
=={{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.
<syntaxhighlight lang="delphi">
procedure TForm1.Button1Click(Sender: TObject);
var
Line 2,736:
 
=={{header|Diego}}==
<syntaxhighlight lang="diego">set_ns(rosettacode);
set_base(0);
 
Line 2,855:
 
=={{header|Dragon}}==
<syntaxhighlight lang="dragon">array = newarray(3) //optionally, replace "newarray(5)" with a brackets list of values like "[1, 2, 3]"
array[0] = 42
showln array[2] </syntaxhighlight>
Line 2,861:
=={{header|DWScript}}==
 
<syntaxhighlight lang="delphi">
// dynamic array, extensible, this a reference type
var d : array of Integer;
Line 2,880:
=={{header|Dyalect}}==
 
<syntaxhighlight lang="dyalect">//Dyalect supports dynamic arrays
var empty = []
var xs = [1, 2, 3]
Line 2,894:
=={{header|Déjà Vu}}==
In Déjà Vu, the relevant datatype is called list, which is basically a stack with random element access for getting and setting values.
<syntaxhighlight lang="dejavu">#create a new list
local :l []
 
Line 2,922:
Literal lists are <code>ConstList</code>s.
 
<syntaxhighlight lang="e">? def empty := []
# value: []
 
Line 2,936:
Note that each of these operations returns a different list object rather than modifying the original. You can, for example, collect values:
 
<syntaxhighlight lang="e">? var numbers := []
# value: []
 
Line 2,947:
FlexLists can be created explicitly, but are typically created by ''diverging'' another list. A ConstList can be gotten from a FlexList by ''snapshot''.
 
<syntaxhighlight lang="e">? def flex := numbers.diverge()
# value: [1, 2].diverge()
 
Line 2,962:
Creating a FlexList with a specific size, generic initial data, and a type restriction:
 
<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]].
Line 2,970:
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">len f[] 3
for i range len f[]
f[i] = i
Line 2,983:
 
'''Fixed-length array'''
<syntaxhighlight lang=EGL"egl">
array int[10]; //optionally, add a braced list of values. E.g. array int[10]{1, 2, 3};
array[1] = 42;
Line 3,008:
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 3,048:
 
Static array
<syntaxhighlight lang="elena"> var staticArray := new int[]{1, 2, 3};</syntaxhighlight>
Generic array
<syntaxhighlight lang="elena"> var array := system'Array.allocate:3;
array[0] := 1;
array[1] := 2;
array[2] := 3;</syntaxhighlight>
Stack allocated array
<syntaxhighlight lang="elena"> int stackAllocatedArray[3];
stackAllocatedArray[0] := 1;
stackAllocatedArray[1] := 2;
stackAllocatedArray[2] := 3;</syntaxhighlight>
Dynamic array
<syntaxhighlight lang="elena"> var dynamicArray := new system'collections'ArrayList();
dynamicArray.append:1;
dynamicArray.append:2;
Line 3,067:
dynamicArray[2] := 3;</syntaxhighlight>
Printing an element
<syntaxhighlight lang="elena"> system'console.writeLine(array[0]);
system'console.writeLine(stackAllocatedArray[1]);
system'console.writeLine(dynamicArray[2]);</syntaxhighlight>
Line 3,074:
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:
 
<syntaxhighlight lang="elixir">ret = {:ok, "fun", 3.1415}</syntaxhighlight>
 
Elements of tuples are indexed numerically, starting with zero.
 
<syntaxhighlight lang="elixir">elem(ret, 1) == "fun"
elem(ret, 0) == :ok
put_elem(ret, 2, "pi") # => {:ok, "fun", "pi"}
Line 3,085:
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.
 
<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.
 
<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:
 
<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.
 
<syntaxhighlight lang="elixir">my_list = [1, :two, "three"]
my_list ++ [4, :five] # => [1, :two, "three", 4, :five]
 
Line 3,108:
Lists have a ''head'', being the first element, and a ''tail'', which are all the elements of the list following the head.
 
<syntaxhighlight lang="elixir">iex(1)> fruit = [:apple, :banana, :cherry]
[:apple, :banana, :cherry]
iex(2)> hd(fruit)
Line 3,120:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
%% Create a fixed-size array with entries 0-9 set to 'undefined'
A0 = array:new(10).
Line 3,204:
 
=={{header|Euphoria}}==
<syntaxhighlight lang=Euphoria"euphoria">
--Arrays task for Rosetta Code wiki
--User:Lnettnay
Line 3,250:
=={{header|F Sharp|F#}}==
'''Fixed-length arrays:'''
<syntaxhighlight lang="fsharp">> Array.create 6 'A';;
val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
> Array.init 8 (fun i -> i * 10) ;;
Line 3,266:
 
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>:
<syntaxhighlight lang="fsharp">> let arr = new ResizeArray<int>();;
val arr : ResizeArray<int>
> arr.Add(42);;
Line 3,287:
 
Directly in the listener :
<syntaxhighlight lang="factor">{ 1 2 3 }
{
[ "The initial array: " write . ]
Line 3,303:
{ 1 "coucou" f [ ] }
Arrays of growable length are called Vectors.
<syntaxhighlight lang="factor">V{ 1 2 3 }
{
[ "The initial vector: " write . ]
Line 3,373:
For example, a static array of 10 cells in the dictionary, 5 initialized and 5 uninitialized:
 
<syntaxhighlight lang="forth">create MyArray 1 , 2 , 3 , 4 , 5 , 5 cells allot
here constant MyArrayEnd
 
Line 3,381:
: .array MyArrayEnd MyArray do I @ . cell +loop ;</syntaxhighlight>
 
<syntaxhighlight lang="forth">
: array ( n -- )
create
Line 3,403:
.MyArray \ 1 2 3 4 5 0 30 0 0 0
</syntaxhighlight>
<syntaxhighlight lang="forth">
: array create dup , dup cells here swap 0 fill cells allot ;
: [size] @ ;
Line 3,425:
 
Basic array declaration:
<syntaxhighlight lang="fortran">integer a (10)</syntaxhighlight>
<syntaxhighlight lang="fortran">integer :: a (10)</syntaxhighlight>
<syntaxhighlight lang="fortran">integer, dimension (10) :: a</syntaxhighlight>
Arrays are one-based. These declarations are equivalent:
<syntaxhighlight lang="fortran">integer, dimension (10) :: a</syntaxhighlight>
<syntaxhighlight lang="fortran">integer, dimension (1 : 10) :: a</syntaxhighlight>
Other bases can be used:
<syntaxhighlight lang="fortran">integer, dimension (0 : 9) :: a</syntaxhighlight>
Arrays can have any type (intrinsic or user-defined), e.g.:
<syntaxhighlight lang="fortran">real, dimension (10) :: a</syntaxhighlight>
<syntaxhighlight lang="fortran">type (my_type), dimension (10) :: a</syntaxhighlight>
Multidimensional array declaration:
<syntaxhighlight lang="fortran">integer, dimension (10, 10) :: a</syntaxhighlight>
<syntaxhighlight lang="fortran">integer, dimension (10, 10, 10) :: a</syntaxhighlight>
Allocatable array declaration:
<syntaxhighlight lang="fortran">integer, dimension (:), allocatable :: a</syntaxhighlight>
<syntaxhighlight lang="fortran">integer, dimension (:, :), allocatable :: a</syntaxhighlight>
Array allocation:
<syntaxhighlight lang="fortran">allocate (a (10))</syntaxhighlight>
<syntaxhighlight lang="fortran">allocate (a (10, 10))</syntaxhighlight>
Array deallocation:
<syntaxhighlight lang="fortran">deallocate (a)</syntaxhighlight>
Array initialisation:
<syntaxhighlight lang="fortran">integer, dimension (10) :: a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</syntaxhighlight>
<syntaxhighlight lang="fortran">integer :: i
integer, dimension (10) :: a = (/(i * i, i = 1, 10)/)</syntaxhighlight>
<syntaxhighlight lang="fortran">integer, dimension (10) :: a = 0</syntaxhighlight>
<syntaxhighlight lang="fortran">integer :: i
integer, dimension (10, 10) :: a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))</syntaxhighlight>
Constant array declaration:
<syntaxhighlight lang="fortran">integer :: i
integer, dimension (10), parameter :: a = (/(i * i, i = 1, 10)/)</syntaxhighlight>
Element assignment:
<syntaxhighlight lang="fortran">a (1) = 1</syntaxhighlight>
<syntaxhighlight lang="fortran">a (1, 1) = 1</syntaxhighlight>
Array assignment (note that since Fortran 2003 array assignment also allocates or reallocates if necessary):
<syntaxhighlight lang="fortran">a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</syntaxhighlight>
<syntaxhighlight lang="fortran">a = (/(i * i, i = 1, 10)/)</syntaxhighlight>
<syntaxhighlight lang="fortran">a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))</syntaxhighlight>
<syntaxhighlight lang="fortran">a = 0</syntaxhighlight>
Array section assignment:
<syntaxhighlight lang="fortran">a (:) = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)</syntaxhighlight>
<syntaxhighlight lang="fortran">a (1 : 5) = (/1, 2, 3, 4, 5/)</syntaxhighlight>
<syntaxhighlight lang="fortran">a (: 5) = (/1, 2, 3, 4, 5/)</syntaxhighlight>
<syntaxhighlight lang="fortran">a (6 :) = (/1, 2, 3, 4, 5/)</syntaxhighlight>
<syntaxhighlight lang="fortran">a (1 : 5) = (/(i * i, i = 1, 10)/)</syntaxhighlight>
<syntaxhighlight lang="fortran">a (1 : 5)= 0</syntaxhighlight>
<syntaxhighlight lang="fortran">a (1, :)= (/(i * i, i = 1, 10)/)</syntaxhighlight>
<syntaxhighlight lang="fortran">a (1 : 5, 1)= (/(i * i, i = 1, 5)/)</syntaxhighlight>
Element retrieval:
<syntaxhighlight lang="fortran">i = a (1)</syntaxhighlight>
Array section retrieval:
<syntaxhighlight lang="fortran">a = b (1 : 10)</syntaxhighlight>
Size retrieval:
<syntaxhighlight lang="fortran">i = size (a)</syntaxhighlight>
Size along a single dimension retrieval:
<syntaxhighlight lang="fortran">i = size (a, 1)</syntaxhighlight>
Bounds retrieval:
<syntaxhighlight lang="fortran">i_min = lbound (a)</syntaxhighlight>
<syntaxhighlight lang="fortran">i_max = ubound (a)</syntaxhighlight>
Bounds of a multidimensional array retrieval:
<syntaxhighlight lang="fortran">a = ubound (b)</syntaxhighlight>
 
=={{header|FreeBASIC}}==
Line 3,519:
 
'''The default lower bound is always 0'''
<syntaxhighlight lang=FreeBASIC"freebasic">' compile with: FBC -s console.
' compile with: FBC -s console -exx to have boundary checks.
 
Line 3,635:
=={{header|Frink}}==
In Frink, all arrays are dynamically resizable. Arrays can be created as literals or using <CODE>new array</CODE>
<syntaxhighlight lang="frink">
a = new array
a@0 = 10
Line 3,648:
Multidimensional regular arrays are a built-in datatype in Futhark. They can be written as array literals:
 
<syntaxhighlight lang=Futhark"futhark">
[1, 2, 3]
</syntaxhighlight>
Line 3,654:
Or created by an assortment of built-in functions:
 
<syntaxhighlight lang=Futhark"futhark">
replicate 5 3 == [3,3,3,3,3]
iota 5 = [0,1,2,3,4]
Line 3,661:
Uniqueness types are used to permit in-place updates without violating referential transparency. For example, we can write a function that writes an element to a specific index of an array as such:
 
<syntaxhighlight lang=Futhark"futhark">
fun update(as: *[]int, i: int, x: int): []int =
let as[i] = x
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:
 
<syntaxhighlight lang="gambas">
DIM mynumbers AS INTEGER[]
myfruits AS STRING[]
Line 3,688:
 
'''[https://gambas-playground.proko.eu/?gist=5061d7f882a4768d212080e416c25e27 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sFixedArray As String[] = ["Rosetta", "code", "is", "a", "programming", "chrestomathy", "site"]
Dim sFixedArray1 As New String[10]
Line 3,715:
 
=={{header|GAP}}==
<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 ] ];
# [ 10, 7, "bob", true, [ "inner", 5 ] ]
Line 3,762:
 
=={{header|Genie}}==
<syntaxhighlight lang="genie">[indent=4]
/*
Arrays, in Genie
Line 3,811:
====Example of Fixed Length Array====
Array containing a space (" "), "A", "B", and "C":
<syntaxhighlight lang=GML"gml">array[0] = ' '
array[1] = 'A'
array[2] = 'B'
Line 3,818:
====Example of Arbitrary Length Array====
Array containing the set of all natural numbers from 1 through k:
<syntaxhighlight lang=GML"gml">for(i = 0; i < k; i += 1)
array[i] = i + 1</syntaxhighlight>
 
Line 3,824:
====Example of Fixed Length Array====
Array containing the multiplication table of 1 through 4 by 1 through 3:
<syntaxhighlight lang=GML"gml">array[1,1] = 1
array[1,2] = 2
array[1,3] = 3
Line 3,839:
====Example of Arbitrary Length Array====
Array containing the multiplication table of 1 through k by 1 through h:
<syntaxhighlight lang=GML"gml">for(i = 1; i <= k; i += 1)
for(j = 1; j <= h; j += 1)
array[i,j] = i * j</syntaxhighlight>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
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.
 
<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]
a 0= puts # pick element at index 0 (stack: 0)
Line 3,937:
=={{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.
<syntaxhighlight lang="groovy">def aa = [ 1, 25, 31, -3 ] // list
def a = [0] * 100 // list of 100 zeroes
def b = 1..9 // range notation
Line 3,972:
 
Here is a more interesting example showing a function that creates and returns a square identity matrix of order N:
<syntaxhighlight lang="groovy">def identity = { n ->
(1..n).collect { i -> (1..n).collect { j -> i==j ? 1.0 : 0.0 } }
}</syntaxhighlight>
 
Test program:
<syntaxhighlight lang="groovy">def i2 = identity(2)
def i15 = identity(15)
 
Line 4,007:
Groovy, like every other C-derived language in the known universe, uses ZERO-based array/list indexing.
 
<syntaxhighlight lang="groovy">def strings = ['Mary', 'had', 'a', 'little', 'lamb', ". It's", 'fleece', 'was', 'white', 'as', 'snow']
 
println strings
Line 4,026:
Negative indices are valid. They indicate indexing from the end of the list towards the start.
 
<syntaxhighlight lang="groovy">println strings[-1]</syntaxhighlight>
 
{{out}}
Line 4,034:
Groovy lists can be resequenced and subsequenced by providing lists or ranges of indices in place of a single index.
 
<syntaxhighlight lang="groovy">println strings[0, 7, 2, 3, 8]
println strings[0..4]
println strings[0..3, -5]</syntaxhighlight>
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:
 
<syntaxhighlight lang=GUISS"guiss">Start,Programs,Lotus 123,Type:Bob[downarrow],Kat[downarrow],Sarah[downarrow]</syntaxhighlight>
 
=={{header|GW-BASIC}}==
Line 4,055:
(GW-BASIC User's Guide)
 
<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
30 FOR I = 0 TO 9
Line 4,066:
 
=={{header|Halon}}==
<syntaxhighlight lang="halon">$array = [];
$array[] = 1;
Line 4,078:
=={{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.
<syntaxhighlight lang="visualfoxpro"> // Declare and initialize two-dimensional array
local arr1 := { { "NITEM", "N", 10, 0 }, { "CONTENT", "C", 60, 0 } }
// Create an empty array
Line 4,090:
arr4 := ASize( arr4, 80 )</syntaxhighlight>
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
<syntaxhighlight lang="visualfoxpro">// Adding new item to array, its size is incremented
AAdd( arr1, { "LBASE", "L", 1, 0 } )
// Delete the first item of arr3, The size of arr3 remains the same, all items are shifted to one position, the last item is replaced by Nil:
Line 4,097:
arr3[ 1, 1, 1 ] := 11.4</syntaxhighlight>
Retrieve items of an array:
<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
</syntaxhighlight>
There is a set of functions to manage arrays in Clipper, including the following:
<syntaxhighlight lang="visualfoxpro">// Fill the 20 items of array with 0, starting from 5-th item:
AFill( arr4, 0, 5, 20 )
// Copy 10 items from arr4 to arr3[ 2 ], starting from the first position:
Line 4,111:
=={{header|Haskell}}==
You can read all about Haskell arrays [http://haskell.org/haskellwiki/Arrays here]. The following example is taken from that page:
<syntaxhighlight lang="haskell">import Data.Array.IO
 
main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)
Line 4,120:
 
=={{header|hexiscript}}==
<syntaxhighlight lang="hexiscript">let a arr 2 # fixed size
let a[0] 123 # index starting at 0
let a[1] "test" # can hold different types
Line 4,127:
 
=={{header|HicEst}}==
<syntaxhighlight lang="hicest">REAL :: n = 3, Astat(n), Bdyn(1, 1)
 
Astat(2) = 2.22222222
Line 4,140:
 
=={{header|HolyC}}==
<syntaxhighlight lang="holyc">// Create an array of fixed size
U8 array[10] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
 
Line 4,151:
==Icon and Unicon==
==={{header|Icon}}===
<syntaxhighlight lang="icon">record aThing(a, b, c) # arbitrary object (record or class) for illustration
 
procedure main()
Line 4,252:
==={{header|Unicon}}===
This Icon solution works in Unicon.
<syntaxhighlight lang="unicon"># Unicon provides a number of extensions
# insert and delete work on lists allowing changes in the middle
# possibly others
Line 4,259:
 
=={{header|i}}==
<syntaxhighlight lang="i">main
//Fixed-length arrays.
f $= array.integer[1]()
Line 4,272:
 
=={{header|Io}}==
<syntaxhighlight lang=Io"io">foo := list("foo", "bar", "baz")
foo at(1) println // bar
foo append("Foobarbaz")
Line 4,295:
=={{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.
<syntaxhighlight lang="j"> 1 NB. a stand-alone scalar value is an array without any axis
1
NB. invoking any array produces that array as the result
Line 4,327:
Note also that J's arrays are (with some obscure exceptions) "constants". We can append to an existing array, creating a new array, but if we kept a reference to the original it would have remained unchanged.
 
<syntaxhighlight lang=J"j"> A=: 7 11
B=: A, 9 5
B
Line 4,334:
7 11</syntaxhighlight>
 
Thus, in recent versions of J, special syntax was introduced to refer to a value while discarding the reference: <syntaxhighlight lang=J"j"> A=: 2 4 6 8
B=: A_:, 1 3 9 5
B
Line 4,342:
 
=={{header|Java}}==
<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;
System.out.println(array[3]);</syntaxhighlight>
Line 4,348:
Dynamic arrays can be made using <code>List</code>s:
 
<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(1, 6); // inserts an element at index 1
Line 4,356:
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.
<syntaxhighlight lang="javascript">// Create a new array with length 0
var myArray = new Array();
 
Line 4,383:
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.<syntaxhighlight lang="jq"># Create a new array with length 0
[]
 
Line 4,422:
=={{header|Jsish}}==
From Javascript, with the differences that Jsi treats ''typeof [elements]'' as "array", not "object".
<syntaxhighlight lang="javascript">/* Arrays in Jsi */
// Create a new array with length 0
var myArray = new Array();
Line 4,515:
 
=={{header|KonsolScript}}==
<syntaxhighlight lang=KonsolScript"konsolscript">//creates an array of length 3
Array:New array[3]:Number;
 
Line 4,528:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">fun main(x: Array<String>) {
var a = arrayOf(1, 2, 3, 4)
println(a.asList())
Line 4,544:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
// Create a new array with length 0
{def myArray1 {A.new}}
Line 4,572:
 
=={{header|lang5}}==
<syntaxhighlight lang="lang5">[]
1 append
['foo 'bar] append
Line 4,581:
Langur uses 1-based indexing.
 
<syntaxhighlight lang="langur">var .a1 = [1, 2, 3, "abc"]
val .a2 = series 4..10
val .a3 = .a1 ~ .a2
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.
 
<syntaxhighlight lang=Lasso"lasso">// Create a new empty array
local(array1) = array
Line 4,665:
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.
 
<syntaxhighlight lang=Lasso"lasso">// Create a staticarray containing 5 items
local(mystaticArray) = staticarray('a','b','c','d','e')
 
Line 4,680:
 
Like everything in Latitude, arrays are simply objects. In particular, arrays store their elements in numerical slots rather than traditional symbolic ones. The translation scheme used to store them enables constant-time push and pop operations on either side of the array.
<syntaxhighlight lang=Latitude"latitude">;; Construct an array.
foo := [1, 2, 3].
 
Line 4,710:
 
Using the LFE REPL, you can explore arrays in the following manner:
<syntaxhighlight lang="lisp">
; Create a fixed-size array with entries 0-9 set to 'undefined'
> (set a0 (: array new 10))
Line 4,776:
DATA is READ into variables. It cannot be READ directly into arrays.
<br>To fill arrays with DATA items, first READ the item into a variable, then use that variable to fill an index of the array.
<syntaxhighlight lang="lb">
dim Array(10)
 
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.
 
<syntaxhighlight lang="tcl"># (not) Arrays, in LIL
set a [list abc def ghi]
set b [list 4 5 6]
Line 4,833:
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">a = [1,2] -- or: a = list(1,2)
put a[2] -- or: put a.getAt(2)
-- 2
Line 4,851:
In addition to the 'list' type shown above, for arrays of bytes (i.e. integers between 0 and 255) there is also the bytearray data type:
 
<syntaxhighlight lang="lingo">ba = bytearray(2, 255) -- initialized with size 2 and filled with 0xff
put ba
-- <ByteArrayObject length = 2 ByteArray = 0xff, 0xff >
Line 4,864:
 
=={{header|Lisaac}}==
<syntaxhighlight lang=Lisaac"lisaac">+ a : ARRAY(INTEGER);
a := ARRAY(INTEGER).create 0 to 9;
a.put 1 to 0;
Line 4,872:
=={{header|Little}}==
Arrays in Little are list of values of the same type and they grow dynamically.
<syntaxhighlight lang=C"c">String fruit[] = {"apple", "orange", "Pear"}</syntaxhighlight>
 
They are zero-indexed. You can use END to get the last element of an array:
<syntaxhighlight lang=C"c">
puts(fruit[0]);
puts(fruit[1]);
Line 4,882:
 
=={{header|Logo}}==
<syntaxhighlight lang="logo">array 5 ; default origin is 1, every item is empty
(array 5 0) ; custom origin
make "a {1 2 3 4 5} ; array literal
Line 4,889:
 
=={{header|LOLCODE}}==
<syntaxhighlight lang=LOLCODE"lolcode">HAI 1.4
BTW declaring array
I HAS A array ITZ A BUKKIT
Line 4,909:
 
=={{header|LSE64}}==
<syntaxhighlight lang="lse64">10 myArray :array
0 array 5 [] ! # store 0 at the sixth cell in the array
array 5 [] @ # contents of sixth cell in array</syntaxhighlight>
Line 4,915:
=={{header|LSL}}==
LSL does not have Arrays, but it does have [http://wiki.secondlife.com/wiki/List lists] which can function similar to a one dimensional ArrayList in Java or C#.
<syntaxhighlight lang=LSL"lsl">
default {
state_entry() {
Line 4,975:
=={{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.
<syntaxhighlight lang="lua">l = {}
l[1] = 1 -- Index starts with 1, not 0.
l[0] = 'zero' -- But you can use 0 if you want
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.
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module CheckArray {
\\ Array with parenthesis in name
Line 5,078:
===Passing Arrays By Reference===
By default arrays passed by value. Here in make() we read reference in a variable A, which interpreter put then pointer to array, so it is a kind of reference (like in C). Using & we have normal reference. A ++ operator in a pointer of array add one to each element.
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Dim a(10)=1
Print a() ' 1 1 1 1 1 1 1 1 1 1
Line 5,095:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">#defining an array of a certain length
a := Array (1..5);
a := [ 0 0 0 0 0 ]
Line 5,114:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">a = Array[Sin, 10]
a[[1]]
Delete[a, 2]</syntaxhighlight>
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.
 
<syntaxhighlight lang=MATLAB"matlab">>> a = [1 2 35] %Declaring a vector (i.e. one-dimensional array)
 
a =
Line 5,188:
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">/* Declare an array, subscripts run from 0 to max value */
array(a, flonum, 20, 20, 3)$
 
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'.
 
<syntaxhighlight lang=Mercury"mercury">:- module array_example.
:- interface.
:- import_module io.
Line 5,301:
 
Example:
<syntaxhighlight lang=MiniScript"miniscript">arr = ["a", 1, 3]
print arr[0]
 
Line 5,308:
 
=={{header|MIPS Assembly}}==
<syntaxhighlight lang="mips">
.data
array: .word 1, 2, 3, 4, 5, 6, 7, 8, 9 # creates an array of 9 32 Bit words.
Line 5,328:
 
=={{header|Modula-3}}==
<syntaxhighlight lang="modula3">VAR staticArray: ARRAY [1..10] OF INTEGER;</syntaxhighlight>
Defines a static array of 10 elements, indexed 1 through 10.
 
Static arrays can also be given initial values:
<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. *)</syntaxhighlight>
 
Open (dynamic) arrays can be be defined by creating a reference to an array of an unspecified size:
<syntaxhighlight lang="modula3">TYPE TOpenIntArray = REF ARRAY OF INTEGER;
VAR openArray: TOpenIntArray;</syntaxhighlight>
Defines an open array of a currently unknown size.
Line 5,342:
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:
<syntaxhighlight lang="modula3">openArray := NEW(TOpenIntArray, 10);</syntaxhighlight>
Initializes the open array to hold 10 elements, indexed 0 through 9. Modula-3 uses garbage collection for heap allocated data by default, so once all references to the open array go out of scope, the memory it occupied is de-allocated automatically.
 
Retrieval or insertion of elements and determining array bounds is performed using the same built-in functions regardless of the array kind. Though open arrays must first be de-referenced when passing them to such functions. Assuming we have made the declarations above, we can do the following:
<syntaxhighlight lang="modula3"> VAR
staticArraySize := NUMBER(staticArray);
staticArrayElement := staticArray[4];
Line 5,353:
openArrayElement := openArray[9];</syntaxhighlight>
 
<syntaxhighlight lang="modula3">staticArray[4] := 100;
openArray[1] := 200;</syntaxhighlight>
 
=={{header|Monte}}==
 
<syntaxhighlight lang=Monte"monte">var myArray := ['a', 'b', 'c','d']</syntaxhighlight>
 
To retrieve a value:
 
<syntaxhighlight lang=Monte"monte">traceln(myArray[0])</syntaxhighlight>
 
To change a value:
 
<syntaxhighlight lang=Monte"monte">myArray := myArray.with(3, 'z')</syntaxhighlight>
 
Now myArray is ['a','b','c','z'].
 
=={{header|Nanoquery}}==
<syntaxhighlight lang=Nanoquery"nanoquery">// create a fixed-length array (length 10)
arr = array(10)
 
Line 5,394:
 
=={{header|Neko}}==
<syntaxhighlight lang=Neko"neko">var myArray = $array(1);
 
$print(myArray[0]);</syntaxhighlight>
Line 5,402:
 
=={{header|Nemerle}}==
<syntaxhighlight lang=Nemerle"nemerle">using System;
using System.Console;
using System.Collections;
Line 5,425:
=={{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]]).
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 5,475:
=={{header|NewLISP}}==
This creates an array of 5 elements, initialized to <code>nil</code>:
<syntaxhighlight lang="lisp">(array 5)
→ (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.
<syntaxhighlight lang="lisp">(set 'myarray (array 3 4 (sequence 1 12)))
→ ((1 2 3 4) (5 6 7 8) (9 10 11 12))</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">var # fixed size arrays
x = [1,2,3,4,5,6,7,8,9,10] # type and size automatically inferred
y: array[1..5, int] = [1,2,3,4,5] # starts at 1 instead of 0
Line 5,506:
 
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang=NS"ns-HUBASIChubasic">10 DIM A(1)
20 A(1)=10
30 PRINT A(1)</syntaxhighlight>
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.
</div>
<syntaxhighlight lang="nsis">
!include NSISArray.nsh
Function ArrayTest
Line 5,532:
 
=={{header|Oberon-2}}==
<syntaxhighlight lang="oberon2">
MODULE Arrays;
IMPORT
Line 5,572:
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
bundle Default {
class Arithmetic {
Line 5,586:
 
=={{header|Objective-C}}==
<syntaxhighlight lang="objc">// NSArrays are ordered collections of NSObject subclasses only.
 
// Create an array of NSString objects.
Line 5,613:
=={{header|OCaml}}==
in the toplevel:
<syntaxhighlight lang="ocaml"># Array.make 6 'A' ;;
- : char array = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
 
Line 5,636:
To create a mutable array, #new is used.
 
<syntaxhighlight lang=Oforth"oforth">[ "abd", "def", "ghi" ] at( 3 ) .
 
Array new dup addAll( [1, 2, 3] ) dup put( 2, 8.1 ) .
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.
 
<syntaxhighlight lang="scheme">
; making a vector
> #(1 2 3 4 5)
Line 5,772:
=={{header|ooRexx}}==
ooRexx arrays hold object references. Arrays will automatically increase in size if needed.
<syntaxhighlight lang=ooRexx"oorexx"> a = .array~new -- create a zero element array
b = .array~new(10) -- create an array with initial size of 10
c = .array~of(1, 2, 3) -- create a 3 element array holding objects 1, 2, and 3
Line 5,796:
to all compound variables with that stem.
 
<syntaxhighlight lang=ooRexx"oorexx">
XXX.='*'
Say 'xxx.1='xxx.1 -- shows xxx.1=*
Line 5,821:
must not exceed 250 bytes no longer applies to ooRexx and Regina.
XXX.u.v...='something'
<syntaxhighlight lang=ooRexx"oorexx">u=17
v='John Doe'
XXX.u.v...='some value'
Line 5,828:
 
When using a stem for storing structured data, as in
<syntaxhighlight lang=ooRexx"oorexx">person.first='Walter'
person.last='Pachl'</syntaxhighlight>
it is advisable to use constant symbols such as 0first and 0last in the tail
Line 5,834:
 
=={{header|OxygenBasic}}==
<syntaxhighlight lang="oxygenbasic">
 
'CREATING A STATIC ARRAY
Line 5,862:
=={{header|Oz}}==
 
<syntaxhighlight lang="oz">declare
Arr = {Array.new 1 %% lowest index
10 %% highest index
Line 5,872:
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">v=[];
v=concat(v,7);
v[1]</syntaxhighlight>
Line 5,878:
=={{header|Pascal}}==
A modification of the Delphi example:
<syntaxhighlight lang="pascal">
Program ArrayDemo;
uses
Line 5,918:
In-line
 
<syntaxhighlight lang="perl"> my @empty;
my @empty_too = ();
Line 5,930:
Dynamic
 
<syntaxhighlight lang="perl">my @arr;
 
push @arr, 1;
Line 5,941:
Two-dimensional
 
<syntaxhighlight lang="perl"> my @multi_dimensional = (
[0, 1, 2, 3],
[qw(a b c d e f g)],
Line 5,956:
without any need to worry about memory management issues.
 
<!--<syntaxhighlight lang=Phix"phix">-->
<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>
Line 6,045:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">include ..\Utilitys.pmt
 
0 tolist /# create an empty array/list. '( )' is equivalent #/
Line 6,064:
===Writing To An Array===
====Single Dimension====
<syntaxhighlight lang="php">$NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];</syntaxhighlight>
 
====Multi-Dimensional====
<syntaxhighlight lang="php">$MultiArray = array(
array(0, 0, 0, 0, 0, 0),
array(1, 1, 1, 1, 1, 1),
Line 6,078:
====Array push====
 
<syntaxhighlight lang="php">$arr = ['apple', 'orange'];
array_push($arr, 'pear');
print implode(',', $arr); // Returns apple,orange,pear</syntaxhighlight>
Line 6,085:
====Single Dimension====
Read the 5th value in the array:
<syntaxhighlight lang="php">echo $NumberArray[5]; // Returns 5
echo $LetterArray[5]; // Returns f</syntaxhighlight>
====Multi-Dimensional====
Read the 2nd line, column 5
<syntaxhighlight lang="php">echo $MultiArray[1][5]; // 2</syntaxhighlight>
===Print a whole array===
This is useful while developing to view the contents of an array:
<syntaxhighlight lang="php">print_r($MultiArray);</syntaxhighlight>
Which would give us:
<syntaxhighlight lang="php">Array(
0 => array(
0 => 0
Line 6,130:
=== Set custom keys for values===
This example starts the indexing from 1 instead of 0
<syntaxhighlight lang="php">$StartIndexAtOne = array(1 => "A", "B", "C", "D");</syntaxhighlight>
This example shows how you can apply any key you want
<syntaxhighlight lang="php">$CustomKeyArray = array("d" => "A", "c" => "B", "b" =>"C", "a" =>"D");</syntaxhighlight>
 
To read the 3rd value of the second array:
<syntaxhighlight lang="php">echo $CustomKeyArray["b"]; // Returns C</syntaxhighlight>
 
===Other Examples===
Create a blank array:
<syntaxhighlight lang="php">$BlankArray = array();</syntaxhighlight>
 
Set a value for the next key in the array:
<syntaxhighlight lang="php">$BlankArray[] = "Not Blank Anymore";</syntaxhighlight>
 
Assign a value to a certain key:
<syntaxhighlight lang="php">$AssignArray["CertainKey"] = "Value";</syntaxhighlight>
 
=={{header|Picat}}==
Line 6,151:
 
Here are some examples how to use arrays.
<syntaxhighlight lang=Picat"picat">import util.
 
go =>
Line 6,218:
 
{{trans|Prolog}}
<syntaxhighlight lang=Picat"picat">listvariant :-
List = new_list(5), % create a list of length 5
nth(1,List,a), % put an a at position 1 , nth/3 uses indexing from 1
Line 6,244:
=={{header|PicoLisp}}==
PicoLisp has no built-in array data type. Lists are used instead.
<syntaxhighlight lang=PicoLisp"picolisp">(setq A '((1 2 3) (a b c) ((d e) NIL 777))) # Create a 3x3 structure
(mapc println A) # Show it</syntaxhighlight>
{{out}}
Line 6,251:
((d e) NIL 777)</pre>
Replace 'b' with 'B' in middle row:
<syntaxhighlight lang=PicoLisp"picolisp">(set (nth A 2 2) 'B)
(mapc println A)</syntaxhighlight>
{{out}}
Line 6,258:
((d e) NIL 777)</pre>
Insert '1' in front of the middle row:
<syntaxhighlight lang=PicoLisp"picolisp">(push (cdr A) 1)
(mapc println A)</syntaxhighlight>
{{out}}
Line 6,265:
((d e) NIL 777)</pre>
Append '9' to the middle row:
<syntaxhighlight lang=PicoLisp"picolisp">(queue (cdr A) 9)
(mapc println A)</syntaxhighlight>
{{out}}
Line 6,273:
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">int main(){
// Initial array, few random elements.
array arr = ({3,"hi",84.2});
Line 6,283:
 
=={{header|PL/I}}==
<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);
 
Line 6,308:
Arrays are a bit of a sticking point for Plain English, because its creators have not as yet devised a sufficiently elegant way to work with them within the constraints of the language. Only lists have high-level routine support. Nevertheless, the capability to build arrays ourselves exists within the language. Following is an example of how it could be done.
 
<syntaxhighlight lang="plainenglish">To run:
Start up.
Write "Creating an array of 100 numbers..." on the console.
Line 6,366:
 
Arrays are homogenous.
<syntaxhighlight lang=Pony"pony">use "assert" // due to the use of Fact
 
- - -
Line 6,385:
 
=={{header|PostScript}}==
<syntaxhighlight lang="text">
%Declaring array
 
Line 6,406:
=={{header|PowerShell}}==
Empty array:
<syntaxhighlight lang="powershell">$a = @()</syntaxhighlight>
Array initialized with only one member:
<syntaxhighlight lang="powershell">$a = ,2
$a = @(2) # alternative</syntaxhighlight>
Longer arrays can simply be created by separating the values with commas:
<syntaxhighlight lang="powershell">$a = 1,2,3</syntaxhighlight>
A value can be appended to an array using the <code>+=</code> operator:
<syntaxhighlight lang="powershell">$a += 5</syntaxhighlight>
Since arrays are immutable this simply creates a new array containing one more member.
 
Values can be retrieved using a fairly standard indexing syntax:
<syntaxhighlight lang="powershell">$a[1]</syntaxhighlight>
Similarly, those values can also be replaced:
<syntaxhighlight lang="powershell">$a[1] = 42</syntaxhighlight>
The range operator <code>..</code> can be used to create contiguous ranges of integers as arrays:
<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:
<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:
<syntaxhighlight lang="powershell">$r[-1] # last index</syntaxhighlight>
 
=={{header|Prolog}}==
Line 6,434:
retrieve and set elements.
 
<syntaxhighlight lang="prolog">
singleassignment:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
Line 6,449:
programming languages, setarg/3 can be used.
 
<syntaxhighlight lang="prolog">
destructive:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
Line 6,462:
Lists can be used as arrays.
 
<syntaxhighlight lang="prolog">
listvariant:-
length(List,100), % create a list of length 100
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.
 
<syntaxhighlight lang=PureBasic"purebasic"> ;Set up an Array of 23 cells, e.g. 0-22
Dim MyArray.i(22)
MyArray(0) = 7
Line 6,484:
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.
<syntaxhighlight lang=PureBasic"purebasic"> ;Extend the Array above to 56 items without affecting the already stored data
ReDim MyArray(55)
MyArray(22) = 7
MyArray(33) = 11
MyArray(44) = 23</syntaxhighlight>
<syntaxhighlight lang=PureBasic"purebasic"> ;Find all 6 non-zero cells from the Array above
For i=0 To ArraySize(MyArray())
If MyArray(i)
Line 6,495:
EndIf
Next</syntaxhighlight>
<syntaxhighlight lang=PureBasic"purebasic"> ; Now, set up a multi dimensional Array
Dim MultiArray.i(800, 600)
MultiArray(100, 200) = 640
MultiArray(130, 40) = 120</syntaxhighlight>
<syntaxhighlight lang=PureBasic"purebasic">Dim MultiArray2.i(64, 128, 32)
PrintN( Str(ArraySize(MultiArray2(), 2)) ; Will tell that second dimension size is '128'</syntaxhighlight>
 
=={{header|Python}}==
Python lists are dynamically resizeable.
<syntaxhighlight lang="python">array = []
 
array.append(1)
Line 6,515:
A simple, single-dimensional array can also be initialized thus:
 
<syntaxhighlight lang="python">myArray = [0] * size</syntaxhighlight>
 
However this will not work as intended if one tries to generalize from the syntax:
 
<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.
Line 6,525:
To initialize a list of lists one could use a pair of nested list comprehensions like so:
 
<syntaxhighlight lang="python">myArray = [[0 for x in range(width)] for y in range(height)]</syntaxhighlight>
 
That is equivalent to:
 
<syntaxhighlight lang="python">myArray = list()
for x in range(height):
myArray.append([0] * width)</syntaxhighlight>
Line 6,535:
To retrieve an element in an array, use any of the following methods:
 
<syntaxhighlight lang="python">
# Retrieve an element directly from the array.
item = array[index]
Line 6,548:
 
Python produces an IndexError when accessing elements out of range:
<syntaxhighlight lang="python">
try:
# This will cause an exception, which will then be caught.
Line 6,558:
 
=={{header|QB64}}==
<syntaxhighlight lang=QB64"qb64">
'Task
'Show basic array syntax in your language.
Line 6,749:
Dynamic
 
<syntaxhighlight lang=R"r">arr <- array(1)
 
arr <- append(arr,3)
Line 6,758:
 
=={{header|Racket}}==
<syntaxhighlight lang=Racket"racket">#lang racket
 
;; import dynamic arrays
Line 6,776:
At its most basic, an array in Raku is quite similar to an array in Perl 5.
 
<syntaxhighlight lang=perl6"raku" line>my @arr;
push @arr, 1;
Line 6,854:
 
=={{header|REBOL}}==
<syntaxhighlight lang=REBOL"rebol">
a: [] ; Empty.
b: ["foo"] ; Pre-initialized.
Line 6,861:
Inserting and appending.
 
<syntaxhighlight lang=REBOL"rebol">
append a ["up" "down"] ; -> ["up" "down"]
insert a [left right] ; -> [left right "up" "down"]
Line 6,868:
Getting specific values.
 
<syntaxhighlight lang=REBOL"rebol">
first a ; -> left
third a ; -> "up"
Line 6,879:
you can even assign to it without destroying the list.
 
<syntaxhighlight lang=REBOL"rebol">
a ; -> [left right "up" "down"]
next a ; -> [right "up" "down"]
Line 6,893:
 
=={{header|Red}}==
<syntaxhighlight lang=Red"red">arr1: [] ;create empty array
arr2: ["apple" "orange" 1 2 3] ;create an array with data
>> insert arr1 "blue"
Line 6,911:
The allowable item types are: integer! float! char! percent!
Vectors of string! are not allowed.
<syntaxhighlight lang=Red"red">>> vec1: make vector! [ 20 30 70]
== make vector! [20 30 70]
>> vec1/2
Line 6,930:
=={{header|ReScript}}==
 
<syntaxhighlight lang=ReScript"rescript">let arr = [1, 2, 3]
 
let _ = Js.Array2.push(arr, 4)
Line 6,947:
Retro has a vocabulary for creating and working with arrays.
 
<syntaxhighlight lang=Retro"retro">
needs array'
 
Line 6,989:
 
===simple arrays===
<syntaxhighlight lang="rexx">/*REXX program demonstrates a simple array usage. */
a.='not found' /*value for all a.xxx (so far).*/
do j=1 to 100 /*start at 1, define 100 elements*/
Line 7,005:
 
===simple arrays, mimic other languages===
<syntaxhighlight lang="rexx">/*REXX program demonstrates array usage with mimicry. */
a. = 'not found' /*value for all a.xxx (so far). */
do j=1 to 100 /*start at 1, define 100 elements*/
Line 7,022:
 
===simple arrays, assigned default===
<syntaxhighlight lang="rexx">/*REXX program demonstrates array usage with mimicry. */
a. = 00 /*value for all a.xxx (so far). */
do j=1 to 100 /*start at 1, define 100 elements*/
Line 7,040:
 
===arrays with non-unity index start===
<syntaxhighlight lang="rexx">/*REXX program demonstrates array usage (with elements out-of-range).*/
array. = 'out of range' /*define ALL elements to this. */
 
Line 7,057:
 
===arrays, disjoint===
<syntaxhighlight lang="rexx">/*REXX program demonstrates disjointed array usage. */
yr. = 'year not supported' /*value for all yr.xxx (so far).*/
 
Line 7,081:
 
===sparse arrays and special indices===
<syntaxhighlight lang="rexx">/*REXX program demonstrates array usage: sparse and disjointed. */
yyy = -55 /*REXX must use this mechanism···*/
a.yyy = 1e9 /*··· when assigning neg indices.*/
Line 7,113:
Dynamic
 
<syntaxhighlight lang="ring"># create an array with one string in it
a = ['foo']
 
Line 7,126:
 
=={{header|RLaB}}==
<syntaxhighlight lang=RLaB"rlab">
// 1-D (row- or column-vectors)
// Static:
Line 7,163:
Robotic does not natively support arrays of any kind.
However, using [https://www.digitalmzx.net/wiki/index.php?title=Counter_interpolation Counter Interpolation], we can create a simple (faux) array.
<syntaxhighlight lang="robotic">
set "index" to 0
. "Assign random values to array"
Line 7,176:
 
You can even create multi-dimensional arrays using the Counter Interpolation method.
<syntaxhighlight lang="robotic">
set "xx" to 0
set "yy" to 0
Line 7,198:
{{works with|ILE RPG}}
 
<syntaxhighlight lang="rpg">
//-Static array
//--def of 10 el array of integers, initialised to zeros
Line 7,232:
Dynamic
 
<syntaxhighlight lang="ruby"># create an array with one object in it
a = ['foo']
 
Line 7,254:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">print "Enter array 1 greater than 0"; : input a1
print "Enter array 2 greater than 0"; : input a2
Line 7,270:
By default, arrays are immutable unless defined otherwise.
 
<syntaxhighlight lang="rust">let a = [1, 2, 3]; // immutable array
let mut m = [1, 2, 3]; // mutable array
let zeroes = [0; 200]; // creates an array of 200 zeroes</syntaxhighlight>
Line 7,276:
To get the length and iterate,
 
<syntaxhighlight lang="rust">let a = [1, 2, 3];
a.len();
for e in a.iter() {
Line 7,284:
Accessing a particular element uses subscript notation, starting from 0.
 
<syntaxhighlight lang="rust">let names = ["Graydon", "Brian", "Niko"];
names[1]; // second element</syntaxhighlight>
 
Dynamic arrays in Rust are called vectors.
 
<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.
 
<syntaxhighlight lang="rust">let mut v = vec![1, 2, 3];
v.push(4);
v.len(); // 4</syntaxhighlight>
 
=={{header|Sather}}==
<syntaxhighlight lang="sather">-- a is an array of INTs
a :ARRAY{INT};
-- create an array of five "void" elements
Line 7,313:
=={{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.
<syntaxhighlight lang="scala">// Create a new integer array with capacity 10
val a = new Array[Int](10)
 
Line 7,325:
val c = b(2)</syntaxhighlight>
Dynamic arrays can be made using <code>ArrayBuffer</code>s:
<syntaxhighlight lang="scala">val a = new collection.mutable.ArrayBuffer[Int]
a += 5 // Append value 5 to the end of the list
a(0) = 6 // Assign value 6 to element 0</syntaxhighlight>
Line 7,332:
Lists are more often used in Scheme than vectors.
 
<syntaxhighlight lang="scheme">(let ((array #(1 2 3 4 5)) ; vector literal
(array2 (make-vector 5)) ; default is unspecified
(array3 (make-vector 5 0))) ; default 0
Line 7,348:
Every type, which can be mapped to integer, can be used as index type.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: charArray is array [char] string; # Define an array type for arrays with char index.
Line 7,390:
Creating simple vectors:
<syntaxhighlight lang="self">vector copySize: 100</syntaxhighlight>
<syntaxhighlight lang="self">vector copySize: 100 FillingWith: anObject</syntaxhighlight>
 
A polymorphic vector:
<syntaxhighlight lang="self">(1 & 'Hello' & 2.0 & someObject) asVector</syntaxhighlight>
 
Using a vector:
<syntaxhighlight lang="self">|v|
"creates an vector that holds up to 20 elements"
v: vector copySize: 20.
Line 7,408:
 
Enumeration:
<syntaxhighlight lang="self">v do: [:each | each printLine].
v copy mapBy: [:each | each squared].
v copy filterBy: [:each | each > 10].</syntaxhighlight>
 
Using a squence:
<syntaxhighlight lang="self">|s|
"creates a new sequence"
s: sequence copyRemoveAll.
Line 7,426:
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">// Initial creation of an array
set a to (1, 2, 3)
 
Line 7,457:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby"># create an empty array
var arr = [];
 
Line 7,488:
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
PROCEDURE STATIC;
Line 7,530:
</pre>
One can write an ArrayList class like Java has in package java.util.
<syntaxhighlight lang="simula">BEGIN
 
CLASS ITEM;;
Line 7,763:
 
=={{header|Slate}}==
<syntaxhighlight lang="slate">slate[1]> #x := ##(1 2 3).
{1. 2. 3}
slate[2]> x
Line 7,787:
Literal Arrays (Array constants):
<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.
 
Programatic use:
<syntaxhighlight lang="smalltalk">|array|
"creates an array that holds up to 20 elements"
array := Array new: 20 .
Line 7,804:
array at: 2 put: 'orange'.</syntaxhighlight>
 
<syntaxhighlight lang="smalltalk">"assigning values to an array"
"suppose array is bound to an array of 20 values"
array at: 5 put: 'substitute fifth element'.
Line 7,812:
do: [ :sig | 'Out of range!' displayNl ].</syntaxhighlight>
 
<syntaxhighlight lang="smalltalk">"retrieving a value from an array"
#($a $b $c) at: 2</syntaxhighlight>
 
Enumeration:
<syntaxhighlight lang="smalltalk">array do:[:each | each printOn: aStream ]
array collect:[:each | each squared|
array select:[:each | each > 10]</syntaxhighlight>
Line 7,824:
{{works with|Squeak}}
Constructing an Array from evaluated expressions:
<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.
 
OrderedCollection:
<syntaxhighlight lang="smalltalk">oc := OrderedCollection withAll: #(4 5 6).
oc add:1. oc add:2. oc add:3.
foo := oc removeFirst.
Line 7,844:
=={{header|SNOBOL4}}==
SNOBOL4 supports multi-dimensional arrays and array initialization.
<syntaxhighlight lang=SNOBOL4"snobol4"> ar = ARRAY("3,2") ;* 3 rows, 2 columns
fill i = LT(i, 3) i + 1 :F(display)
ar<i,1> = i
Line 7,862:
 
=={{header|SPL}}==
<syntaxhighlight lang="spl">a[1] = 2.5
a[2] = 3
a[3] = "Result is "
Line 7,901:
done: ; program continues</pre>
We are now in a position to translate this algorithm into SSEM instructions and run it. As always, the SSEM version is a bit fiddlier than the pseudocode because the SSEM has no <tt>load</tt> or <tt>add</tt> instructions; but it follows the pseudocode as closely as the instruction set allows, so it should be comparatively readable. As a test, we shall sum an array of the first four positive integers—a very significant operation for the Pythagoreans of old—and halt with the accumulator holding the result.
<syntaxhighlight lang="ssem">10101000000000100000000000000000 0. -21 to c
11101000000000010000000000000000 1. Sub. 23
00101000000001100000000000000000 2. c to 20
Line 7,931:
 
=={{header|Standard ML}}==
<syntaxhighlight lang=Standard"standard MLml">
(* create first array and assign elements *)
-val first = Array.tabulate (10,fn x=>x+10) ;
Line 7,957:
 
=== Matrix command ===
<syntaxhighlight lang="stata">matrix a = 2,9,4\7,5,3\6,1,8
display det(a)
matrix svd u d v = a
Line 7,967:
 
=== Mata ===
<syntaxhighlight lang="stata">mata
a = 2,9,4\7,5,3\6,1,8
det(a)
Line 7,976:
 
=={{header|Suneido}}==
<syntaxhighlight lang=Suneido"suneido">array = Object('zero', 'one', 'two')
array.Add('three')
array.Add('five', at: 5)
Line 7,983:
 
=={{header|Swift}}==
<syntaxhighlight lang=Swift"swift">// Arrays are typed in Swift, however, using the Any object we can add any type. Swift does not support fixed length arrays
var anyArray = [Any]()
anyArray.append("foo") // Adding to an Array
Line 7,991:
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
// arrays are created as literals, by simply listing elements, or by a generator expression, or a combination.
def a: [1, 2, 3..7:2, 11];
Line 8,028:
=={{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.)
<syntaxhighlight lang="tcl">set ary {}
 
lappend ary 1
Line 8,037:
puts [lindex $ary 0]</syntaxhighlight>
Note also that serialization is automatic on treating as a string:
<syntaxhighlight lang="tcl">puts $ary; # Print the whole array</syntaxhighlight>
 
=={{header|Tern}}==
Arrays and lists are synonymous in Tern.
<syntaxhighlight lang="tern">let list = [1, 22, 3, 24, 35, 6];
 
for(i in list) {
Line 8,060:
<br>'''List'''<br>
One dimensional arrays are lists, they can be set as a whole with the syntax:
<syntaxhighlight lang="ti83b">{1,2,3,4,5}→L1</syntaxhighlight>
using only numerical values separated by commas and enclosed by curly braces.<br>
Lists can be accessed as a whole using L1-L6 or a custom list name
Line 8,066:
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.
<syntaxhighlight lang="ti83b">{1,2,3,4,5}→L1
Disp L1(3)
0→L1(4)</syntaxhighlight>
This would return 3 and set the fourth list element to 0.
<br>You can dynamically define or delete lists by:
<syntaxhighlight lang="ti83b">20→dim(L1)
DelVar L1
5→dim(∟MYLIST)
Line 8,077:
'''Matrix'''<br>
Two dimensional arrays are matrices. Similar, set them and retrieve numbers using the syntax:
<syntaxhighlight lang="ti83b">[[11,21,31,41][12,22,32,42][13,23,33,43]]→[A]
Disp [A](1,3)
0→[A](4,2)</syntaxhighlight>
This would return 13 and set the element (4,2) to 0.
<br>You can dynamically define or delete matrices by:
<syntaxhighlight lang="ti83b">{5,5}→dim([A])
DelVar [A]</syntaxhighlight>
 
Line 8,088:
Arrays in TorqueScript:
 
<syntaxhighlight lang=TorqueScript"torquescript">
$array[0] = "hi";
$array[1] = "hello";
Line 8,099:
=> hello
 
<syntaxhighlight lang=TorqueScript"torquescript">
$array["Greet",0] = "hi";
$array["Greet",1] = "hello";
Line 8,117:
Vectors can be created as empty containers, or they can be initialized with some values at the time of creation.
 
<syntaxhighlight lang=Scheme"scheme">module1 : {
v1: Vector<Int>(),
v2: Vector<String>(),
Line 8,129:
Individual elements in a vector can be read, appended, and deleted.
 
<syntaxhighlight lang=Scheme"scheme">(with v [1,2,3]
(textout (get v 1)) // <= 2
(erase v 1)
Line 8,139:
All standard container operations can be applied to vectors:
 
<syntaxhighlight lang=Scheme"scheme">(with v [3,1,5,2,4]
(textout (reverse v)) // <= [4, 2, 5, 1, 3]
(textout (sort v)) // <= [1, 2, 3, 4, 5]
Line 8,210:
A complete program which turns comma-separated into tab-separated,
where the first and last field from each line are exchanged:
<syntaxhighlight lang="txr">@(collect)
@line
@(bind f @(split-str line ","))
Line 8,226:
=={{header|uBasic/4tH}}==
uBasic/4tH has only one single, global array of 256 integers. Since it's fixed, it can't be declared.
<syntaxhighlight lang="text">Let @(0) = 5 : Print @(0)</syntaxhighlight>
 
=={{header|Unicon}}==
Unicon's arrays are provided by the list type, which is a hybrid list/array type.
Lists of integers or reals, if not polluted by other types nor changed in size, may use a C-compatible internal representation (long and double).
<syntaxhighlight lang="text">L := list(100); L[12] := 7; a := array(100, 0.0); a[3] +:= a[1]+a[2]</syntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 8,241:
 
To create an array:
<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 list3[0] # empty list called "list3"; the subscript is ignored
Line 8,248:
list5=([3]=apple [2]=cherry [1]=banana [0]=strawberry)</syntaxhighlight>
To obtain the number of items in an array:
<syntaxhighlight lang="bash">count=${#alist[*]}
echo "The number of items in alist is ${#alist[*]}"</syntaxhighlight>
To iterate up over the items in the array:
<syntaxhighlight lang="bash">x=0
while [[ $x < ${#alist[*]} ]]; do
echo "Item $x = ${alist[$x]}"
Line 8,257:
done</syntaxhighlight>
To iterate down over theitems in an array:
<syntaxhighlight lang="bash">x=${#alist[*]} # start with the number of items in the array
while [[ $x > 0 ]]; do # while there are items left
: $((x--)) # decrement first, because indexing is zero-based
Line 8,263:
done</syntaxhighlight>
To append to an array, use the current number of items in the array as the next index:
<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:
<syntaxhighlight lang="bash"># shell function to append values to an array
# push LIST VALUES ...
push() {
Line 8,276:
push alist many words to add</syntaxhighlight>
To delete a single array item, the first item:
<syntaxhighlight lang="bash">unset alist[0]</syntaxhighlight>
To delete and return the last item in an array (e.g., "pop" function):
<syntaxhighlight lang="bash"># pop ARRAY -- pop the last item on ARRAY and output it
 
pop() {
Line 8,302:
No items in alist</syntaxhighlight>
To delete all the items in an array:
<syntaxhighlight lang="bash">unset alist[*]</syntaxhighlight>
To delete the array itself (and all items in it, of course):
<syntaxhighlight lang="bash">unset alist</syntaxhighlight>
 
=={{header|உயிர்/Uyir}}==
<syntaxhighlight lang="உயிர்/Uyiruyir">
இருபரிமாணணி வகை எண் அணி {3, 3};
இருபரிமாணணி2 வகை எண் அணி {3} அணி {3};
Line 8,321:
=={{header|Vala}}==
Non-dynamic arrays:
<syntaxhighlight lang="vala">
int[] array = new int[10];
 
Line 8,332:
{{libheader|Gee}}
Dynamic Arrays with Gee:
<syntaxhighlight lang="vala">
var array = new ArrayList<int> ();
 
Line 8,345:
=={{header|VBA}}==
The Option Base statement is used at the module level to declare the default lower bound for array subscripts.
<syntaxhighlight lang="vb">Option Base {0|1} </syntaxhighlight>
<syntaxhighlight lang="vb">Sub matrix()
'create an array,
Dim a(3) As Integer
Line 8,379:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">'Arrays - VBScript - 08/02/2021
 
'create a static array
Line 8,434:
 
=={{header|VHDL}}==
<syntaxhighlight lang=VHDL"vhdl">
entity Array_Test is
end entity Array_Test;
Line 8,496:
=={{header|Vim Script}}==
Lists can be used for dynamic arrays. Indexing starts at 0.
<syntaxhighlight lang="vim">" Creating a dynamic array with some initial values
let array = [3, 4]
 
Line 8,520:
 
=={{header|Visual Basic .NET}}==
<syntaxhighlight lang="vbnet">'Example of array of 10 int types:
Dim numbers As Integer() = New Integer(9) {}
'Example of array of 4 string types:
Line 8,553:
 
=={{header|Vlang}}==
<syntaxhighlight lang="go">// Arrays, in V
// Tectonics: v run arrays.v
module main
Line 8,627:
 
=={{header|Wee Basic}}==
<syntaxhighlight lang=Wee"wee Basicbasic">dim array$(2)
let array$(1)="Hello!"
let array$(2)="Goodbye!"
Line 8,633:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascript">var arr = []
arr.add(1)
arr.add(2)
Line 8,649:
 
=={{header|X86 Assembly}}==
<syntaxhighlight lang="asm">
section .text
global _start
Line 8,734:
=={{header|XBS}}==
Arrays in [[XBS]] are very similar to [[JavaScript]].
<syntaxhighlight lang=XBS"xbs">set Array = ["Hello","World"];
log(Array[0]);
Array.push("Test");
Line 8,742:
=={{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):
<syntaxhighlight lang="scheme">[1] (define a (make-vector 10)) ; vector of 10 elements initialized to the empty list
 
A
Line 8,768:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\codes;
char A(10); \creates a static array of 10 bytes, pointed to by "A"
char B; \declares a variable for a pointer to a dynamic array
Line 8,778:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">dim a(10) // create a numeric array with 11 elements, from 0 to 10
// Indexed at your preference (0 to 9 or 1 to 10)
print arraysize(a(), 1) // this function return the element's higher number of an array
Line 8,810:
 
An array is nothing more than a contiguous section of memory. Whether an array is mutable or not is solely determined by whether its memory location is in ROM or RAM.
<syntaxhighlight lang="z80">Array: ;an array located in RAM. Its values can be updated freely.
byte 0,0,0,0,0
byte 0,0,0,0,0
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:
<syntaxhighlight lang="z80">Array:
byte 0,0,0,0,0
byte 0,0,20,0,0
Line 8,829:
 
 
<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.
Line 8,848:
In the example below, we wish to load the 13th (zero-indexed) element from the array MyTable.
 
<syntaxhighlight lang="z80">LD H,>MyTable ;works out to be LD h,4 thanks to our alignment below.
;>LABEL means "the high byte of the address represented by LABEL
LD L,13 ;this was a lot faster than doing LD HL,&0400 and adding the desired index later.
Line 8,865:
 
That might have been a bit confusing, so let's visualize the concept. Here's a practical example of storing a sine wave pattern. Instead of storing 16-bit data together like you normally would:
<syntaxhighlight lang="z80">org &0400
word &8000,&8327,&864e,&8973,&8c98,&8fba,&92da,&95f7
word &9911,&9c27,&9f38,&a244,&a54c,&a84d,&ab48,&ae3c
Line 8,872:
 
You can instead store it like this:
<syntaxhighlight lang="z80">org &0400
byte <&8000,<&8327,<&864e,<&8973,<&8c98,<&8fba,<&92da,<&95f7
byte <&9911,<&9c27,<&9f38,<&a244,<&a54c,<&a84d,<&ab48,<&ae3c
Line 8,886:
 
So let's say we want to read the last entry in "the table".
<syntaxhighlight lang="z80">LD h,&04 ;load high byte of address &0400
LD L,&1F ;desired index
ld a,(hl)
Line 8,898:
=={{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.
<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[3]=4;
Line 8,905:
 
=={{header|zonnon}}==
<syntaxhighlight lang="pascal">
var
a: array 10 of integer;
Line 8,912:
 
=={{header|ZX Spectrum Basic}}==
<syntaxhighlight lang="zxbasic">10 DIM a(5)
20 LET a(2)=128
30 PRINT a(2)</syntaxhighlight>
10,327

edits