Create a two-dimensional array at runtime: Difference between revisions

m
m (→‎{{header|S-BASIC}}: added comment)
 
(35 intermediate revisions by 24 users not shown)
Line 4:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">V width = 3
V height = 5
V myarray = [[0] * width] * height
print(myarray[height-1][width-1])</langsyntaxhighlight>
=={{header|68000 Assembly}}==
The routine used to retrieve the input is left unimplemented.
<langsyntaxhighlight lang="68000devpac">;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Array setup
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 96:
DBRA D7,loop_destroyArray ;loop using bottom 2 bytes of the array size as a loop counter
DBRA D6,loop_destroyArray ;decrement this, D7 is $FFFF each time execution gets here so this acts as a "carry" of sorts.
;if this value was 0 prior to the loop, the loop ends immediately.</langsyntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program createarray264.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 64
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRead1: .asciz "Input size level 1 : "
szMessRead2: .asciz "Input size level 2 : "
szMessIndice1: .asciz "Indice 1 ="
szMessIndice2: .asciz " Indice 2 ="
szMessResult: .asciz " Item = "
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip BUFFERSIZE // conversion buffer
sZoneConv1: .skip BUFFERSIZE // conversion buffer
sZoneConv2: .skip BUFFERSIZE // conversion buffer
sBuffer: .skip BUFFERSIZE
 
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
ldr x0,qAdrszMessRead1
bl affichageMess
mov x0,#STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8,READ
svc 0 // call system
ldr x0,qAdrsBuffer // buffer address
bl conversionAtoD
mov x9,x0
ldr x0,qAdrszMessRead2
bl affichageMess
mov x0,#STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8,READ
svc 0 // call system
ldr x0,qAdrsBuffer // buffer address
bl conversionAtoD
mov x10,x0
// create array
lsl x12,x10,#3 // compute size level 2
mul x8,x12,x9 // compute size array
tst x8,0xF // multiple of 16 ?
add x11,x8,8 // if no add 8 octets
csel x8,x8,x11,eq // the stack must always be aligned on 16 bytes
// in 64 assembly arm
sub sp,sp,x8 // reserve place on stack
mov fp,sp // save array address
mov x0,#0 // init all items array
1: // begin loop1
mov x1,#0
2: // begin loop2
mul x2,x0,x12
add x2,x2,x1, lsl #3
str x2,[fp,x2] // store shift in array item
add x1,x1,#1
cmp x1,x10
blt 2b
add x0,x0,#1
cmp x0,x9
blt 1b
mov x0,fp
mov x1,#1 // second indice level 1
mov x2,#0 // first indice level 2
mov x3,x12 // level 2 size
bl displayItem
mov x0,fp
sub x1,x9,#1 // last level 1
sub x2,x10,#1 // last level 2
mov x3,x12 // level 2 size
bl displayItem
 
add sp,sp,x8 // release space on stack
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrsZoneConv1: .quad sZoneConv1
qAdrsZoneConv2: .quad sZoneConv2
qAdrszMessRead1: .quad szMessRead1
qAdrszMessRead2: .quad szMessRead2
qAdrsBuffer: .quad sBuffer
qAdrszMessResult: .quad szMessResult
qAdrszMessStart: .quad szMessStart
qAdrszMessIndice1: .quad szMessIndice1
qAdrszMessIndice2: .quad szMessIndice2
/***************************************************/
/* display array item */
/***************************************************/
/* x0 array address */
/* x1 indice 1 */
/* x2 indice 2 */
/* x3 level 2 size */
displayItem:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,fp,[sp,-16]! // save registers
mov x5,x0
mov x6,x1
mov x0,x6
ldr x1,qAdrsZoneConv
bl conversion10 // conversion indice 1
mov x0,x2
ldr x1,qAdrsZoneConv1
bl conversion10 // conversion indice 2
mul x4,x6,x3 // multiply indice level 1 by level 2 size
add x4,x4,x2, lsl #3 // add indice level 2 * 8 (8 bytes)
ldr x0,[x5,x4] // load array item
ldr x1,qAdrsZoneConv2
bl conversion10
mov x0,#7 // string number to display
ldr x1,qAdrszMessIndice1
ldr x2,qAdrsZoneConv // insert conversion in message
ldr x3,qAdrszMessIndice2
ldr x4,qAdrsZoneConv1 // insert conversion in message
ldr x5,qAdrszMessResult
ldr x6,qAdrsZoneConv2 // insert conversion in message
ldr x7,qAdrszCarriageReturn
bl displayStrings // display message
100:
ldp x6,fp,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* display multi strings */
/* new version 24/05/2023 */
/***************************************************/
/* x0 contains number strings address */
/* x1 address string1 */
/* x2 address string2 */
/* x3 address string3 */
/* x4 address string4 */
/* x5 address string5 */
/* x6 address string5 */
/* x7 address string6 */
displayStrings: // INFO: displayStrings
stp x8,lr,[sp,-16]! // save registers
stp x2,fp,[sp,-16]! // save registers
add fp,sp,#32 // save paraméters address (4 registers saved * 8 bytes)
mov x8,x0 // save strings number
cmp x8,#0 // 0 string -> end
ble 100f
mov x0,x1 // string 1
bl affichageMess
cmp x8,#1 // number > 1
ble 100f
mov x0,x2
bl affichageMess
cmp x8,#2
ble 100f
mov x0,x3
bl affichageMess
cmp x8,#3
ble 100f
mov x0,x4
bl affichageMess
cmp x8,#4
ble 100f
mov x0,x5
bl affichageMess
cmp x8,#5
ble 100f
mov x0,x6
bl affichageMess
cmp x8,#6
ble 100f
mov x0,x7
bl affichageMess
100:
ldp x2,fp,[sp],16 // restaur registers
ldp x8,lr,[sp],16 // restaur registers
ret
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
Input size level 1 : 10
Input size level 2 : 10
Indice 1 =1 Indice 2 =0 Item = 80
Indice 1 =9 Indice 2 =9 Item = 792
</pre>
=={{header|Action!}}==
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT
 
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
 
DEFINE PTR="CARD"
DEFINE INT_SIZE="2"
DEFINE CARD_SIZE="2"
TYPE IntArray2D=[BYTE rows,cols PTR p]
 
BYTE FUNC GetNumber(CHAR ARRAY s)
BYTE n,min=[1],max=[100]
 
DO
PrintF("Get number of %S (%B..%B): ",s,min,max)
n=InputB()
IF n>=min AND n<=max THEN
EXIT
FI
OD
RETURN (n)
 
PROC Create(IntArray2D POINTER a)
PTR ARRAY rowArray
BYTE row
 
IF a.p#0 THEN Break() FI
rowArray=Alloc(a.rows*CARD_SIZE)
a.p=rowArray
FOR row=0 TO a.rows-1
DO
rowArray(row)=Alloc(a.cols*INT_SIZE)
OD
RETURN
 
PROC Destroy(IntArray2D POINTER a)
PTR ARRAY rowArray
BYTE row
 
IF a.p=0 THEN Break() FI
rowArray=a.p
FOR row=0 TO a.rows-1
DO
Free(rowArray(row),a.cols*INT_SIZE)
OD
Free(a.p,a.rows*CARD_SIZE)
a.p=0
RETURN
 
PROC SetValue(IntArray2D POINTER a BYTE row,col INT v)
PTR ARRAY rowArray
INT ARRAY colArray
 
IF a.p=0 OR row>=a.rows OR col>=a.cols THEN
Break()
FI
rowArray=a.p
colArray=rowArray(row)
colArray(col)=v
RETURN
 
INT FUNC GetValue(IntArray2D POINTER a BYTE row,col)
PTR ARRAY rowArray
INT ARRAY colArray
 
IF a.p=0 OR row>=a.rows OR col>=a.cols THEN
Break()
FI
rowArray=a.p
colArray=rowArray(row)
RETURN (colArray(col))
 
PROC TestCreate(IntArray2D POINTER a)
PrintF("Create array of %B rows and %B cols%E",a.rows,a.cols)
Create(a)
RETURN
 
PROC TestDestroy(IntArray2D POINTER a)
PrintF("Destroy array of %B rows and %B cols%E",a.rows,a.cols)
Destroy(a)
RETURN
 
PROC TestSetValue(IntArray2D POINTER a BYTE row,col INT v)
PrintF("Write %I to row %B and col %B%E",v,row,col)
SetValue(a,row,col,v)
RETURN
 
PROC TestGetValue(IntArray2D POINTER a BYTE row,col)
INT v
 
v=GetValue(a,row,col)
PrintF("Read at row %B and col %B: %I%E",row,col,v)
RETURN
 
PROC Main()
IntArray2D a
 
Put(125) PutE() ;clear screen
AllocInit(0)
 
a.rows=GetNumber("rows")
a.cols=GetNumber("cols")
a.p=0
 
TestCreate(a)
TestSetValue(a,a.rows/2,a.cols/2,6502)
TestGetValue(a,a.rows/2,a.cols/2)
TestDestroy(a)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Create_a_two-dimensional_array_at_runtime.png Screenshot from Atari 8-bit computer]
<pre>
Get number of rows (1..100): 80
Get number of cols (1..100): 90
Create array of 80 rows and 90 cols
Write 6502 to row 40 and col 45
Read at row 40 and col 45: 6502
Destroy array of 80 rows and 90 cols
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">
with Ada.Text_Io;
with Ada.Float_Text_Io;
Line 120 ⟶ 460:
end;
-- The variable Matrix is popped off the stack automatically
end Two_Dimensional_Arrays;</langsyntaxhighlight>
{{omit from|Modula-2}}
 
=={{header|ALGOL 60}}==
<langsyntaxhighlight lang="algol60"> begin
comment Create a two-dimensional array at runtime - Algol 60;
integer n,m;
Line 136 ⟶ 476:
end;
comment array a : out of scope;
end </langsyntaxhighlight>
{{in}}
<pre>
Line 149 ⟶ 489:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">main:(
print("Input two positive whole numbers separated by space and press newline:");
[read int,read int] INT array;
array[1,1]:=42;
print (array[1,1])
)</langsyntaxhighlight>
 
=={{header|ALGOL-M}}==
<syntaxhighlight lang="ALGOL">
begin
 
integer first, second;
 
write("Two Dimensional Array Exercise");
write("Length of first dimension:");
read(first);
write("Length of second dimension:");
read(second);
 
begin % we need to start a new block %
integer array test[1:first, 1:second];
test[1,1] := 99;
write("Stored value at 1,1 =",test[1,1]);
end; % array is now out of scope %
 
end
</syntaxhighlight>
{{out}}
<pre>
Two Dimensional Array Exercise
Length of first dimension:
->6
Length of second dimension:
->7
Stored value at 1,1 = 99
</pre>
 
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
integer dimension1UpperBound, dimension2UpperBound;
write( "upper bound for dimension 1: " );
Line 178 ⟶ 549:
end
 
end.</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
Amazing Hopper crea arrays de forma dinámica.
<syntaxhighlight lang="amazing hopper">
#include <flow.h>
#import lib/input.bas.lib
#include include/flow-input.h
 
DEF-MAIN
CLR-SCR
MSET(nRow, nCol)
LOCATE( 2,5 ), PRN("Input size rows :")
LOC-COL( 23 ), LET( nRow := ABS(VAL(READ-NUMBER( nRow ) )))
LOCATE( 3,5 ), PRN("Input size cols :")
LOC-COL( 23 ), LET( nCol := ABS(VAL(READ-NUMBER( nCol ) )))
COND( IS-NOT-ZERO?( MUL(nRow,nCol) ) )
DIM(nRow, nCol) AS-VOID( array )
BLK-[1,1], {100} PUT(array)
PRNL("\tElement at position 1,1 : ", GET(array) )
CLEAR(array) /* destroy array */
CEND
END
SUBRUTINES
</syntaxhighlight>
{{out}}
<pre>
Input size rows : 30
Input size cols : 30
Element at position 1,1 : 100
</pre>
=={{header|APL}}==
Arrays are an integral part of APL. Array size, shape, and data type can be easily manipulated at runtime.
 
<langsyntaxhighlight APLlang="apl">array←m n ⍴ 0 ⍝ array of zeros with shape of m by n.
 
array[1;1]←73 ⍝ assign a value to location 1;1.
Line 190 ⟶ 591:
 
⎕ex 'array' ⍝ erase the array
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
AppleScript has no array, but an AppleScript list can be used in a multidimensional fashion. There's no issue with their dimensions, they grow while adding elements. Memory allocation is dynamic.
 
<langsyntaxhighlight AppleScriptlang="applescript">set R to text returned of (display dialog "Enter number of rows:" default answer 2) as integer
set c to text returned of (display dialog "Enter number of columns:" default answer 2) as integer
set array to {}
Line 219 ⟶ 620:
-- Destroy array (typically unnecessary since it'll automatically be destroyed once script ends).
set array to {}
</syntaxhighlight>
</lang>
 
To correct the last comment in the script above: when a script's run, the values of its properties, globals, and run-handler (''ie.'' top level) variables are saved back to the script file when the execution finishes. So variables containing bulky values like lists ideally ''should'' be set to something smaller before the end in order to prevent file bloat. Or local variables could be used, which would be the better option above as the <code>return</code> statement prevents the last line from being executed anyway.
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program createarray2.s */
 
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ STDIN, 0 @ Linux input console
.equ READ, 3 @ Linux syscall
.equ BUFFERSIZE, 64
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRead1: .asciz "Input size level 1 : "
szMessRead2: .asciz "Input size level 2 : "
szMessIndice1: .asciz "Indice 1 ="
szMessIndice2: .asciz "Indice 2 ="
szMessResult: .asciz "Item = "
szMessStart: .asciz "Program 32 bits start.\n"
szCarriageReturn: .asciz "\n"
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip BUFFERSIZE // conversion buffer
sZoneConv1: .skip BUFFERSIZE // conversion buffer
sZoneConv2: .skip BUFFERSIZE // conversion buffer
sBuffer: .skip BUFFERSIZE
 
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
ldr r0,iAdrszMessRead1
bl affichageMess
mov r0,#STDIN @ Linux input console
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7,#READ @ request to read datas
svc 0 @ call system
ldr r0,iAdrsBuffer @ buffer address
bl conversionAtoD
mov r9,r0
ldr r0,iAdrszMessRead2
bl affichageMess
mov r0,#STDIN @ Linux input console
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7,#READ @ request to read datas
svc 0 @ call system
ldr r0,iAdrsBuffer @ buffer address
bl conversionAtoD
mov r10,r0
@ create array
lsl r12,r10,#2 @ compute size level 2
mul r8,r12,r9 @ compute size array
sub sp,sp,r8 @ reserve place on stack
mov fp,sp
mov r0,#0 @ init all items array
1: @ begin loop1
mov r1,#0
2: @ begin loop2
mul r2,r0,r12
add r2,r2,r1, lsl #2
str r2,[fp,r2] @ store shift in array item
add r1,r1,#1
cmp r1,r10
blt 2b
add r0,r0,#1
cmp r0,r9
blt 1b
mov r0,fp
mov r1,#1 @ second indice level 1
mov r2,#0 @ first indice level 2
mov r3,r12 @ level 2 size
bl displayItem
mov r0,fp
sub r1,r9,#1 @ last level 1
sub r2,r10,#1 @ last level 2
mov r3,r12 @ level 2 size
bl displayItem
 
add sp,sp,r8 @ release space on stack
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrsZoneConv1: .int sZoneConv1
iAdrsZoneConv2: .int sZoneConv2
iAdrszMessRead1: .int szMessRead1
iAdrszMessRead2: .int szMessRead2
iAdrsBuffer: .int sBuffer
iAdrszMessResult: .int szMessResult
iAdrszMessStart: .int szMessStart
iAdrszMessIndice1: .int szMessIndice1
iAdrszMessIndice2: .int szMessIndice2
/***************************************************/
/* display array item */
/***************************************************/
/* r0 array address */
/* r1 indice 1 */
/* r2 indice 2 */
/* r3 level 2 size */
displayItem:
push {r1-r6,lr} @ save des registres
mov r5,r0
mov r6,r1
mov r0,r6
ldr r1,iAdrsZoneConv
bl conversion10 @ conversion indice 1
mov r0,r2
ldr r1,iAdrsZoneConv1
bl conversion10 @ conversion indice 2
mul r4,r6,r3 @ multiply indice level 1 by level 2 size
add r4,r4,r2, lsl #2 @ add indice level 2 * 4 (4 bytes)
ldr r0,[r5,r4] @ load array item
ldr r1,iAdrsZoneConv2
bl conversion10
mov r0,#7 @ string number to display
ldr r1,iAdrszMessIndice1
ldr r2,iAdrsZoneConv @ insert conversion in message
ldr r3,iAdrszMessIndice2
ldr r4,iAdrsZoneConv1 @ insert conversion in message
push {r4}
ldr r4,iAdrszMessResult
push {r4}
ldr r4,iAdrsZoneConv2 @ insert conversion in message
push {r4}
ldr r4,iAdrszCarriageReturn
push {r4}
bl displayStrings @ display message
add sp,sp,#16
100:
pop {r1-r6,pc}
/***************************************************/
/* display multi strings */
/***************************************************/
/* r0 contains number strings address */
/* r1 address string1 */
/* r2 address string2 */
/* r3 address string3 */
/* other address on the stack */
/* thinck to add number other address * 4 to add to the stack */
displayStrings: @ INFO: displayStrings
push {r1-r4,fp,lr} @ save des registres
add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes)
mov r4,r0 @ save strings number
cmp r4,#0 @ 0 string -> end
ble 100f
mov r0,r1 @ string 1
bl affichageMess
cmp r4,#1 @ number > 1
ble 100f
mov r0,r2
bl affichageMess
cmp r4,#2
ble 100f
mov r0,r3
bl affichageMess
cmp r4,#3
ble 100f
mov r3,#3
sub r2,r4,#4
1: @ loop extract address string on stack
ldr r0,[fp,r2,lsl #2]
bl affichageMess
subs r2,#1
bge 1b
100:
pop {r1-r4,fp,pc}
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
{{Out}}
<pre>
Program 32 bits start.
Input size level 1 : 10
Input size level 2 : 5
Indice 1 =1 Indice 2 =0 Item = 20
Indice 1 =9 Indice 2 =4 Item = 196
</pre>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
 
Line 235 ⟶ 841:
arr\[x]\[y]: 123
 
print ["item at [" x "," y "] =" arr\[x]\[y]]</langsyntaxhighlight>
 
{{out}}
Line 245 ⟶ 851:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">; == get dimensions from user input
$sInput = InputBox('2D Array Creation', 'Input comma separated count of rows and columns, i.e. "5,3"')
$aDimension = StringSplit($sInput, ',', 2)
Line 265 ⟶ 871:
MsgBox(0, 'Output', 'row[' & UBound($a2D) -1 & '], col[' & UBound($a2D, 2) -1 & ']' & @CRLF & '= ' & $a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] )
 
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
AWK has no multidimensional array; but AWK arrays (which are [[Associative array]] indeed) can be used also in a multidimensional fashion. Since AWK arrays are associative arrays, there's no issue in their dimensions: they grow while adding new key-value pair.
 
<langsyntaxhighlight lang="awk">/[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
Line 282 ⟶ 888:
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">10 INPUT "ENTER TWO INTEGERS:"; X%, Y%
20 DIM A%(X% - 1, Y% - 1)
30 X% = RND(1) * X%
Line 293 ⟶ 898:
50 A%(X%, Y%) = -32767
60 PRINT A%(X%, Y%)
70 CLEAR</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">arraybase 1
input integer "Enter one positive integer: ", i
input integer "Enter other positive integer: ", j
dim a(i, j)
a[i, j] = i * j
print "a("; string(i); ","; string(j); ") = "; a[i, j]
end</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">10 input "Enter two positive integers, separated by a comma? ";i,j
20 dim array(i,j)
30 array(i,j) = i*j
40 print "a(";str$(i);",";str$(j);") = ";array(i,j)
50 erase array</syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
<syntaxhighlight lang="qbasic">10 INPUT "Enter two positive integers, separated by a comma"; I, J
20 DIM ARRAY(I, J)
30 ARRAY(I, J) = I * J
40 PRINT "a("; STR$(I); ","; STR$(J); " ) ="; ARRAY(I, J)
50 ERASE ARRAY</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
<syntaxhighlight lang="qbasic">10 PRINT "ENTER ONE POSITIVE INTEGER: "
20 INPUT I
30 PRINT "ENTER OTHER POSITIVE INTEGER: "
40 INPUT J
50 LET A(I,J) = I*J
60 PRINT "A(";I;",";J;") = ";A(I,J)
70 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
{{works with|GW-BASIC}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">INPUT "Enter two positive integers, separated by a comma"; i, j
DIM array(1 TO i, 1 TO j)
array(i, j) = i * j
PRINT "a("; STR$(i); ","; STR$(j); " ) = "; array(i, j)
ERASE array</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">INPUT prompt "Enter two positive integers, separated by a comma ": i, j
DIM array(0,0)
MAT REDIM array(1 TO i, 1 TO j)
LET array(i, j) = i*j
PRINT "a("; STR$(i); ","; STR$(j); ") ="; array(i, j)
MAT REDIM array(0,0)
END</syntaxhighlight>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Create a two-dimensional array at runtime"
VERSION "0.0001"
 
DECLARE FUNCTION Entry ()
 
FUNCTION Entry ()
i$ = INLINE$("Enter one positive integer: ")
j$ = INLINE$("Enter other positive integer: ")
i = SSHORT(i$)
j = SSHORT(j$)
DIM a[i, j]
a[i, j] = i * j
PRINT "a("; STRING(i); ", "; STRING(j); ") ="; a[i, j]
END FUNCTION</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="freebasic">input "Enter one positive integer: " i
input "Enter other positive integer: " j
dim a(i, j)
a(i, j) = i * j
print "a(", str$(i), ",", str$(j), ") = ", a(i, j)
exit</syntaxhighlight>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> INPUT "Enter array dimensions separated by a comma: " a%, b%
DIM array(a%, b%)
array(1, 1) = PI
PRINT array(1, 1)</langsyntaxhighlight>
 
==={{header|Commodore BASIC}}===
Note: Size of array may be limited by RAM availability in some Commodore machines.
<langsyntaxhighlight FreeBasiclang="freebasic">10 print chr$(147);chr$(14);
15 print "Size of array:"
20 print "Columns (1-20)";:input x%
Line 315 ⟶ 1,005:
70 print "Element";nx;",";ny;"= '";a$(nx,ny);"'"
80 clr:rem clear variables from ram
</syntaxhighlight>
</lang>
 
{{out}}
Line 331 ⟶ 1,021:
</pre>
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim As Integer i, j
Line 341 ⟶ 1,031:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 350 ⟶ 1,040:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 INPUT PROMPT "Enter array dimensions separated by a coma: ":A,B
110 NUMERIC ARRAY(1 TO A,1 TO B)
120 LET ARRAY(1,1)=PI
130 PRINT ARRAY(1,1)</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
Line 365 ⟶ 1,055:
If you dimension arrays that are extra large to make sure you can hold data, but only have a small set of data, then all the space you reserved is wasted.
This hurts performance, because memory is set aside for the number of elements in the DIM statement.
<syntaxhighlight lang="lb">
<lang lb>
input "Enter first array dimension "; a
input "Enter second array dimension "; b
Line 375 ⟶ 1,065:
 
end
</syntaxhighlight>
</lang>
 
==={{header|PureBasic}}===
 
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define x, y
 
Line 395 ⟶ 1,085:
PrintN("Press ENTER to exit"):Input()
End ; Close down and let PureBasic delete the Console and all variables.
EndIf</langsyntaxhighlight>
 
==={{header|QuickBASIC}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight lang="qbasic"> CLS
INPUT a, b 'inputs need to be separated by commas
DIM array (1 TO a, 1 TO b)
array(1,1) = 42
PRINT array(1,1)
ERASE array</langsyntaxhighlight>
 
==={{header|Run BASIC}}===
<langsyntaxhighlight RunBasiclang="runbasic">print "Enter array 1 greater than 0"; : input a1
print "Enter array 2 greater than 0"; : input a2
Line 415 ⟶ 1,106:
chrArray$(1,1) = "Hello"
numArray(1,1) = 987.2
print chrArray$(1,1);" ";numArray(1,1)</langsyntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Arrays are indexed from 1; the only limit on their size (which may be an exigent limit) is the available memory. We create an array, write to a randomly selected element and then print it out, and finally use <code>CLEAR</code> to destroy the array (and all the other variables in the program).
<langsyntaxhighlight lang="basic"> 10 PRINT "1ST DIMENSION: ";
20 INPUT D1
30 PRINT D1
Line 432 ⟶ 1,123:
120 PRINT "ITEM ";X;", ";Y;" = ";A(X,Y)
130 CLEAR
140 PRINT "ARRAY DESTROYED"</langsyntaxhighlight>
{{out}}
<pre>1ST DIMENSION: 11
Line 441 ⟶ 1,132:
 
==={{header|Sinclair ZX Spectrum BASIC}}===
<langsyntaxhighlight lang="zxbasic">10 INPUT "Size? ";rows;"*";columns
20 DIM a(rows,columns): REM defines a numeric array
30 LET a=INT (RND*rows)+1: LET c=INT (RND*columns+1): REM the array is labelled a, but the letter a is still available for variable assignment
40 LET a(a,c)=1
50 PRINT a(a,c)
60 DIM a(1): REM arrays cannot be removed without CLEARing the entire variable space, but redimensioning them to 1 will save most of the space they used</langsyntaxhighlight>
 
==={{header|TI-83 BASIC}}===
<langsyntaxhighlight lang="ti83b">Input "ROWS? ",R
Input "COLS? ",C
{R,C}→dim([A])
42→[A](1,1)
Disp [A](1,1)
DelVar [A]</langsyntaxhighlight>
 
==={{header|Visual Basic .NET}}===
 
<langsyntaxhighlight lang="vbnet">Module Program
Sub Main()
Console.WriteLine("Enter two space-delimited integers:")
Line 471 ⟶ 1,162:
Console.WriteLine(arr(0, 0))
End Sub
End Module</langsyntaxhighlight>
 
{{out}}
Line 477 ⟶ 1,168:
5 42
2</pre>
 
=={{header|BQN}}==
 
{{works with|https://github.com/dzaima/CBQN CBQN}}
 
<syntaxhighlight lang="bqn">#!/usr/bin/env bqn
 
# Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments
# (BQNcrate phrase).
Split ← (¬-˜⊢×·+`»⊸>)∘≠⊔⊢
 
# Natural number from base-10 digits (BQNcrate phrase).
Base10 ← 10⊸×⊸+˜´∘⌽
 
# Parse any number of space-separated numbers from string 𝕩.
ParseNums ← {Base10¨ -⟜'0' ' ' Split 𝕩}
 
# •GetLine is a nonstandard CBQN extension.
•Show ⥊⟜(↕×´) ParseNums •GetLine@</syntaxhighlight>
 
{{out}}
<pre>4 2
┌─
╵ 0 1
2 3
4 5
6 7
┘</pre>
 
=={{header|C}}==
=== C99 ===
{{works with|C99}}
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int main(int argc, char **argv) {
Line 493 ⟶ 1,212:
 
return 0;
}</langsyntaxhighlight>
 
=== Traditional Style ===
Allocate multi-dimensional arrays with a single call to malloc. The demonstration code builds a rank 3 array.
<syntaxhighlight lang="c">
<lang c>
/*
assume this file is c.c ,
Line 613 ⟶ 1,332:
return EXIT_SUCCESS;
}
#endif</langsyntaxhighlight>
 
 
This style is supported by all 'C' compilers.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
Line 636 ⟶ 1,355:
free(a1);
return 0;
}</langsyntaxhighlight>
This style also supports more efficient memory utilization if you're only using a portion of the
array. If you only need the upper right half of a square array, you can do something like the following.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
Line 666 ⟶ 1,385:
free(a1);
return 0;
}</langsyntaxhighlight>
 
This approach most closely matches the C99 example, as '''alloca''' allocates on the [[stack]], rather than the [[heap]], as '''malloc''' does.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <alloca.h>
int main(int argc, char **argv)
Line 687 ⟶ 1,406:
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
class Program
{
Line 704 ⟶ 1,423:
Console.ReadLine();
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
=== With language built-in facilities ===
 
<langsyntaxhighlight lang="cpp">#include <iostream>
 
int main()
Line 734 ⟶ 1,453:
 
return 0;
}</langsyntaxhighlight>
 
=== Using std::vector from the standard library ===
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <vector>
 
Line 758 ⟶ 1,477:
// the array is automatically freed at the end of main()
return 0;
}</langsyntaxhighlight>
 
=== Using boost::multi_array ===
{{libheader|Boost}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <boost/multi_array.hpp>
 
Line 783 ⟶ 1,502:
 
return 0;
}</langsyntaxhighlight>
 
=== Using boost::uBLAS ===
{{libheader|Boost|from 1.29}}
{{works with|Boost|1.54}}
<langsyntaxhighlight lang="cpp">#include <cstdlib>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
Line 805 ⟶ 1,524:
 
return EXIT_FAILURE;
}</langsyntaxhighlight>
 
=={{header|Clean}}==
<langsyntaxhighlight lang="clean">import StdEnv
 
Start :: *World -> { {Real} }
Line 815 ⟶ 1,534:
(_, dim1, console) = freadi console
(_, dim2, console) = freadi console
= createArray dim1 (createArray dim2 1.0)</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(let [rows (Integer/parseInt (read-line))
cols (Integer/parseInt (read-line))
a (to-array-2d (repeat rows (repeat cols nil)))]
(aset a 0 0 12)
(println "Element at 0,0:" (aget a 0 0)))</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">prompt = proc (s: string) returns (int)
stream$puts(stream$primary_output(), s)
return(int$parse(stream$getl(stream$primary_input())))
end prompt
 
start_up = proc ()
po: stream := stream$primary_output()
 
% Ask for width and height
width: int := prompt("Width? ")
height: int := prompt("Height? ")
 
% Create an array of arrays.
% In order to actually create separate arrays, rather than repeating
% a reference to the same array over and over, fill_copy must be used.
arr: array[array[int]] :=
array[array[int]]$fill_copy(1, width, array[int]$fill(1, height, 0))
% Set a value
x: int := 1+width/2
y: int := 1+height/2
arr[x][y] := 123
% Retrieve the value
stream$putl(po, "arr[" || int$unparse(x) || "][" || int$unparse(y)
|| "] = " || int$unparse(arr[x][y]))
 
% The array will be automatically garbage-collected once there
% are no more references to it.
end start_up</syntaxhighlight>
{{out}}
<pre>Width? 8
Height? 6
arr[5][4] = 123</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(let ((d1 (read))
(d2 (read)))
(assert (and (typep d1 '(integer 1))
Line 834 ⟶ 1,589:
(p2 (floor d2 2)))
(setf (aref array p1 p2) t)
(print (aref array p1 p2))))</langsyntaxhighlight>
 
The <tt>[http://www.lispworks.com/documentation/HyperSpec/Body/m_assert.htm assert]</tt> will allow the user to reenter the dimensions if they are not positive integers.
Line 842 ⟶ 1,597:
Arrays in Component Pascal are started from zero index. No DISPOSE-like procedures because of garbage collection.
 
<langsyntaxhighlight lang="oberon2">
MODULE TestArray;
(* Implemented in BlackBox Component Builder *)
Line 860 ⟶ 1,615:
END DoTwoDim;
 
END TestArray.</langsyntaxhighlight>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">require "random"
 
first = gets.not_nil!.to_i32
Line 876 ⟶ 1,631:
 
arr[first][second] = random.next_int
puts arr[first][second]</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.conv, std.string;
int nRow, nCol;
Line 902 ⟶ 1,657:
array[0][0] = 3.5;
writeln("The number at place [0, 0] is ", array[0][0]);
}</langsyntaxhighlight>
{{out}}
<pre>Give me the numer of rows:
Line 910 ⟶ 1,665:
=={{header|Delphi}}==
Dimensions are generated randomly, not input by user.
<langsyntaxhighlight lang="delphi">program Project1;
 
{$APPTYPE CONSOLE}
Line 937 ⟶ 1,692:
 
Readln;
end.</langsyntaxhighlight>
 
Test run:
Line 952 ⟶ 1,707:
Column 08 = 10 rows
Column 09 = 02 rows</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
write "Number of rows: "
nrows = number input
print nrows
write "Number of columns: "
ncols = number input
print ncols
#
len a[][] nrows
for i to nrows
len a[i][] ncols
.
a[1][1] = 11
print a[1][1]
len a[][] 0
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 56.0x :
 
Typified array
<langsyntaxhighlight lang="elena">import extensions;
public program()
Line 964 ⟶ 1,737:
var m := new Integer();
console.write:("Enter two space delimited integers:");
console.loadLine(n,m);
Line 972 ⟶ 1,745:
console.printLine(myArray.at(0, 0))
}</langsyntaxhighlight>
Jagged array
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 982 ⟶ 1,755:
auto m := new Integer();
console.write:("Enter two space delimited integers:");
console.loadLine(n,m);
auto myArray2 := new object[][](n.Value).populate::(int i => (new object[](m.Value)) );
myArray2[0][0] := 2;
myArray2[1][0] := "Hello";
Line 991 ⟶ 1,764:
console.printLine(myArray2[0][0]);
console.printLine(myArray2[1][0]);
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule TwoDimArray do
 
Line 1,024 ⟶ 1,797:
 
IO.puts(TwoDimArray.get(arr,2,0))
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( two_dimensional_array ).
 
Line 1,046 ⟶ 1,819:
New_array = set( X - 1, Y - 1, X * Y, Array ),
io:fwrite( "In position ~p ~p we have ~p~n", [X - 1, Y - 1, get( X - 1, Y - 1, New_array)] ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,056 ⟶ 1,829:
=={{header|ERRE}}==
In ERRE language arrays created at run-time is "dynamic arrays". For this task will be enough this code:
<syntaxhighlight lang="text">
PROGRAM DYNAMIC
 
Line 1,069 ⟶ 1,842:
PRINT("Value in row";2;"and col";3;"is";A%[2,3])
END PROGRAM
</syntaxhighlight>
</lang>
You can redimension A% using pragmas:
!$ERASE A% with a subsequent
Line 1,075 ⟶ 1,848:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include get.e
 
sequence array
Line 1,089 ⟶ 1,862:
array[i][j] = height + width
 
printf(1,"array[%d][%d] is %d\n", {i,j,array[i][j]})</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let width = int( Console.ReadLine() )
Line 1,098 ⟶ 1,871:
let arr = Array2D.create width height 0
arr.[0,0] <- 42
printfn "%d" arr.[0,0]</langsyntaxhighlight>
 
=={{header|Factor}}==
Factor doesn't provide any support for easy access of 2d arrays. But since factor's written in factor, we can just add it and it's just as good :)
<langsyntaxhighlight lang="factor">USING: io kernel math.matrices math.parser prettyprint
sequences ;
IN: rosettacode.runtime2darray
Line 1,115 ⟶ 1,888:
[ [ 42 { 0 0 } ] dip set-Mi,j ] ! set the { 0 0 } element to 42
[ [ { 0 0 } ] dip Mi,j . ] ! read the { 0 0 } element
bi ;</langsyntaxhighlight>
 
=={{header|Fermat}}==
<syntaxhighlight lang="fermat">?m; {imput the dimensions of the array}
?n;
Array a[m,n]; {generate an array of m rows and n columns}
a[m\2, n\2] := m+n-1; {put some value in one of the cells}
!!a[m\2, n\2]; {display that entry}
@[a]; {delete the array}</syntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: cell-matrix
create ( width height "name" ) over , * cells allot
does> ( x y -- addr ) dup cell+ >r @ * + cells r> + ;
Line 1,125 ⟶ 1,906:
 
36 0 0 test !
0 0 test @ . \ 36</langsyntaxhighlight>
 
{{libheader|Forth Scientific Library}}
<langsyntaxhighlight lang="forth">INTEGER DMATRIX my-matrix{{
& my-matrix{{ 8 9 }}malloc
 
Line 1,134 ⟶ 1,915:
my-matrix{{ 3 4 }} @ .
 
& my-matrix{{ }}free</langsyntaxhighlight>
 
=={{header|Fortran}}==
In Fortran 90 and later
<langsyntaxhighlight lang="fortran">PROGRAM Example
 
IMPLICIT NONE
Line 1,157 ⟶ 1,938:
DEALLOCATE (array, STAT=errcheck)
 
END PROGRAM Example</langsyntaxhighlight>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Create_a_two-dimensional_array_at_runtime}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Create a two-dimensional array at runtime 01.png]]
In '''[https://formulae.org/?example=Create_a_two-dimensional_array_at_runtime this]''' page you can see the program(s) related to this task and their results.
 
[[File:Fōrmulæ - Create a two-dimensional array at runtime 02.png]]
 
There is no need to "release" the array, once the result is delivered, all intermediate elements are destroyed.
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
[rows, cols] = dims = eval[input["Enter dimensions: ", ["Rows", "Columns"]]]
a = new array[dims, 0] // Create and initialize to 0
a@(rows-1)@(cols-1) = 10
println[a@(rows-1)@(cols-1)]
</syntaxhighlight>
</lang>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
CFStringRef iStr, jStr
long i, j
 
iStr = input @"Enter one positive integer: "
jStr = input @"Enter other positive integer: "
i = fn StringIntegerValue(iStr)
j = fn StringIntegerValue(jStr)
mda (0, 0) = {i, j}
mda (i, j) = i * j
printf @"mda(%ld, %ld) = %ld", i, j, mda_integer (i, j)
 
HandleEvents
</syntaxhighlight>
{{output}}
With inputs of 5 and 7:
<pre>
mda(5, 7) = 35
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Creating an array of 0
a := NullMat(2, 2);
# [ [ 0, 0 ], [ 0, 0 ] ]
Line 1,190 ⟶ 1,997:
 
Determinant(a);
# 1</langsyntaxhighlight>
 
=={{header|Go}}==
Arrays in Go are only one dimensional. Code below show the obvious way of composing a 2d array as an array of arrays that can be indexed as a[r][c].
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,221 ⟶ 2,028:
a = nil
// memory allocated earlier with make can now be garbage collected.
}</langsyntaxhighlight>
The technique above alocates each row separately. This might be good if you need extremely large arrays that cannot be allocated in a single piece. It might be bad though, for locality, as there would be no guarantee that the separate allocations would be localized in memory. A technique that maintains locality is this,
<langsyntaxhighlight lang="go"> // allocate composed 2d array
a := make([][]int, row)
e := make([]int, row * col)
for i := range a {
a[i] = e[i*col:(i+1)*col]
}</langsyntaxhighlight>
Now all rows are allocated with a single allocation. Alternatively, slice e can be used directly without going through slice a. Element r c can be accessed simply as e[r*cols+c] for example, or accessor functions can be defined such as,
<syntaxhighlight lang="go">
<lang go>
func get(r, c int) int {
return e[r*cols+c]
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def make2d = { nrows, ncols ->
(0..<nrows).collect { [0]*ncols }
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def r = new Random()
 
System.in.splitEachLine(/,\s*/) { dim ->
Line 1,260 ⟶ 2,067:
a2d.each { println it }
println()
}</langsyntaxhighlight>
 
Input:
Line 1,280 ⟶ 2,087:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Data.Array
 
doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)]</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: array(1)
 
DLG(NameEdit=rows, NameEdit=cols, Button='OK', TItle='Enter array dimensions')
Line 1,291 ⟶ 2,098:
ALLOCATE(array, cols, rows)
array(1,1) = 1.234
WRITE(Messagebox, Name) array(1,1) </langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,297 ⟶ 2,104:
Multiply dimensioned arrays are arrays of arrays in both languages.
 
<langsyntaxhighlight lang="icon">procedure main(args)
nr := integer(args[1]) | 3 # Default to 3x3
nc := integer(args[2]) | 3
Line 1,309 ⟶ 2,116:
A[x][y] := &pi
write("A[",x,"][",y,"] -> ",A[x][y])
end</langsyntaxhighlight>
 
Sample output:
Line 1,319 ⟶ 2,126:
The following is only for demonstration. No real program should just assume that the user input is valid, integer, large enough etc.
<langsyntaxhighlight lang="idl">read, x, prompt='Enter x size:'
read, y, prompt='Enter y size:'
d = fltarr(x,y)
Line 1,327 ⟶ 2,134:
;==> outputs 5.6
 
delvar, d</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,333 ⟶ 2,140:
The natural ways of creating a two dimensional array, from array dimensions, in J are <code>i.</code> and <code>$</code>
 
<langsyntaxhighlight lang="j"> array1=:i. 3 4 NB. a 3 by 4 array with arbitrary values
array2=: 5 6 $ 2 NB. a 5 by 6 array where every value is the number 2</langsyntaxhighlight>
 
To update the upper left corner of the array with the value 99, you might use <code>}</code>
 
<langsyntaxhighlight lang="j"> array1=: 99 (<0 0)} array1</langsyntaxhighlight>
 
And, to retrieve that value you might use <code>{</code>
 
<langsyntaxhighlight lang="j"> (<0 0) { array1</langsyntaxhighlight>
 
Finally, J manages storage for you, so to delete the array, you could either have the name refer to a new value
 
<langsyntaxhighlight lang="j"> array1=: 0</langsyntaxhighlight>
 
or you could remove the name itself:
 
<syntaxhighlight lang ="j"> erase'array1'</langsyntaxhighlight>
 
Putting these ideas together and adding a few frills:
 
<langsyntaxhighlight lang="j">task=: verb define
assert. y -: 0 0 + , y NB. error except when 2 dimensions are specified
INIT=. 0 NB. array will be populated with this value
Line 1,362 ⟶ 2,169:
ARRAY=. NEW INDEX} ARRAY NB. use our new value at that location
INDEX { ARRAY NB. and return the value from that location
)</langsyntaxhighlight>
Passing two integers to <tt>task</tt> (as a list) satisfies the specifications for a two-dimensional array, but providing a longer list of integers accomplishes the same task on an array of as many dimensions as the count of integers given.
 
Example use (result should always be 1 which is the value of <code>NEW</code>):
 
<langsyntaxhighlight Jlang="j"> task 99 99
1</langsyntaxhighlight>
 
The type of the array is determined by the type of the values used in filling the array. E.g., alternate data types are obtained by substituting any of the following lines:
<langsyntaxhighlight lang="j">'init new' =. ' ';'x' NB. literals
'init new' =. 1r2;2r3 NB. fractions
'init new' =. a: ; <<'Rosetta' NB. boxes</langsyntaxhighlight>
 
=={{header|Java}}==
 
<langsyntaxhighlight lang="java">import java.util.Scanner;
 
public class twoDimArray {
Line 1,390 ⟶ 2,197:
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">var width = Number(prompt("Enter width: "));
var height = Number(prompt("Enter height: "));
 
Line 1,409 ⟶ 2,216:
 
//cleanup array
arr = void(0);</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,426 ⟶ 2,233:
 
Here's a simple example.
<langsyntaxhighlight lang="jq"># A function to create an m x n matrix
# filled with the input element
def matrix(m;n):
Line 1,436 ⟶ 2,243:
# Task: create a matrix with dimensions specified by the user
# and set the [1,2] element:
(0 | matrix($m|tonumber; $n|tonumber)) | setpath([1,2]; 99)</langsyntaxhighlight>
 
If the above is in a file, say 2d.jq, the invocation:
Line 1,442 ⟶ 2,249:
<tt>jq -n -c --arg m 2 --arg n 3 -f 2d.jq </tt>
 
would produce: <langsyntaxhighlight lang="jq">[[0,0,0,0],[0,0,99,0],[0,0,0,0]]</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 1,448 ⟶ 2,255:
Julia supports n-dimensional arrays as native data types: `Array{T, N}`, where `T` is the type of it´s elements and `N` is the number of dimensions.
 
<langsyntaxhighlight lang="julia">function input(prompt::AbstractString)
print(prompt)
return readline()
Line 1,463 ⟶ 2,270:
x[3, 3] = 5.0 # overloads `setindex!` generic function
x::Matrix # `Matrix{T}` is an alias for `Array{T, 2}`
x = 0; gc() # Julia has no `del` command, rebind `x` and call the garbage collector</langsyntaxhighlight>
 
Manually calling the garbage collector may or may not actually collect the array, but it will be eventually.
Line 1,469 ⟶ 2,276:
=={{header|Kotlin}}==
Program arguments provide dimensions of the array (4 5 in the example).
<langsyntaxhighlight lang="scala">fun main(args: Array<String>) {
// build
val dim = arrayOf(10, 15)
Line 1,483 ⟶ 2,290:
// print
array.forEach { println(it.asList()) }
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3, 4, 5]
Line 1,492 ⟶ 2,299:
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">make "a2 mdarray [5 5]
mdsetitem [1 1] :a2 0 ; by default, arrays are indexed starting at 1
print mditem [1 1] :a2 ; 0</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function multiply(n, a, b) if a <= b then return n, multiply(n, a + 1, b) end end
 
a, b = io.read() + 0, io.read() + 0
Line 1,503 ⟶ 2,310:
matrix[a][b] = 5
print(matrix[a][b])
print(matrix[1][1])</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckArray {
Do {
Line 1,522 ⟶ 2,329:
}
CheckArray
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
This hardly covers the richness and complexity of arrays in Maple, but here goes:
<langsyntaxhighlight Maplelang="maple">> a := Array( 1 .. 3, 1 .. 4 ): # initialised to 0s
> a[1,1] := 1: # assign an element
> a[2,3] := 4: # assign an element
Line 1,537 ⟶ 2,344:
 
> a := 'a': # unassign the name
> gc(); # force a garbage collection; may or may not actually collect the array, but it will be eventually</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">arrayFun[m_Integer,n_Integer]:=Module[{array=ConstantArray[0,{m,n}]},
array[[1,1]]=RandomReal[];
array[[1,1]]
]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">width = input('Array Width: ');
height = input('Array Height: ');
 
Line 1,556 ⟶ 2,363:
 
clear array; % de-allocate (remove) array from workspace
</syntaxhighlight>
</lang>
 
 
Sample Output:
<langsyntaxhighlight MATLABlang="matlab">Array Width: 18
Array Height: 12
Array element (1,1) = 12</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight Maximalang="maxima">printf(true, "in the following terminate every number with semicolon `;'")$
n: readonly("Input x-size: ")$
m: readonly("Input y-size: ")$
Line 1,573 ⟶ 2,380:
/* indexing starts from 0 */
print(a[0,0]);
print(a[n-1,m-1]);</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">a = getKBValue prompt:"Enter first dimension:"
b = getKBValue prompt:"Enter second dimension:"
arr1 = #()
Line 1,586 ⟶ 2,393:
)
arr1[a][b] = 1
print arr1[a][b]</langsyntaxhighlight>
 
=={{header|MUMPS}}==
This example uses a two level tree to mimic an 2D array.
<syntaxhighlight lang="mumps">
<lang MUMPS>
ARA2D
NEW X,Y,A,I,J
Line 1,602 ⟶ 2,409:
KILL X,Y,A,I,J
QUIT
</syntaxhighlight>
</lang>
 
=={{header|NetRexx}}==
'''Note:''' No attempt is made to validate the input.
Any errors will be handled as exceptions by the underlying JVM.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,619 ⟶ 2,426:
say "arry["xPos","yPos"]:" arry[xPos, yPos]
return
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,628 ⟶ 2,435:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils, rdstdin
let
Line 1,647 ⟶ 2,454:
echo s[0][0]
 
# The allocated memory is freed by the garbage collector.</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class TwoDimArray {
use IO;
function : Main(args : String[]) ~ Nil {
 
rows := Standard->ReadLine()->ToInt();
bundle Default {
cols := Standard->ReadLine()->ToInt();
class TwoDee {
function : Main(args : System.String[]) ~ Nil {
if(rows > DoIt(0 & cols > 0); {
array := Float->New[rows, cols];
}
array[0,0] := 42.0;
Standard->Print("The number at place [0,] is: ")->PrintLine(array[0,0]);
function : native : DoIt() ~ Nil {
Console->GetInstance()->Print("Enter x: ");
x := Console->GetInstance()->ReadString()->ToInt();
Console->GetInstance()->Print("Enter y: ");
y := Console->GetInstance()->ReadString()->ToInt();
if(x > 0 & y > 0) {
array : Int[,] := Int->New[x, y];
array[0, 0] := 2;
array[0, 0]->PrintLine();
};
}
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
Line 1,684 ⟶ 2,480:
{{works with|GNUstep}}
{{works with|Cocoa}}
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main()
Line 1,709 ⟶ 2,505:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let nbr1 = read_int ();;
let nbr2 = read_int ();;
let array = Array.make_matrix nbr1 nbr2 0.0;;
array.(0).(0) <- 3.5;;
print_float array.(0).(0); print_newline ();;</langsyntaxhighlight>
 
or using the module [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Bigarray.html Bigarray]:
 
<langsyntaxhighlight lang="ocaml">let nbr1 = read_int ();;
let nbr2 = read_int ();;
let arr = Bigarray.Array2.create Bigarray.float32 Bigarray.c_layout nbr1 nbr2 ;;
arr.{0,0} <- 3.5;;
print_float arr.{0,0}; print_newline ();;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
ooRexx arrays can be created with up to 999,999,999 dimensions...assuming you have enough memory to do so.
Actually it's the 'size' of the array that's limited (the product of the dimensions).
<langsyntaxhighlight ooRexxlang="oorexx">Say "enter first dimension"
pull d1
say "enter the second dimension"
Line 1,740 ⟶ 2,536:
say a[10,10]
max=1000000000
b = .array~new(max,max) </langsyntaxhighlight>
{{out}}
<pre>D:\>rexx 2d
Line 1,757 ⟶ 2,553:
=={{header|Oz}}==
Oz does not have multi-dimensional arrays. But we can create an array of arrays (similarly to most examples on this page):
<langsyntaxhighlight lang="oz">declare
%% Read width and height from stdin
class TextFile from Open.file Open.text end
Line 1,771 ⟶ 2,567:
%% set and read element
Arr.1.1 := 42
{Show Arr.1.1}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">tmp(m,n)={
my(M=matrix(m,n,i,j,0));
M[1,1]=1;
M[1,1]
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,785 ⟶ 2,581:
The following code is standard Extended Pascal (tested with <tt>gpc --extended-pascal</tt>):
 
<langsyntaxhighlight lang="pascal">program array2d(input, output);
 
type
Line 1,810 ⟶ 2,606:
{ get rid of array }
dispose(data);
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 1,817 ⟶ 2,613:
Predefining an array (or multi-dimension array) size is unnecessary, Perl dynamically resizes the array to meet the requirements. Of course I'm assuming that the user is entering array size 0 based.
 
<langsyntaxhighlight lang="perl">sub make_array($ $){
# get array sizes from provided params, but force numeric value
my $x = ($_[0] =~ /^\d+$/) ? shift : 0;
Line 1,835 ⟶ 2,631:
print "\n";
}
}</langsyntaxhighlight>
 
The above is a bit verbose, here is a simpler implementation:
 
<langsyntaxhighlight lang="perl">sub array {
my ($x, $y) = @_;
map {[ (0) x $x ]} 1 .. $y
Line 1,857 ⟶ 2,653:
> 0 0 0
> 0 1 0
> 0 0 0</langsyntaxhighlight>
 
=={{header|Phix}}==
Obviously the sigificant part here is the three lines beginning "sequence array", the rest is all just boilerplate gui code.
Copy of [[Create_a_two-dimensional_array_at_runtime#Euphoria|Euphoria]]
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence array
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Create2Darray.exw</span>
integer height,width,i,j
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> <span style="color: #000080;font-style:italic;">-- (layout/spacing leaves a little to be desired...)</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">lab</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">tab</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">tab</span><span style="color: #0000FF;">)</span>
height = floor(prompt_number("Enter height: "))
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tab</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)</span>
width = floor(prompt_number("Enter width: "))
<span style="color: #004080;">sequence</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d %d"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">height</span><span style="color: #0000FF;">,</span><span style="color: #000000;">width</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">height</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">j</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">width</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">array</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">width</span><span style="color: #0000FF;">),</span><span style="color: #000000;">height</span><span style="color: #0000FF;">)</span>
array = repeat(repeat(0,width),height)
<span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">height</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">width</span>
i = floor(height/2+0.5)
j = floor(width/2+0.5)
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"array[%d][%d] is %d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]})</span>
array[i][j] = height + width
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
printf(1,"array[%d][%d] is %d\n", {i,j,array[i][j]})</lang>
<span style="color: #7060A8;">IupRefresh</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">lab</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter two numbers (&gt;0) separated by a space"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">tab</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"valuechanged_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"EXPAND=HORIZONTAL"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">lab</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tab</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"GAP=10,NORMALIZESIZE=VERTICAL"</span><span style="color: #0000FF;">),</span>
<span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})},</span><span style="color: #008000;">"MARGIN=5x5"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">`TITLE="Create 2D array"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
The distributed version contains the older and simpler but console-only code.
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
"Enter height: " input tonum nl
Line 1,885 ⟶ 2,713:
-1 get -1 get "Value of the last element of the last dimension: " print print drop
drop /# remove array/list from the stack #/
</syntaxhighlight>
</lang>
With syntactic sugar
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
"Enter height: " input tonum nl
Line 1,896 ⟶ 2,724:
( -1 -1 ) mget "Value of the last element of the last dimension: " print print drop
drop /# remove array/list from the stack #/
</syntaxhighlight>
</lang>
With more syntactic sugar
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
"Enter height: " input tonum nl
Line 1,907 ⟶ 2,735:
( -1 -1 ) sget "Value of the last element of the last dimension: " print print
drop /# remove array/list from the stack #/
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">import util.
 
go =>
print("Input the number of rows and columns: "),
[Rows,Cols]=split(read_line()).map(to_int),
X=new_array(Rows,Cols),
X[1,1] = Rows*Cols+1,
println(X[1,1]).</syntaxhighlight>
 
{{out}}
<pre>Input the number of rows and columns: 10 20
201</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de 2dimTest (DX DY)
(let A (make (do DX (link (need DY))))
(set (nth A 3 3) 999) # Set A[3][3] to 999
Line 1,916 ⟶ 2,758:
(get A 3 3) ) ) # Return A[3][3]
 
(2dimTest 5 5)</langsyntaxhighlight>
Output:
<pre>(NIL NIL NIL NIL NIL)
Line 1,926 ⟶ 2,768:
 
=={{header|PL/I}}==
<syntaxhighlight lang="text">
/* First way using a controlled variable: */
 
Line 1,939 ⟶ 2,781:
 
free A;
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight PLlang="pl/Ii"> 6.00000E+0000 5.00000E+0000 4.00000E+0000 3.00000E+0000 2.00000E+0000
1.00000E+0000
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Second way using a BEGIN block: */
 
Line 1,956 ⟶ 2,798:
 
/* The array is automatically destroyed when the block terminates. */
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight PLlang="pl/Ii"> 1.00000E+0000 2.00000E+0000 3.00000E+0000 4.00000E+0000 5.00000E+0000
6.00000E+0000 7.00000E+0000 8.00000E+0000 9.00000E+0000 1.00000E+0001
1.10000E+0001 1.20000E+0002
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Third way using a PROCEDURE block: */
 
Line 1,975 ⟶ 2,817:
 
/* The array is automatically destroyed when the procedure terminates. */
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="pl/i">
<lang PL/I>
1.00000E+0000 2.00000E+0000 3.00000E+0000 4.00000E+0000 5.00000E+0000
6.00000E+0000 7.00000E+0000 8.00000E+0000 9.00000E+0000 1.00000E+0001
1.10000E+0001 1.20000E+0001 1.30000E+0001 1.40000E+0001 1.50000E+0001
1.60000E+0001 1.70000E+0001 1.80000E+0001 1.90000E+0001 2.00000E+0001
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">vars itemrep;
incharitem(charin) -> itemrep;
;;; Read sizes
Line 1,996 ⟶ 2,838:
ar(0,0) =>
;;; Make sure array is unreferenced
0 -> ar;</langsyntaxhighlight>
 
Pop11 is garbage collected so there is no need to destroy array. However, the array is live as long as variable ar references it. The last assignment makes sure that we loose all our references to the array turning it into garbage.
Line 2,003 ⟶ 2,845:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Read-ArrayIndex ([string]$Prompt = "Enter an integer greater than zero")
{
Line 2,026 ⟶ 2,868:
 
$array2d = New-Object -TypeName 'System.Object[,]' -ArgumentList $x, $y
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,033 ⟶ 2,875:
</pre>
Populate the array:
<syntaxhighlight lang="powershell">
<lang PowerShell>
[int]$k = 1
 
Line 2,040 ⟶ 2,882:
0..5 | ForEach-Object -Begin {$k += 10} -Process {$array2d[$i,$_] = $k + $_}
}
</syntaxhighlight>
</lang>
This is the entire array:
<syntaxhighlight lang="powershell">
<lang PowerShell>
for ($i = 0; $i -lt 6; $i++)
{
"{0}`t{1}`t{2}`t{3}`t{4}`t{5}" -f (0..5 | ForEach-Object {$array2d[$i,$_]})
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,058 ⟶ 2,900:
</pre>
Get an element of the array:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$array2d[2,2]
</syntaxhighlight>
</lang>
{{Out}}
<pre>
33
</pre>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<syntaxhighlight lang="prolog">:- dynamic array/2.
 
run :-
write('Enter two positive integers, separated by a comma: '),
read((I,J)),
assert(array(I,J)),
Value is I * J,
format('a(~w,~w) = ~w', [I, J, Value]),
retractall(array(_,_)).</syntaxhighlight>
 
=={{header|Python}}==
{{works with|Python| 2.5 and 3.6}}
 
<langsyntaxhighlight lang="python">width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])</langsyntaxhighlight>
 
'''Note:''' Some people may instinctively try to write myarray as [[0] * width] * height, but the * operator creates ''n'' references to [[0] * width]
Line 2,079 ⟶ 2,933:
You can also use a two element tuple to index a dictionary like so:
 
<langsyntaxhighlight lang="python">myarray = {(w,h): 0 for w in range(width) for h in range(height)}
# or, in pre 2.7 versions of Python: myarray = dict(((w,h), 0) for w in range(width) for h in range(height))
myarray[(0,0)] = 3.5
print (myarray[(0,0)])</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ witheach peek ] is {peek} ( { p --> x )
 
[ dip dup
witheach [ peek dup ]
drop ] is unpackdepack ( { p --> * )
 
[ reverse
Line 2,098 ⟶ 2,952:
[ dup dip
[ rot dip
[ unpackdepack drop ] ]
repack ] is {poke} ( x { p --> { )
 
Line 2,119 ⟶ 2,973:
say "Reading element {1,4} of array: "
' [ 1 4 ] {peek} echo</langsyntaxhighlight>
 
{{out}}
Line 2,132 ⟶ 2,986:
=={{header|R}}==
{{trans|C}}
<langsyntaxhighlight lang="r">input <- readline("Enter two integers. Space delimited, please: ")
dims <- as.numeric(strsplit(input, " ")[[1]])
arr <- array(dim=dims)
Line 2,138 ⟶ 2,992:
jj <- ceiling(dims[2]/2)
arr[ii, jj] <- sum(dims)
cat("array[", ii, ",", jj, "] is ", arr[ii, jj], "\n", sep="")</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,144 ⟶ 2,998:
Using a vector of vectors to represent arrays:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,157 ⟶ 3,011:
 
array
</syntaxhighlight>
</lang>
 
Output:
Line 2,177 ⟶ 3,031:
 
Line 4: Print each line of the array.
<syntaxhighlight lang="raku" perl6line>my ($major,$minor) = prompt("Dimensions? ").comb(/\d+/);
my @array = [ '@' xx $minor ] xx $major;
@array[ *.rand ][ *.rand ] = ' ';
.say for @array;</langsyntaxhighlight>
 
Typical run:
<syntaxhighlight lang="text">Dimensions? 5x35
[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
Line 2,189 ⟶ 3,043:
[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
</syntaxhighlight>
</lang>
 
The most recent versions of Rakudo have preliminary support for 'shaped arrays'. Natively shaped arrays are a flexible feature for declaring typed, potentially multi-dimensional arrays, potentially with pre-defined
dimensions. They will make memory-efficient matrix storage and matrix operations possible.
 
<syntaxhighlight lang="raku" perl6line>my ($major,$minor) = +«prompt("Dimensions? ").comb(/\d+/);
my Int @array[$major;$minor] = (7 xx $minor ) xx $major;
@array[$major div 2;$minor div 2] = 42;
say @array;</langsyntaxhighlight>
 
Typical run:
<syntaxhighlight lang="text">Dimensions? 3 x 10
[[7 7 7 7 7 7 7 7 7 7] [7 7 7 7 7 42 7 7 7 7] [7 7 7 7 7 7 7 7 7 7]]</langsyntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="rebol">Red ["Create two-dimensional array at runtime"]
 
width: to-integer ask "What is the width of the array? "
height: to-integer ask "What is the height of the array? "
 
; 2D arrays are just nested blocks in Red.
matrix: copy [] ; Make an empty block to hold our rows.
loop height [ ; A loop for each row...
row: append/dup copy [] 0 width ; Create a block like [0 0 0 0] if width is 4.
append/only matrix row ; Append the row to our matrix as its own block.
]
 
a: 3
b: 2
matrix/2/4: 27 ; use path syntax to access or assign
matrix/1/1: 99 ; series are 1-indexed in Red; there is no matrix/0/0
matrix/(a)/(a): 10 ; accessing elements with words requires special care
matrix/:b/:b: 33 ; alternative
print mold matrix</syntaxhighlight>
{{out}}
<pre>
What is the width of the array? 5
What is the height of the array? 3
[[99 0 0 0 0] [0 33 0 27 0] [0 0 10 0 0]]
</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program allocates/populates/displays a two-dimensional array. */
call bloat /*the BLOAT procedure does all allocations.*/
/*no more array named @ at this point. */
Line 2,236 ⟶ 3,117:
╚════════════════════════════════════════════════════════════════════╝*/
drop @. /*because of the PROCEDURE statement, the*/
return /* [↑] DROP statement is superfluous. */</langsyntaxhighlight>
'''output''' when the following input is entered after the prompt message: &nbsp; <tt> 30 15 </tt>
<pre>
Line 2,272 ⟶ 3,153:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
See 'Enter width : ' give width
See 'Enter height : ' give height
Line 2,278 ⟶ 3,159:
aList = list(height) for x in aList x = list(width) next
aList[1][2] = 10 See aList[1][2] + nl
</syntaxhighlight>
</lang>
 
 
« "# rows?" "3" INPUT "# columns?" "5" INPUT <span style="color:grey">''@ ask for size, with 3 and 5 as default values''</span>
2 →LIST STR→ 0 CON <span style="color:grey">''@ create array in stack''</span>
{ 1 2 } TIME PUT <span style="color:grey">''@ put current time at array[1,2] ''</span>
{ 1 2 } GET <span style="color:grey">''@ read array[1,2] and remove array from the stack ''</span>
» '<span style="color:blue">TASK' STO</span>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">puts 'Enter width and height: '
w=gets.to_i
arr = Array.new(gets.to_i){Array.new(w)}
arr[1][3] = 5
p arr[1][3]</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::env;
 
fn main() {
Line 2,302 ⟶ 3,190:
v[0][0] = 1;
println!("{}", v[0][0]);
}</langsyntaxhighlight>
 
=={{header|S-BASIC}}==
<syntaxhighlight lang="BASIC">
var a, b = integer
 
print "Two-Dimensional Array Example"
input "Size of first dimension"; a
input "Size of second dimension"; b
 
dim integer test_array(a, b)
 
test_array(1,1) = 99 rem S-BASIC arrays are indexed from 1
 
print "Value stored at 1,1 ="; test_array(1,1)
 
end
</syntaxhighlight>
{{out}}
<pre>
Two-Dimensional Array Example
Size of first dimension? 7
Size of second dimension? 7
Value stored at 1,1 = 99
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object Array2D{
def main(args: Array[String]): Unit = {
val x = Console.readInt
Line 2,314 ⟶ 3,226:
println("The number at (0, 0) is "+a(0)(0))
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 2,322 ⟶ 3,234:
There is no two-dimensional array-type built in to Scheme, but there is a vector.
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme read)
Line 2,347 ⟶ 3,259:
(floor (/ y 2))))
(newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,363 ⟶ 3,275:
There are SRFI libraries providing arrays. This example uses SRFI 63.
 
<langsyntaxhighlight lang="scheme">
(import (except (scheme base) equal?)
(scheme read)
Line 2,382 ⟶ 3,294:
;; Retrieve and display result
(display (array-ref array (floor (/ x 2)) (floor (/ y 2)))) (newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,394 ⟶ 3,306:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,409 ⟶ 3,321:
anArray[1][1] := 3;
writeln("The number at place [1, 1] is " <& anArray[1][1]);
end func;</langsyntaxhighlight>
 
Output:
Line 2,419 ⟶ 3,331:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func make_matrix(x, y) {
y.of { x.of(0) };
}
Line 2,428 ⟶ 3,340:
var matrix = make_matrix(x, y); # create the matrix
matrix[y/2][x/2] = 1; # write something inside it
say matrix; # display the matrix</langsyntaxhighlight>
{{out}}
<pre>
Line 2,436 ⟶ 3,348:
</pre>
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
INTEGER N,M;
M := ININT;
Line 2,447 ⟶ 3,359:
END;
! ARRAY A OUT OF SCOPE ;
END.</langsyntaxhighlight>
{{in}}
<pre>10 20</pre>
Line 2,454 ⟶ 3,366:
99
</pre>
 
=={{header|Slope}}==
<syntaxhighlight lang="slope">
(define width (string->number (read-line)))
(define height (string->number (read-line)))
(if (and width height)
(list-seed height (list-seed width #t))
(! "A non-number value was submitted"))
</syntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Pharo}}
<langsyntaxhighlight lang="smalltalk">
m := (FillInTheBlankMorph request: 'Number of rows?') asNumber.
n := (FillInTheBlankMorph request: 'Number of columns?') asNumber.
Line 2,469 ⟶ 3,390:
at: (aMatrix columnCount // 2).
Transcript show: 'Entry is', e printString.
</syntaxhighlight>
</lang>
{{works with|GNU Smalltalk}}
 
Smalltalk has no problems in creating objects at runtime. I haven't found a class for multidimensional array in the standard library, so let us suppose to have a class named MultidimensionalArray.
 
<langsyntaxhighlight lang="smalltalk">|num1 num2 arr|
num1 := stdin nextLine asInteger.
num2 := stdin nextLine asInteger.
Line 2,490 ⟶ 3,411:
(arr at: {i. j}) displayNl
]
].</langsyntaxhighlight>
 
A possible implementation for a '''Bi'''dimensionalArray class is the following (changing ''Multi'' into ''Bi'' and using this class, the previous code runs fine):
 
<langsyntaxhighlight lang="smalltalk">Object subclass: BidimensionalArray [
|biArr|
<comment: 'bidim array'>
Line 2,519 ⟶ 3,440:
^ (biArr at: (biDim at: 1)) at: (biDim at: 2) put: val
]
].</langsyntaxhighlight>
 
Instead of implementing such a class (or the MultidimensionalArray one), we can use a LookupTable class, using Array objects as keys (each element of the array will be an index for a specific ''dimension'' of the "array"). The final effect is the same as using an array (almost in the ''AWK sense'') and the approach has some advantages.
 
<langsyntaxhighlight lang="smalltalk">|num1 num2 pseudoArr|
num1 := stdin nextLine asInteger.
num2 := stdin nextLine asInteger.
Line 2,542 ⟶ 3,463:
(pseudoArr at: {i. j}) displayNl.
]
].</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 2,552 ⟶ 3,473:
Note: trim(input) is needed for Snobol4+.
 
<langsyntaxhighlight SNOBOL4lang="snobol4">* # Get user X,Y dimensions
output = 'Enter X,Y:'; xy = trim(input)
xy break(',') . x ',' rem . y
Line 2,572 ⟶ 3,493:
* # Release array for garbage collection
arr =
end</langsyntaxhighlight>
 
Output:
Line 2,582 ⟶ 3,503:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">val nbr1 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn);
val nbr2 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn);
val array = Array2.array (nbr1, nbr2, 0.0);
Array2.update (array, 0, 0, 3.5);
print (Real.toString (Array2.sub (array, 0, 0)) ^ "\n");</langsyntaxhighlight>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">display "Number of rows?" _request(nr)
display "Number of columns?" _request(nc)
matrix define a=J($nr,$nc,0)
matrix a[1,2]=1.5
matrix list a
matrix drop a</langsyntaxhighlight>
 
This is also possible in Mata, except that console input is still done from Stata:
 
<langsyntaxhighlight lang="stata">mata
mata stata display "Number of rows?" _request(nr)
mata stata display "Number of columns?" _request(nc)
Line 2,607 ⟶ 3,528:
a
mata drop a
end</langsyntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang="text">import Foundation
 
print("Enter the dimensions of the array seperated by a space (width height): ")
Line 2,628 ⟶ 3,549:
println(array)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,638 ⟶ 3,559:
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">
puts "Enter width:"
set width [gets stdin]
Line 2,655 ⟶ 3,576:
# Cleanup array
unset arr
</syntaxhighlight>
</lang>
 
=={{header|Toka}}==
Toka has no direct support for 2D arrays, but they can be created and operated on in a manner similar to normal arrays using the following functions.
 
<langsyntaxhighlight lang="toka">[ ( x y -- address )
cells malloc >r
dup cells >r
Line 2,673 ⟶ 3,594:
[ ( value a b address -- )
array.get array.put
] is 2D-put-element</langsyntaxhighlight>
 
And a short test:
<langsyntaxhighlight lang="toka">5 5 2D-array >r #! Create an array and save the pointer to it
10 2 3 r@ 2D-put-element #! Set element 2,3 to 10
2 3 r@ 2D-get-element #! Get the element at 2,3
r> drop #! Discard the pointer to the array</langsyntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl int width height
out "width: " console
set width (in int console)
Line 2,701 ⟶ 3,622:
 
set twodstream<0><0> 5
out twodstream<0><0> endl console</langsyntaxhighlight>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 2,725 ⟶ 3,646:
Erase myArray
End Sub
</syntaxhighlight>
</lang>
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang="vim">" Create a two-dimensional array with r rows and c columns.
" The optional third argument specifies the initial value
" (default is 0).
Line 2,756 ⟶ 3,677:
let array[rows - 1][cols - 1] = rows * cols
echo array[rows - 1][cols - 1]
unlet array</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import os
 
fn main() {
// input
mut row := os.input("enter rows: ").str()
for elem in row {if elem.is_digit() == false {println('Input Error!') exit(1)}}
mut col := os.input("enter cols: ").str()
for elem in col {if elem.is_digit() == false {println('Input Error!') exit(1)}}
// create 2d array of specified size
mut arr2d := [][]int{len: row.int(), init: []int{len: col.int()}}
 
// assign values
arr2d[0][0] = 7
 
// view
println(arr2d)
 
// clear
arr2d.clear()
}
</syntaxhighlight>
 
{{out}}
<pre>
enter rows: 3
enter cols: 3
[[7, 0, 0], [0, 0, 0], [0, 0, 0]]
</pre>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "io" for Stdin, Stdout
 
var x
Line 2,786 ⟶ 3,738:
System.print("\na[%(x-1)][%(y-1)] = %(a[x-1][y-1])")
// make the array eligible for garbage collection
a = null</langsyntaxhighlight>
 
{{out}}
Line 2,799 ⟶ 3,751:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">inc c:\cxpl\codes; \(command words can be abbreviated to first 3 letters)
def IntSize=4; \number of bytes in an integer (2 or 4 depending on version)
int X, Y, A, I;
Line 2,807 ⟶ 3,759:
A(X/2, Y/2):= X+Y;
IntOut(0, A(X/2, Y/2)); CrLf(0);
]</langsyntaxhighlight>
 
Space allocated by the Reserve intrinsic is automatically released when
Line 2,825 ⟶ 3,777:
 
Since the array is row major, sub-scripting works as expected: [row][col].
<langsyntaxhighlight lang="zkl">rows:=ask("Rows: ").toInt();
cols:=ask("columns: ").toInt();
array:=rows.pump(List.createLong(rows),List.createLong(cols,0).copy);
array[1][2]=123;
array.println();
array[1][2].println();</langsyntaxhighlight>
The createLong method pre-allocates a list, optionally filled with a constant or computation.
{{out}}
Line 2,840 ⟶ 3,792:
</pre>
If you want Matrix/linear algebra, you can use the GNU Scientific Library:
<langsyntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
rows:=ask("Rows: ").toInt();
cols:=ask("columns: ").toInt();
Line 2,846 ⟶ 3,798:
m[1,2]=123;
m.format().println();
println(m[1,2]);</langsyntaxhighlight>
Again, garbage collected.
{{out}}
Line 2,859 ⟶ 3,811:
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module Main;
type
Line 2,875 ⟶ 3,827:
writeln("m[0,1].> ",m[0,1])
end Main.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
13

edits