
Data Structure
This illustrates a data structure, a means of storing data within a program.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
V width = 3V height = 5V myarray = [[0] * width] * heightprint(myarray[height-1][width-1])
The routine used to retrieve the input is left unimplemented.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Array setup;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;Create_2D_Array:ARRAY_2Dequ$100000ARRAY_POINTER_VARIABLEequ$200000; input: D0 = width, D1 = height; assume the input is byte length and unsigned, ranging from 1 to FF.AND.L#$000000FF,D0AND.L#$000000FF,D1 ;sanitize the input to byte length.LEAARRAY_2D,A0;get base array address.;The array's size will be measured in bytes, as this is how memory offsetting is measured.;For this example the elements will all be 32-bit.;Therefore, the dimensions need to be multiplied by the byte count of each element.LSL.W#2,D0;four bytes per element = multiply by 4LSL.W#2,D1;Next, these values are multiplied to get the array's size.MOVE.LD0,D2MULUD1,D2;D2 is the array's size (measured in bytes) and will be placed at the beginning.;This does not count as an element of the array for the purposes of row/column indexing.;The array's base address will be offset by 4 bytes prior to any indexing.MOVE.LD2,(A0)+;store D2 in A0, add 4 to A0MOVEA.LA0,[ARRAY_POINTER_VARIABLE];the brackets are optional, they show that this is a memory address label.;this is still a move to a memory address with or without the brackets.;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Storing a value in the array;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;LEAARRAY_POINTER_VARIABLE,A1;load the address where the array's base address is stored.MOVE.L(A1),A1;dereference the pointer and get ARRAY_2D+4 into A1.; for this example the arbitrary row/column indices (2,5) will be used.MOVE.L#2,D4MULUD0,D4;there are D0 entries per row, multiply row index by elements per row.MOVE.L#5,D5MOVE.L#$00112233,D7 ;determine the value we want to store in the array.; The bytes per element was factored into D0 when the array was created. So D4 is already where it should be.LSL.L#2,D5;column index still needs to be scaled by the bytes per element.LEA(A1,D4),A1;select the desired row.;68000 doesn't allow you to use more than 1 data register at a time to offset. So we have to offset separately.;Despite the use of parentheses this is NOT a dereference like it would be with "MOVE.L (A1),D7". D4 is merely added to the address in A1.MOVE.LD7,(A1,D5);store #$00112233 in row 2, column 5 of the array.;Loading a value is the same as storing it, except the operands in the last instruction are reversed, and MOVE.L #$00112233,D7;is omitted.;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Destroying the array;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; The array is destroyed by storing something else in its location. If you really want to reset it to zero, you can; do so with the following:LEAARRAY_POINTER_VARIABLE,A1MOVE.L(A1),A1MOVE.L-(A1),D7;get the array size into D7. Remember that the array's size was stored just before its data.ThisvalueispotentiallytoolargeforasingleDBRA,butitcanbesplitup.SWAPD7MOVE.WD7,D6;get the top half of D7 into D6. D6 will be the outer loop's DBRA value.SWAPD7SUBQ.L#1,D7;D7 needs to be decremented by 1. D6 is fine the way it is.MOVE.L(A0)+,D0;dummy move to increment the pointer back to the array base.MOVEQ#0,D0;faster than MOVE.L #0,D0loop_destroyArray:MOVE.LD0,(A0)+DBRAD7,loop_destroyArray;loop using bottom 2 bytes of the array size as a loop counterDBRAD6,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.
/* 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 *//*********************************/.dataszMessRead1: .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 *//*********************************/.bsssZoneConv: .skip BUFFERSIZE // conversion buffersZoneConv1: .skip BUFFERSIZE // conversion buffersZoneConv2: .skip BUFFERSIZE // conversion buffersBuffer: .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 szCarriageReturnqAdrsZoneConv: .quad sZoneConvqAdrsZoneConv1: .quad sZoneConv1qAdrsZoneConv2: .quad sZoneConv2qAdrszMessRead1: .quad szMessRead1 qAdrszMessRead2: .quad szMessRead2 qAdrsBuffer: .quad sBufferqAdrszMessResult: .quad szMessResultqAdrszMessStart: .quad szMessStartqAdrszMessIndice1: .quad szMessIndice1qAdrszMessIndice2: .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 message100: 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"
Program 64 bits start.Input size level 1 : 10Input size level 2 : 10Indice 1 =1 Indice 2 =0 Item = 80Indice 1 =9 Indice 2 =9 Item = 792
The user must type in the monitor the following command after compilation and before running the program!
SET EndProg=*
CARD EndProg ;required for ALLOCATE.ACTINCLUDE "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 ODRETURN (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) ODRETURNPROC 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=0RETURNPROC 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)=vRETURNINT 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)RETURNPROC TestDestroy(IntArray2D POINTER a) PrintF("Destroy array of %B rows and %B cols%E",a.rows,a.cols) Destroy(a)RETURNPROC 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)RETURNPROC 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)RETURNPROC 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)RETURNScreenshot from Atari 8-bit computer
Get number of rows (1..100): 80Get number of cols (1..100): 90Create array of 80 rows and 90 colsWrite 6502 to row 40 and col 45Read at row 40 and col 45: 6502Destroy array of 80 rows and 90 cols
withAda.Text_Io;withAda.Float_Text_Io;withAda.Integer_Text_Io;procedureTwo_Dimensional_ArraysistypeMatrix_Typeisarray(Positiverange<>,Positiverange<>)ofFloat;Dim_1:Positive;Dim_2:Positive;beginAda.Integer_Text_Io.Get(Item=>Dim_1);Ada.Integer_Text_Io.Get(Item=>Dim_2);-- Create an inner block with the correctly sized arraydeclareMatrix:Matrix_Type(1..Dim_1,1..Dim_2);beginMatrix(1,Dim_2):=3.14159;Ada.Float_Text_Io.Put(Item=>Matrix(1,Dim_2),Fore=>1,Aft=>5,Exp=>0);Ada.Text_Io.New_Line;end;-- The variable Matrix is popped off the stack automaticallyendTwo_Dimensional_Arrays;
begin comment Create a two-dimensional array at runtime - Algol 60; integer n,m; ininteger(0,m); ininteger(0,n); begin integer array a[1:m,1:n]; a[m,n] := 99; outinteger(1,a[m,n]);outstring(1,"\n") end; comment array a : out of scope;end
55
99
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]))begininteger 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 %endTwo Dimensional Array ExerciseLength of first dimension:->6Length of second dimension:->7Stored value at 1,1 = 99
begin integer dimension1UpperBound, dimension2UpperBound; write( "upper bound for dimension 1: " ); read( dimension1UpperBound ); write( "upper bound for dimension 2: " ); read( dimension2UpperBound ); begin % we start a new block because declarations must precede statements % % and variables in array bounds must be from outside the block % integer array matrix ( 1 :: dimension1UpperBound , 1 :: dimension2UpperBound ); % set the first element - the program will crash if the user input % % upper bounds less than 1 % matrix( 1, 1 ) := 3; % write it % write( matrix( 1, 1 ) ); % the array is automatically deleted when the block ends % endend.
Amazing Hopper crea arrays de forma dinámica.
#include <flow.h>#import lib/input.bas.lib#include include/flow-input.hDEF-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 */ CENDENDSUBRUTINESInput size rows : 30 Input size cols : 30 Element at position 1,1 : 100
Arrays are an integral part of APL. Array size, shape, and data type can be easily manipulated at runtime.
array←mn⍴0⍝ array of zeros with shape of m by n.array[1;1]←73⍝ assign a value to location 1;1.array[1;1]⍝ read the value back out⎕ex'array'⍝ erase the array
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.
setRtotext returnedof(display dialog"Enter number of rows:"defaultanswer2)asintegersetctotext returnedof(display dialog"Enter number of columns:"defaultanswer2)asintegersetarrayto{}repeatwithifrom1toRsettempto{}repeatwithjfrom1tocsettemp'sendto0endrepeatsetarray'sendtotempendrepeat-- Address the first column of the first row:setarray'sitem1'sitem1to-10-- Negative index values can be used to address from the end:setarray'sitem-1'sitem-1to10-- Access an item (row 2 column 1):setxtoarray'sitem2'sitem1returnarray-- Destroy array (typically unnecessary since it'll automatically be destroyed once script ends).setarrayto{}
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 ideallyshould 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 thereturn statement prevents the last line from being executed anyway.
/* 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 *//*********************************/.dataszMessRead1: .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 *//*********************************/.bsssZoneConv: .skip BUFFERSIZE // conversion buffersZoneConv1: .skip BUFFERSIZE // conversion buffersZoneConv2: .skip BUFFERSIZE // conversion buffersBuffer: .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 szCarriageReturniAdrsZoneConv: .int sZoneConviAdrsZoneConv1: .int sZoneConv1iAdrsZoneConv2: .int sZoneConv2iAdrszMessRead1: .int szMessRead1 iAdrszMessRead2: .int szMessRead2 iAdrsBuffer: .int sBufferiAdrszMessResult: .int szMessResultiAdrszMessStart: .int szMessStartiAdrszMessIndice1: .int szMessIndice1iAdrszMessIndice2: .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,#16100: 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,#41: @ loop extract address string on stack ldr r0,[fp,r2,lsl #2] bl affichageMess subs r2,#1 bge 1b100: pop {r1-r4,fp,pc}/***************************************************//* ROUTINES INCLUDE *//***************************************************/.include "../affichage.inc"Program 32 bits start.Input size level 1 : 10Input size level 2 : 5Indice 1 =1 Indice 2 =0 Item = 20Indice 1 =9 Indice 2 =4 Item = 196
width:to:integerinput"give me the array's width:"height:to:integerinput"give me the array's height:"arr:array.of:@[widthheight]0x:random0decwidthy:random0decheightarr\[x]\[y]: 123print["item at ["x","y"] ="arr\[x]\[y]]
give me the array's width: 10give me the array's height: 2item at [ 9 , 0 ] = 123
Array:=[]InputBox,data,,EntertwointegersseparatedbyaSpace:`n(ex.57)StringSplit,i,data,%A_Space%Array[i1,i2]:="that element"MsgBox,%"Array["i1","i2"] = "Array[i1,i2]
; == 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); == create arrayDim$a2D[$aDimension[0]][$aDimension[1]]; == write value to last row/last column$a2D[UBound($a2D)-1][UBound($a2D,2)-1]='test string'; == output this value to MsgBoxMsgBox(0,'Output','row['&UBound($a2D)-1&'], col['&UBound($a2D,2)-1&']'&@CRLF&'= '&$a2D[UBound($a2D)-1][UBound($a2D,2)-1])
AWK has no multidimensional array; but AWK arrays (which areAssociative 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.
/[0-9]+ [0-9]+/{for(i=0;i<$1;i++){for(j=0;j<$2;j++){arr[i,j]=i*j}}# how to scan "multidim" array as explained in the GNU AWK manualfor(combinarr){split(comb,idx,SUBSEP)printidx[1]","idx[2]"->"arr[idx[1],idx[2]]}}
10 INPUT "ENTER TWO INTEGERS:"; X%, Y%20 DIM A%(X% - 1, Y% - 1)30 X% = RND(1) * X%40 Y% = RND(1) * Y%50 A%(X%, Y%) = -3276760 PRINT A%(X%, Y%)70 CLEAR
arraybase 1input integer "Enter one positive integer: ", iinput integer "Enter other positive integer: ", jdim a(i, j)a[i, j] = i * jprint "a("; string(i); ","; string(j); ") = "; a[i, j]end10input"Enter two positive integers, separated by a comma? ";i,j20dimarray(i,j)30array(i,j)=i*j40print"a(";str$(i);",";str$(j);") = ";array(i,j)50erasearray
10INPUT"Enter two positive integers, separated by a comma";I,J20DIMARRAY(I,J)30ARRAY(I,J)=I*J40PRINT"a(";STR$(I);",";STR$(J);" ) =";ARRAY(I,J)50ERASEARRAY
10PRINT"ENTER ONE POSITIVE INTEGER: "20INPUTI30PRINT"ENTER OTHER POSITIVE INTEGER: "40INPUTJ50LETA(I,J)=I*J60PRINT"A(";I;",";J;") = ";A(I,J)70END
TheGW-BASIC solution works without any changes.
INPUT"Enter two positive integers, separated by a comma";i,jDIMarray(1TOi,1TOj)array(i,j)=i*jPRINT"a(";STR$(i);",";STR$(j);" ) = ";array(i,j)ERASEarray
INPUTprompt"Enter two positive integers, separated by a comma ":i,jDIMarray(0,0)MATREDIMarray(1TOi,1TOj)LETarray(i,j)=i*jPRINT"a(";STR$(i);",";STR$(j);") =";array(i,j)MATREDIMarray(0,0)END
PROGRAM"Create a two-dimensional array at runtime"VERSION"0.0001"DECLAREFUNCTIONEntry()FUNCTIONEntry()i$=INLINE$("Enter one positive integer: ")j$=INLINE$("Enter other positive integer: ")i=SSHORT(i$)j=SSHORT(j$)DIMa[i,j]a[i,j]=i*jPRINT"a(";STRING(i);", ";STRING(j);") =";a[i,j]ENDFUNCTION
input"Enter one positive integer: "iinput"Enter other positive integer: "jdima(i,j)a(i,j)=i*jprint"a(",str$(i),",",str$(j),") = ",a(i,j)exit
INPUT"Enter array dimensions separated by a comma: "a%,b%DIMarray(a%,b%)array(1,1)=PIPRINTarray(1,1)
Note: Size of array may be limited by RAM availability in some Commodore machines.
10printchr$(147);chr$(14);15print"Size of array:"20print"Columns (1-20)";:inputx%25ifx%<1orx%>20thenprint"Try again.":goto2030print"Rows (1-20)";:inputy%35ify%<1ory%>20thenprint"Try again.":goto3040x%=x%-1:y%=y%-1:dima$(x%,y%)50nx=int(rnd(1)*x%):ny=int(rnd(1)*y%)60a$(nx,ny)="X"70print"Element";nx;",";ny;"= '";a$(nx,ny);"'"80clr:remclearvariablesfromram
Size of array:Columns (1-20)? 10Rows (1-20)? 10Element 6 , 3 = 'X'ready.print a$(6,3)ready.
' FB 1.05.0 Win64DimAsIntegeri,jInput"Enter two positive integers, separated by a comma";i,jDima(1Toi,1Toj)AsIntegera(i,j)=i*jPrint"a(";Str(i);",";Str(j);") =";a(i,j)EraseaPrintPrint"Press any key to quit"Sleep
Enter two positive integers, separated by a comma? 4, 7a(4,7) = 28
100 INPUT PROMPT "Enter array dimensions separated by a coma: ":A,B110 NUMERIC ARRAY(1 TO A,1 TO B)120 LET ARRAY(1,1)=PI130 PRINT ARRAY(1,1)
Arrays can hold numbers ( eg age( 100)( or strings ( eg name$( 100))LB arrays can only be one or two dimensioned.If an array is not DIMensioned explicitly, then the array will be limited to 11 elements, 0 to 10.Non DIMensioned double subscript arrays will be limited to 100 elements 0 to 9 by 0 to 9.The DIM statement can be followed by a list of arrays to be dimensioned, separated by commas.REDIM redimensions an already dimensioned array and clears all elements to zero (or to an empty string in the case of string arrays).This can be very useful for writing applications that have data sets of unknown size.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.
input "Enter first array dimension "; ainput "Enter second array dimension "; bdim array( a, b)array( 1, 1) = 123.456print array( 1, 1)end
IfOpenConsole()Definex,yPrint("Input X-Size: ")x=Val(Input())Print("Input Y-Size: ")y=Val(Input())Dima(x,y);Shouldreallycheckifx&yarelargerthen1,butthatwouldbelessfun....a(1,1)=Random(1000)PrintN("a(1,1)= "+Str(a(1,1)))PrintN("Press ENTER to exit"):Input()End;ClosedownandletPureBasicdeletetheConsoleandallvariables.EndIf
CLSINPUTa,b'inputs need to be separated by commasDIMarray(1TOa,1TOb)array(1,1)=42PRINTarray(1,1)ERASEarray
print "Enter array 1 greater than 0"; : input a1print "Enter array 2 greater than 0"; : input a2 dim chrArray$(max(a1,1),max(a2,1))dim numArray(max(a1,1),max(a2,1))chrArray$(1,1) = "Hello"numArray(1,1) = 987.2print chrArray$(1,1);" ";numArray(1,1)
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 useCLEAR to destroy the array (and all the other variables in the program).
10PRINT"1ST DIMENSION: ";20INPUTD130PRINTD140PRINT"2ND DIMENSION: ";50INPUTD260PRINTD270DIMA(D1,D1)80PRINT"ARRAY CREATED"90LETX=1+INT(D1*RND)100LETY=1+INT(D2*RND)110LETA(X,Y)=37120PRINT"ITEM ";X;", ";Y;" = ";A(X,Y)130CLEAR140PRINT"ARRAY DESTROYED"
1ST DIMENSION: 112ND DIMENSION: 6ARRAY CREATEDITEM 7, 4 = 37ARRAY DESTROYED
10INPUT"Size? ";rows;"*";columns20DIMa(rows,columns):REMdefinesanumericarray30LETa=INT(RND*rows)+1:LETc=INT(RND*columns+1):REMthearrayislabelleda,buttheletteraisstillavailableforvariableassignment40LETa(a,c)=150PRINTa(a,c)60DIMa(1):REMarrayscannotberemovedwithoutCLEARingtheentirevariablespace,butredimensioningthemto1willsavemostofthespacetheyused
Input "ROWS? ",RInput "COLS? ",C{R,C}→dim([A])42→[A](1,1)Disp [A](1,1)DelVar [A]ModuleProgramSubMain()Console.WriteLine("Enter two space-delimited integers:")Diminput=Console.ReadLine().Split()Dimrows=Integer.Parse(input(0))Dimcols=Integer.Parse(input(1))' VB uses max-index for array creation.Dimarr(rows-1,cols-1)AsIntegerarr(0,0)=2Console.WriteLine(arr(0,0))EndSubEndModule
Enter two space-delimited integers:5 422
#!/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@
4 2┌─ ╵ 0 1 2 3 4 5 6 7 ┘
#include<stdio.h>intmain(intargc,char**argv){intuser1=0,user2=0;printf("Enter two integers. Space delimited, please: ");scanf("%d %d",&user1,&user2);intarray[user1][user2];array[user1/2][user2/2]=user1+user2;printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);return0;}
Allocate multi-dimensional arrays with a single call to malloc. The demonstration code builds a rank 3 array.
/* assume this file is c.c , compile and run on linux: cc -Wall -g -DCOMPILE_EXAMPLE c.c -lm -o c && ./c*/#include<stdlib.h>#include<stdio.h>staticvoiderror(intstatus,char*message){fprintf(stderr,"\n%s\n",message);exit(status);}staticvoid*dwlcalloc(intn,size_tbytes){void*rv=(void*)calloc(n,bytes);if(NULL==rv)error(1,"memory allocation failure");returnrv;}void*allocarray(size_trank,size_t*shape,size_titemSize){/* Allocates arbitrary dimensional arrays (and inits all pointers) with only 1 call to malloc. Lambert Electronics, USA, NY. This is wonderful because one only need call free once to deallocate the space. Special routines for each size array are not need for allocation of for deallocation. Also calls to malloc might be expensive because they might have to place operating system requests. One call seems optimal. */size_tsize,i,j,dataSpace,pointerSpace,pointers,nextLevelIncrement;char*memory,*pc,*nextpc;if(rank<2){if(rank<0)error(1,"invalid negative rank argument passed to allocarray");size=rank<1?1:*shape;returndwlcalloc(size,itemSize);}pointerSpace=0,dataSpace=1;for(i=0;i<rank-1;++i)pointerSpace+=(dataSpace*=shape[i]);pointerSpace*=sizeof(char*);dataSpace*=shape[i]*itemSize;memory=pc=dwlcalloc(1,pointerSpace+dataSpace);pointers=1;for(i=0;i<rank-2;){nextpc=pc+(pointers*=shape[i])*sizeof(char*);nextLevelIncrement=shape[++i]*sizeof(char*);for(j=0;j<pointers;++j)*((char**)pc)=nextpc,pc+=sizeof(char*),nextpc+=nextLevelIncrement;}nextpc=pc+(pointers*=shape[i])*sizeof(char*);nextLevelIncrement=shape[++i]*itemSize;for(j=0;j<pointers;++j)*((char**)pc)=nextpc,pc+=sizeof(char*),nextpc+=nextLevelIncrement;returnmemory;}#ifdef COMPILE_EXAMPLE#include<string.h>#include<math.h>#define Z 5#define Y 10#define X 39#define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L))voidp_char(void*pv){chars[3];inti=0;s[i++]=' ',s[i++]=*(char*)pv,s[i++]=0;fputs(s,stdout);}voiddisplay(void*a,size_trank,size_t*shape,void(*f)(void*)){inti;if(0==rank)(*f)(a);elseif(1==rank){for(i=0;i<*shape;++i)(*f)(a+i);putchar('\n');}else{for(i=0;i<*shape;++i)display(((void**)a)[i],rank-1,shape+1,f);putchar('\n');}}intmain(){/* character cell 3D graphics. Whoot */char***array;floatx,y,z;size_trank,shape[3],i,j,k;rank=0;shape[rank++]=Z,shape[rank++]=Y,shape[rank++]=X;array=allocarray(rank,shape,sizeof(char));memset(**array,' ',X*Y*Z*(sizeof(***array)));/* load the array with spaces */for(i=0;i<X;++i){x=i/(float)X;for(j=0;j<Y;++j){y=j/(float)X;z=x*y*(4*M_PI);z=5.2*(0.5+(0.276765-sin(z)*cos(z)*exp(1-z))/0.844087);/* a somewhat carefully designed silly function *//* printf("%g %g %g\n", x, y, z); */k=(int)z;array[BIND(k,0,Z-1)][j][i]='@';/* BIND ensures a valid index */}}display(array,rank,shape,p_char);puts("\nIt is what it is.");free(array);returnEXIT_SUCCESS;}#endif
This style is supported by all 'C' compilers.
#include<stdio.h>#include<stdlib.h>intmain(intargc,char**argv){intuser1=0,user2=0;int*a1,**array,row;printf("Enter two integers. Space delimited, please: ");scanf("%d %d",&user1,&user2);a1=malloc(user1*user2*sizeof(int));array=malloc(user1*sizeof(int*));for(row=0;row<user1;row++)array[row]=a1+row*user2;array[user1/2][user2/2]=user1+user2;printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);free(array);free(a1);return0;}
This style also supports more efficient memory utilization if you're only using a portion of thearray. If you only need the upper right half of a square array, you can do something like the following.
#include<stdio.h>#include<stdlib.h>intmain(intargc,char**argv){intuser1=0;intspace_needed;int*a1,**array;introw,col,offset;printf("Enter size of array: ");scanf("%d",&user1);space_needed=(user1+1)*user1/2;a1=malloc(space_needed*sizeof(*a1));array=malloc(user1*sizeof(*array));for(row=0,offset=0;row<user1;offset+=(user1-row),row++){array[row]=a1+offset-row;for(col=row;col<user1;col++)array[row][col]=1+col-row;}for(row=0;row<user1;row++)printf("%d ",array[row][user1-1]);printf("\n");free(array);free(a1);return0;}
This approach most closely matches the C99 example, asalloca allocates on thestack, rather than theheap, asmalloc does.
#include<stdio.h>#include<alloca.h>intmain(intargc,char**argv){intuser1=0,user2=0;int*a1,**array,row;printf("Enter two integers. Space delimited, please: ");scanf("%d %d",&user1,&user2);a1=alloca(user1*user2*sizeof(int));array=alloca(user1*sizeof(int*));for(row=0;row<user1;row++)array[row]=a1+row*user2;array[user1/2][user2/2]=user1+user2;printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);return0;}
classProgram{staticvoidMain(string[]args){Console.WriteLine("Enter two integers. Space delimited please: ");strings=Console.ReadLine();int[,]myArray=newint[(int)s[0],(int)s[2]];myArray[0,0]=2;Console.WriteLine(myArray[0,0]);Console.ReadLine();}}
#include<iostream>intmain(){// read valuesintdim1,dim2;std::cin>>dim1>>dim2;// create arraydouble*array_data=newdouble[dim1*dim2];double**array=newdouble*[dim1];for(inti=0;i<dim1;++i)array[i]=array_data+dim2*i;// write elementarray[0][0]=3.5;// output elementstd::cout<<array[0][0]<<std::endl;// get rid of arraydelete[]array;delete[]array_data;return0;}
#include<iostream>#include<vector>intmain(){// read valuesintdim1,dim2;std::cin>>dim1>>dim2;// create arraystd::vector<std::vector<double>>array(dim1,std::vector<double>(dim2));// write elementarray[0][0]=3.5;// output elementstd::cout<<array[0][0]<<std::endl;// the array is automatically freed at the end of main()return0;}
#include<iostream>#include<boost/multi_array.hpp>typedefboost::multi_array<double,2>two_d_array_type;intmain(){// read valuesintdim1,dim2;std::cin>>dim1>>dim2;// create arraytwo_d_array_typeA(boost::extents[dim1][dim2]);// write elementA[0][0]=3.1415;// read elementstd::cout<<A[0][0]<<std::endl;return0;}
#include<cstdlib>#include<boost/numeric/ublas/matrix.hpp>#include<boost/numeric/ublas/io.hpp>intmain(constintargc,constchar**argv){if(argc>2){usingnamespaceboost::numeric::ublas;matrix<double>m(atoi(argv[1]),atoi(argv[2]));// buildfor(unsignedi=0;i<m.size1();i++)for(unsignedj=0;j<m.size2();j++)m(i,j)=1.0+i+j;// fillstd::cout<<m<<std::endl;// printreturnEXIT_SUCCESS;}returnEXIT_FAILURE;}
importStdEnvStart::*World->{{Real}}Startworld#(console,world)=stdioworld(_,dim1,console)=freadiconsole(_,dim2,console)=freadiconsole=createArraydim1(createArraydim21.0)
(let[rows(Integer/parseInt(read-line))cols(Integer/parseInt(read-line))a(to-array-2d(repeatrows(repeatcolsnil)))](aseta0012)(println"Element at 0,0:"(ageta00)))
prompt = proc (s: string) returns (int) stream$puts(stream$primary_output(), s) return(int$parse(stream$getl(stream$primary_input())))end promptstart_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_upWidth? 8Height? 6arr[5][4] = 123
(let((d1(read))(d2(read)))(assert(and(typepd1'(integer1))(typepd2'(integer1)))(d1d2))(let((array(make-array(listd1d2):initial-elementnil))(p10)(p2(floord22)))(setf(arefarrayp1p2)t)(print(arefarrayp1p2))))
Theassert will allow the user to reenter the dimensions if they are not positive integers.
Arrays in Component Pascal are started from zero index. No DISPOSE-like procedures because of garbage collection.
MODULETestArray;(* Implemented in BlackBox Component Builder *)IMPORTOut;(* Open array *)PROCEDUREDoTwoDim*;VARd:POINTERTOARRAYOFARRAYOFINTEGER;BEGINNEW(d,5,4);(* allocating array in memory *)d[1,2]:=100;(* second row, third column element *)d[4,3]:=-100;(* fifth row, fourth column element *)Out.Int(d[1,2],0);Out.Ln;Out.Int(d[4,3],0);Out.Ln;ENDDoTwoDim;ENDTestArray.
require"random"first=gets.not_nil!.to_i32second=gets.not_nil!.to_i32arr=Array(Array(Int32)).new(first,Array(Int32).newsecond,0)random=Random.newfirst=random.rand0..(first-1)second=random.rand0..(second-1)arr[first][second]=random.next_intputsarr[first][second]
voidmain(){importstd.stdio,std.conv,std.string;intnRow,nCol;write("Give me the numer of rows: ");try{nRow=readln.strip.to!int;}catch(StdioException){nRow=3;writeln;}write("Give me the numer of columns: ");try{nCol=readln.strip.to!int;}catch(StdioException){nCol=5;writeln;}autoarray=newfloat[][](nRow,nCol);array[0][0]=3.5;writeln("The number at place [0, 0] is ",array[0][0]);}
Give me the numer of rows: Give me the numer of columns: The number at place [0, 0] is 3.5
Dimensions are generated randomly, not input by user.
programProject1;{$APPTYPE CONSOLE}usesSysUtils;varmatrix:arrayofarrayofByte;i,j:Integer;beginRandomize;//Finalization is not required in this case, but you have to do//so when reusing the variable in scopeFinalize(matrix);//Init first dimension with random size from 1..10//Remember dynamic arrays are indexed from 0SetLength(matrix,Random(10)+1);//Init 2nd dimension with random sizes toofori:=Low(matrix)toHigh(matrix)doSetLength(matrix[i],Random(10)+1);//End of code, the following part is just outputWriteln(Format('Total amount of columns = %.2d',[Length(matrix)]));fori:=Low(matrix)toHigh(matrix)doWriteln(Format('Column %.2d = %.2d rows',[i,Length(matrix[i])]));Readln;end.
Test run:
Total amount of columns = 10Column 00 = 04 rowsColumn 01 = 08 rowsColumn 02 = 09 rowsColumn 03 = 05 rowsColumn 04 = 01 rowsColumn 05 = 04 rowsColumn 06 = 07 rowsColumn 07 = 04 rowsColumn 08 = 10 rowsColumn 09 = 02 rows
Since DuckDB has a variety of ways to represent lists,there are many possibilities for representing an m * n array,including as a table with m*n rows or with m rows and n columns, or as a list of lists, or even as a two-dimensional DuckDB array (e.g. INTEGER[2][3]).
Each possibility has its pros and cons.For example, the m*n rows representation would be well-suited forsparse arrays, or if updates are frequent. The main disadvantageof using tables to back arrays in the DuckDB context is the difficultyof ensuring the integrity of the representation.
For this entry, we'll focus on the representation as a table with mrows, each having a column consisting of a list of length n. Sincethis approach blends the table and list-oriented approaches, focusingon it will highlight various aspects of both, for example, the tensionbetween the order-free semantics of SQL tables and the requirementsregarding the ordering of rows in a two-dimensional array.
Let's begin by assuming the two integers, m and n, are provided asenvironment variables, M and N, and that the array is intended forholding DOUBLE values.
The proper ordering of rows will be taken care of by defining a column, i,to index the rows. Ideally, we would start with a declaration such as:
i INTEGER UNIQUE check(i>0), check(i<= getenv('M'))However, DuckDB currently makes the updating of rows constrained by UNIQUEtedious and/or inefficient, and so we'll just use `NOT NULL` instead.
To avoid having to specify an ORDER BY clause in queries,we will define a VIEW of the table, along the lines of:
create view t as from t_ order by i;
where t_ is the backing table.
#Createanunnamedm*narrayasatablewithmrows,eachrowbeingalistcreateorreplacefunctionmatrix(m,n,init)astable(withrecursiverowas(selectlist_transform(range(0,n),x->z)asrowfrom(selectinitasz)),cteas(select1asi,rowfromrowunionallselecti+1,rowfromctewherei<m)fromcte);#Thebackingtablecreateorreplacetablet_(iINTEGERNOTNULLcheck(i>0),check(i<=getenv('M')::INTEGER),rowDOUBLE[]);#Theviewcreateorreplaceviewtasfromt_orderbyi;#Initializethebackingtableinsertintot_frommatrix(getvariable('M')::INT,getvariable('N')::INT,0.0);prepareupdate_matrixas/* $1=i $2=j $3=value */updatet_setrow=row[1:$2-1]||[$3]||row[$2+1:]wherei=$1;createorreplacefunctionmatrix_get(ii,jj)as(selectrow[jj]fromtwherei=ii);
ExamplesIn the following typescript, "D " is the DuckDB prompt.
D execute update_matrix(1,1,10.0);D execute update_matrix(2,2,20); -- notice the implicit conversion that will take placeD from t;┌───────┬───────────────────────┐│ i │ row ││ int32 │ double[] │├───────┼───────────────────────┤│ 1 │ [10.0, 0.0, 0.0, 0.0] ││ 2 │ [0.0, 20.0, 0.0, 0.0] ││ 3 │ [0.0, 0.0, 0.0, 0.0] │└───────┴───────────────────────┘D select matrix_get(2,2);┌──────────────────┐│ matrix_get(2, 2) ││ double │├──────────────────┤│ 20.0 │└──────────────────┘# Since t and t_ have not been persisted, dropping them explicitly is probably unnecessary,# but could be achieved by:D drop view t;D drop table t_;
write "Number of rows: "nrows = number inputprint nrowswrite "Number of columns: "ncols = number inputprint ncols# len a[][] nrowsfor i to nrows len a[i][] ncols.a[1][1] = 11print a[1][1]len a[][] 0
ELENA 6.x :
Typified array
import extensions; public Program(){ var n := new Integer(); var m := new Integer(); Console.write("Enter two space delimited integers:"); Console.loadLine(n,m); var myArray := class Matrix<int>.allocate(n,m); myArray.setAt(0,0,2); Console.printLine(myArray.at(0, 0))}Jagged array
import system'routines;import extensions; public Program(){ auto n := new Integer(); 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"; Console.printLine(myArray2[0][0]); Console.printLine(myArray2[1][0]); }defmoduleTwoDimArraydodefcreate(w,h)doList.duplicate(0,w)|>List.duplicate(h)enddefset(arr,x,y,value)doList.replace_at(arr,x,List.replace_at(Enum.at(arr,x),y,value))enddefget(arr,x,y)doarr|>Enum.at(x)|>Enum.at(y)endendwidth=IO.gets"Enter Array Width: "w=width|>String.trim()|>String.to_integer()height=IO.gets"Enter Array Height: "h=height|>String.trim()|>String.to_integer()arr=TwoDimArray.create(w,h)arr=TwoDimArray.set(arr,2,0,42)IO.puts(TwoDimArray.get(arr,2,0))
-module(two_dimensional_array).-export([create/2,get/3,set/4,task/0]).create(X,Y)->array:new([{size,X},{default,array:new([{size,Y}])}]).get(X,Y,Array)->array:get(Y,array:get(X,Array)).set(X,Y,Value,Array)->Y_array=array:get(X,Array),New_y_array=array:set(Y,Value,Y_array),array:set(X,New_y_array,Array).task()->{ok,[X,Y]}=io:fread("Input two integers. Space delimited, please: ","~d~d"),Array=create(X,Y),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)]).
7> two_dimensional_array:task().Input two integers. Space delimited, please: 4 5In position 3 4 we have 20
In ERRE language arrays created at run-time is "dynamic arrays". For this task will be enough this code:
PROGRAM DYNAMIC!$DYNAMICDIM A%[0,0]BEGIN PRINT(CHR$(12);) !CLS INPUT("Subscripts",R%,C%) !$DIM A%[R%,C%] A%[2,3]=6 PRINT("Value in row";2;"and col";3;"is";A%[2,3])END PROGRAMYou can redimension A% using pragmas:!$ERASE A% with a subsequent !$DIM A%[.,.]
include get.esequence arrayinteger height,width,i,jheight = floor(prompt_number("Enter height: ",{}))width = floor(prompt_number("Enter width: ",{}))array = repeat(repeat(0,width),height)i = floor(height/2+0.5)j = floor(width/2+0.5)array[i][j] = height + widthprintf(1,"array[%d][%d] is %d\n", {i,j,array[i][j]})openSystemletwidth=int(Console.ReadLine())letheight=int(Console.ReadLine())letarr=Array2D.createwidthheight0arr.[0,0]<-42printfn"%d"arr.[0,0]
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 :)
USING:iokernelmath.matricesmath.parserprettyprintsequences;IN:rosettacode.runtime2darray:set-Mi,j(elt{i,j}matrix--)[first2swap]dipnthset-nth;:Mi,j({i,j}matrix--elt)[first2swap]dipnthnth;:example(--)readlnreadln[string>number]bi@zero-matrix! create the array[[42{0 0}]dipset-Mi,j]! set the { 0 0 } element to 42[[{0 0}]dipMi,j.]! read the { 0 0 } elementbi;
?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}:cell-matrixcreate( width height "name" )over,*cellsallotdoes>( x y -- addr )dupcell+>r@*+cellsr>+;55cell-matrixtest3600test!00test@.\ 36
INTEGERDMATRIXmy-matrix{{&my-matrix{{89}}malloc8my-matrix{{34}}!my-matrix{{34}}@.&my-matrix{{}}free
In Fortran 90 and later
PROGRAMExampleIMPLICIT NONEINTEGER::rows,columns,errcheckINTEGER,ALLOCATABLE::array(:,:)WRITE(*,*)"Enter number of rows"READ(*,*)rowsWRITE(*,*)"Enter number of columns"READ(*,*)columnsALLOCATE(array(rows,columns),STAT=errcheck)! STAT is optional and is used for error checkingarray(1,1)=42WRITE(*,*)array(1,1)DEALLOCATE(array,STAT=errcheck)END PROGRAMExample
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 —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in itswebsite.
Inthis page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
There is no need to "release" the array, once the result is delivered, all intermediate elements are destroyed.
[rows, cols] = dims = eval[input["Enter dimensions: ", ["Rows", "Columns"]]]a = new array[dims, 0] // Create and initialize to 0a@(rows-1)@(cols-1) = 10println[a@(rows-1)@(cols-1)]
window 1CFStringRef iStr, jStrlong i, jiStr = input @"Enter one positive integer: "jStr = input @"Enter other positive integer: "i = intval(iStr)j = intval(jStr)mda (0, 0) = {i, j}mda (i, j) = i * jprintf @"mda(%ld, %ld) = %ld", i, j, mda_integer(i, j)mda_killHandleEventsWith inputs of 5 and 7:
mda(5, 7) = 35
# Creating an array of 0a:=NullMat(2,2);# [ [ 0, 0 ], [ 0, 0 ] ]# Some assignmentsa[1][1]:=4;a[1][2]:=5;a[2][1]:=3;a[2][2]:=4;a# [ [ 4, 5 ], [ 3, 4 ] ]Determinant(a);# 1
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].
packagemainimport"fmt"funcmain(){varrow,colintfmt.Print("enter rows cols: ")fmt.Scan(&row,&col)// allocate composed 2d arraya:=make([][]int,row)fori:=rangea{a[i]=make([]int,col)}// array elements initialized to 0fmt.Println("a[0][0] =",a[0][0])// assigna[row-1][col-1]=7// retrievefmt.Printf("a[%d][%d] = %d\n",row-1,col-1,a[row-1][col-1])// remove only referencea=nil// memory allocated earlier with make can now be garbage collected.}
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,
// allocate composed 2d arraya:=make([][]int,row)e:=make([]int,row*col)fori:=rangea{a[i]=e[i*col:(i+1)*col]}
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,
funcget(r,cint)int{returne[r*cols+c]}
Solution:
defmake2d={nrows,ncols->(0..<nrows).collect{[0]*ncols}}
Test:
defr=newRandom()System.in.splitEachLine(/,\s*/){dim->defnrows=dim[0]asintdefncols=dim[1]asintdefa2d=make2d(nrows,ncols)defrow=r.nextInt(nrows)defcol=r.nextInt(ncols)defval=r.nextInt(nrows*ncols)a2d[row][col]=valprintln"a2d[${row}][${col}] == ${a2d[row][col]}"a2d.each{printlnit}println()}
Input:
3, 54, 4
Output:
a2d[0][3] == 8[0, 0, 0, 8, 0][0, 0, 0, 0, 0][0, 0, 0, 0, 0]a2d[2][2] == 5[0, 0, 0, 0][0, 0, 0, 0][0, 0, 5, 0][0, 0, 0, 0]
importData.Arraydoitnm=a!(0,0)wherea=array((0,0),(n,m))[((0,0),42)]
REAL :: array(1)DLG(NameEdit=rows, NameEdit=cols, Button='OK', TItle='Enter array dimensions')ALLOCATE(array, cols, rows)array(1,1) = 1.234WRITE(Messagebox, Name) array(1,1)
All Icon and Unicon data objects are automatically reclaimed.Multiply dimensioned arrays are arrays of arrays in both languages.
proceduremain(args)nr:=integer(args[1])|3# Default to 3x3nc:=integer(args[2])|3A:=list(nr)every!A:=list(nc)x:=?nr# Select a random elementy:=?ncA[x][y]:=&piwrite("A[",x,"][",y,"] -> ",A[x][y])end
Sample output:
->ar 65 2A[37][1] -> 3.141592654
The following is only for demonstration. No real program should just assume that the user input is valid, integer, large enough etc.
read,x,prompt='Enter x size:'read,y,prompt='Enter y size:'d=fltarr(x,y)d[3,4]=5.6print,d[3,4];==> outputs 5.6delvar,d
The natural ways of creating a two dimensional array, from array dimensions, in J arei. and$
array1=:i.34NB. a 3 by 4 array with arbitrary valuesarray2=:56$2NB. a 5 by 6 array where every value is the number 2
To update the upper left corner of the array with the value 99, you might use}
array1=:99(<00)}array1
And, to retrieve that value you might use{
(<00){array1
Finally, J manages storage for you, so to delete the array, you could either have the name refer to a new value
array1=:0
or you could remove the name itself:
erase'array1'
Putting these ideas together and adding a few frills:
task=:verbdefineassert.y-:00+,yNB. error except when 2 dimensions are specifiedINIT=.0NB. array will be populated with this valueNEW=.1NB. we will later update one location with this valueARRAY=.y$INITNB. here, we create our 2-dimensional arrayINDEX=.<?$ARRAYNB. pick an arbitrary location within our arrayARRAY=.NEWINDEX}ARRAYNB. use our new value at that locationINDEX{ARRAYNB. and return the value from that location)
Passing two integers totask (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 ofNEW):
task99991
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:
'init new'=.' ';'x'NB. literals'init new'=.1r2;2r3NB. fractions'init new'=.a:;<<'Rosetta'NB. boxes
importjava.util.Scanner;publicclasstwoDimArray{publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intnbr1=in.nextInt();intnbr2=in.nextInt();double[][]array=newdouble[nbr1][nbr2];array[0][0]=42.0;System.out.println("The number at place [0 0] is "+array[0][0]);}}
varwidth=Number(prompt("Enter width: "));varheight=Number(prompt("Enter height: "));//make 2D arrayvararr=newArray(height);for(vari=0;i<h;i++){arr[i]=newArray(width);}//set value of elementa[0][0]='foo';//print value of elementconsole.log('arr[0][0] = '+arr[0][0]);//cleanup arrayarr=void(0);
jq data types are exactly those of JSON, so there are various alternatives for representing matrices.
One way to represent an m by n matrix is as an array of m arrays, one of which is of length n, and all of which have length less than or equal to n.
If M is such as array, then the syntax M[i][j] can be used to access the (i,j) element in the conventional sense, except that the index origin in jq is 0.
Note that the expressionM | getpath([i,j]) would also access M[i][j].
To set the M[i][j] element to, say, e, one can use theidiom:
M | setpath([i,j]; e)
Here's a simple example.
# A function to create an m x n matrix # filled with the input elementdef matrix(m;n): . as $init | ( [ range(0; n + 1) ] | map($init)) as $row | ( [ range(0; m + 1) ] | map($row)) ;# 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)
If the above is in a file, say 2d.jq, the invocation:
jq -n -c --arg m 2 --arg n 3 -f 2d.jq
would produce:
[[0,0,0,0],[0,0,99,0],[0,0,0,0]]
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.
functioninput(prompt::AbstractString)print(prompt)returnreadline()endn=input("Upper bound for dimension 1: ")|>x->parse(Int,x)m=input("Upper bound for dimension 2: ")|>x->parse(Int,x)x=rand(n,m)display(x)x[3,3]# overloads `getindex` generic functionx[3,3]=5.0# overloads `setindex!` generic functionx::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
Manually calling the garbage collector may or may not actually collect the array, but it will be eventually.
Program arguments provide dimensions of the array (4 5 in the example).
funmain(args:Array<String>){// buildvaldim=arrayOf(10,15)valarray=Array(dim[0],{IntArray(dim[1])})// fillarray.forEachIndexed{i,it->it.indices.forEach{j->it[j]=1+i+j}}// printarray.forEach{println(it.asList())}}
[1, 2, 3, 4, 5][2, 3, 4, 5, 6][3, 4, 5, 6, 7][4, 5, 6, 7, 8]
make "a2 mdarray [5 5]mdsetitem [1 1] :a2 0 ; by default, arrays are indexed starting at 1print mditem [1 1] :a2 ; 0
functionmultiply(n,a,b)ifa<=bthenreturnn,multiply(n,a+1,b)endenda,b=io.read()+0,io.read()+0matrix={multiply({multiply(1,1,b)},1,a)}matrix[a][b]=5print(matrix[a][b])print(matrix[1][1])
ModuleCheckArray{Do{Input"A, B=",A%,B%}UntilA%>0andB%>0\\1@is1Decimaladdone=lambdaN=1@->{=N:N++}DimBase1,Arr(A%,B%)<<addone()\\pialsoisdecimalArr(1,1)=piPrintArr(1,1)PrintArr()\\allvariables/arrays/innerfunctions/moduleserasednow}CheckArray
This hardly covers the richness and complexity of arrays in Maple, but here goes:
>a:=Array(1..3,1..4):# initialised to 0s>a[1,1]:=1:# assign an element>a[2,3]:=4:# assign an element>a;# display the array[1000][][0040][][0000]>a:='a':# unassign the name>gc();# force a garbage collection; may or may not actually collect the array, but it will be eventually
arrayFun[m_Integer,n_Integer]:=Module[{array=ConstantArray[0,{m,n}]},array[[1,1]]=RandomReal[];array[[1,1]]]
width=input('Array Width: ');height=input('Array Height: ');array=zeros(width,height);array(1,1)=12;disp(['Array element (1,1) = 'num2str(array(1,1))]);cleararray;% de-allocate (remove) array from workspace
Sample Output:
ArrayWidth:18ArrayHeight:12Arrayelement(1,1)=12
printf(true,"in the following terminate every number with semicolon `;'")$n:readonly("Input x-size: ")$m:readonly("Input y-size: ")$a:make_array(fixnum,n,m)$fillarray(a,makelist(i,i,1,m*n))$/* indexing starts from 0 */print(a[0,0]);print(a[n-1,m-1]);
a = getKBValue prompt:"Enter first dimension:"b = getKBValue prompt:"Enter second dimension:"arr1 = #()arr2 = #()arr2[b] = undefinedfor i in 1 to a do( append arr1 (deepCopy arr2))arr1[a][b] = 1print arr1[a][b]
This example uses a two level tree to mimic an 2D array.
ARA2D NEW X,Y,A,I,JREARA WRITE !,"Please enter two positive integers" READ:10 !,"First: ",X READ:10 !,"Second: ",Y GOTO:(X\1'=X)!(X<0)!(Y\1'=Y)!(Y<0) REARA FOR I=1:1:X FOR J=1:1:Y SET A(I,J)=I+J WRITE !,"The corner of X and Y is ",A(X,Y) KILL X,Y,A,I,J QUIT
Note: No attempt is made to validate the input.Any errors will be handled as exceptions by the underlying JVM.
/* NetRexx */optionsreplaceformatcommentsjavacrossrefsymbolsnobinarysay"give me the X and Y dimensions as two positive integers:"parseaskxDimyDimxPos=xDim%2--integerdividetogetclosetothemiddleofthearrayyPos=yDim%2arry=Rexx[xDim,yDim]arry[xPos,yPos]=xDim/yDim--makeupavalue...say"arry["xPos","yPos"]:"arry[xPos,yPos]return
Output:
give me the X and Y dimensions as two positive integers:1250 1777arry[625,888]: 0.703432752
importstrutils,rdstdinletw=readLineFromStdin("Width: ").parseInt()h=readLineFromStdin("Height: ").parseInt()# Create the rows.vars=newSeq[seq[int]](h)# Create the columns.foriin0..<h:s[i].newSeq(w)# Store a value in an element.s[0][0]=5# Retrieve and print it.echos[0][0]# The allocated memory is freed by the garbage collector.
class TwoDimArray { function : Main(args : String[]) ~ Nil { rows := Standard->ReadLine()->ToInt(); cols := Standard->ReadLine()->ToInt(); if(rows > 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]); } }}Being Objective-C derivated from C, theC solution works fine in Objective-C too.
The "OpenStep" frameworks (GNUstep, Cocoa) does not provide a class for multidimensional array; of course it can be implemented in several way (also as awrapper for the plain C way of handling arrays). Here I show a straightforward use of the NSMutableArray class.
#import <Foundation/Foundation.h>intmain(){@autoreleasepool{intnum1,num2;scanf("%d %d",&num1,&num2);NSLog(@"%d %d",num1,num2);NSMutableArray*arr=[NSMutableArrayarrayWithCapacity:(num1*num2)];// initialize it with 0sfor(inti=0;i<(num1*num2);i++)[arraddObject:@0];// replace 0s with something more interestingfor(inti=0;i<num1;i++){for(intj=0;j<num2;j++){arr[i*num2+j]=@(i*j);}}// access a value: i*num2+j, where i,j are the indexes for the bidimensional arrayNSLog(@"%@",arr[1*num2+3]);}return0;}
letnbr1=read_int();;letnbr2=read_int();;letarray=Array.make_matrixnbr1nbr20.0;;array.(0).(0)<-3.5;;print_floatarray.(0).(0);print_newline();;
or using the moduleBigarray:
letnbr1=read_int();;letnbr2=read_int();;letarr=Bigarray.Array2.createBigarray.float32Bigarray.c_layoutnbr1nbr2;;arr.{0,0}<-3.5;;print_floatarr.{0,0};print_newline();;
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).
Say"enter first dimension"pulld1say"enter the second dimension"pulld2a=.array~new(d1,d2)a[1,1]="Abc"saya[1,1]sayd1d2a[d1,d2]saya[10,10]max=1000000000b=.array~new(max,max)
D:\>rexx 2denter first dimension3enter the second dimension5Abc3 5 The NIL objectThe NIL object *-* Compiled method NEW with scope "Array" 11 *-* b = .array~new(max,max)Error 93 running D:\2d.rex line 11: Incorrect call to methodError 93.959: An array cannot contain more than 99,999,999 elements
Oz does not have multi-dimensional arrays. But we can create an array of arrays (similarly to most examples on this page):
declare %% Read width and height from stdin class TextFile from Open.file Open.text end StdIn = {New TextFile init(name:stdin)} Width = {String.toInt {StdIn getS($)}} Height = {String.toInt {StdIn getS($)}} %% create array Arr = {Array.new 1 Width unit}in for X in 1..Width do Arr.X := {Array.new 1 Height 0} end %% set and read element Arr.1.1 := 42 {Show Arr.1.1}tmp(m,n)={ my(M=matrix(m,n,i,j,0)); M[1,1]=1; M[1,1]};The following code is standard Extended Pascal (tested withgpc --extended-pascal):
programarray2d(input,output);typetArray2d(dim1,dim2:integer)=array[1..dim1,1..dim2]ofreal;pArray2D=^tArray2D;vard1,d2:integer;data:pArray2D;begin{ read values }readln(d1,d2);{ create array }new(data,d1,d2);{ write element }data^[1,1]:=3.5;{ output element }writeln(data^[1,1]);{ get rid of array }dispose(data);end.
beginvar(m,n):=ReadInteger2;vara:array[,]ofinteger:=newinteger[m,n];a[0,0]:=1;a[m-1,n-1]:=55;a.Println;vara1:=MatrRandomInteger(m,n);a1.Println;end.
3 4 1 0 0 0 0 0 0 0 0 0 0 55 76 53 12 48 79 22 15 43 40 97 26 64
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.
submake_array($ $){# get array sizes from provided params, but force numeric valuemy$x=($_[0]=~ /^\d+$/)?shift:0;my$y=($_[0]=~ /^\d+$/)?shift:0;# define array, then add multi-dimensional elementsmy@array;$array[0][0]='X ';# first by first element$array[5][7]='X 'if(5<=$yand7<=$x);# sixth by eighth element, if the max size is big enough$array[12][15]='X 'if(12<=$yand15<=$x);# thirteenth by sixteenth element, if the max size is big enough# loop through the elements expected to exist base on input, and display the elements contents in a gridforeachmy$dy(0..$y){foreachmy$dx(0..$x){(defined$array[$dy][$dx])?(print$array[$dy][$dx]):(print'. ');}print"\n";}}
The above is a bit verbose, here is a simpler implementation:
subarray{my($x,$y)=@_;map{[(0)x$x]}1..$y}my@square=array3,3;# everything above this line is mostly redundant in perl,# since perl would have created the array automatically when used.# however, the above function initializes the array elements to 0,# while perl would have used undef## $cube[3][4][5] = 60 # this is valid even if @cube was previously undefined$square[1][1]=1;print"@$_\n"for@square;>000>010>000
Obviously the sigificant part here is the three lines beginning "sequence array", the rest is all just boilerplate gui code.
-- demo\rosetta\Create2Darray.exwwithjavascript_semantics-- (layout/spacing leaves a little to be desired...)includepGUI.eIhandlelab,tab,res,dlgfunctionvaluechanged_cb(Ihandletab)strings=IupGetAttribute(tab,"VALUE")sequencer=scanf(s,"%d %d")iflength(r)=1theninteger{height,width}=r[1],i=floor(height/2+0.5),j=floor(width/2+0.5)ifi>0andj>0thensequencearray=repeat(repeat(0,width),height)array[i][j]=height+widths=sprintf("array[%d][%d] is %d\n",{i,j,array[i][j]})IupSetStrAttribute(res,"TITLE",s)IupRefresh(res)endifendifreturnIUP_DEFAULTendfunctionproceduremain()IupOpen()lab=IupLabel("Enter two numbers (>0) separated by a space")tab=IupText("VALUECHANGED_CB",Icallback("valuechanged_cb"),"EXPAND=HORIZONTAL")res=IupLabel("")dlg=IupDialog(IupVbox({IupHbox({lab,tab},"GAP=10,NORMALIZESIZE=VERTICAL"),IupHbox({res})},"MARGIN=5x5"),`TITLE="Create 2D array"`)IupShow(dlg)ifplatform()!=JSthenIupMainLoop()IupClose()endifendproceduremain()
The distributed version contains the older and simpler but console-only code.
include ..\Utilitys.pmt"Enter height: " input tonum nl"Enter width: " input tonum nl0 swap repeat swap repeat /# create two dimensional array/list. All zeroes #/-1 get 99 -1 set -1 set /# set the last element o last dimension #/pstack /# show the content of the stack #/-1 get -1 get "Value of the last element of the last dimension: " print print dropdrop /# remove array/list from the stack #/
With syntactic sugar
include ..\Utilitys.pmt"Enter height: " input tonum nl"Enter width: " input tonum nl0 swap repeat swap repeat /# create two dimensional array/list. All zeroes #/-1 get 99 ( -1 -1 ) mset /# set the last element o last dimension #/pstack /# show the content of the stack #/( -1 -1 ) mget "Value of the last element of the last dimension: " print print dropdrop /# remove array/list from the stack #/
With more syntactic sugar
include ..\Utilitys.pmt"Enter height: " input tonum nl"Enter width: " input tonum nl0 swap repeat swap repeat /# create two dimensional array/list. All zeroes #/99 ( -1 -1 ) sset /# set the last element o last dimension #/pstack /# show the content of the stack #/( -1 -1 ) sget "Value of the last element of the last dimension: " print printdrop /# remove array/list from the stack #/
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]).Input the number of rows and columns: 10 20201
(de 2dimTest (DX DY) (let A (make (do DX (link (need DY)))) (set (nth A 3 3) 999) # Set A[3][3] to 999 (mapc println A) # Print all (get A 3 3) ) ) # Return A[3][3](2dimTest 5 5)
Output:
(NIL NIL NIL NIL NIL)(NIL NIL NIL NIL NIL)(NIL NIL 999 NIL NIL)(NIL NIL NIL NIL NIL)(NIL NIL NIL NIL NIL)-> 999
/* First way using a controlled variable: */declare A(*,*) float controlled;get list (m, n);allocate A(m,n);get list (A);put skip list (A);/* The array remains allocated until the program terminates, *//* or until explicitly destroyed using a FREE statement. */free A;
6.00000E+0000 5.00000E+0000 4.00000E+0000 3.00000E+0000 2.00000E+0000 1.00000E+0000
/* Second way using a BEGIN block: */get list (m, n);begin; declare A(m, n) float; get list (A); put skip list (A);end;/* The array is automatically destroyed when the block terminates. */
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
/* Third way using a PROCEDURE block: */get list (m, n);call S (m, n);S: procedure (m, n); declare A(m, n) float; get list (A); put skip list (A);end S;/* The array is automatically destroyed when the procedure terminates. */
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
require"io2"require"table2"print("Enter the dimensions of the array:")localx=io.readInt(" First dimension : ",1)localy=io.readInt(" Second dimension : ",1)locala=table.create(x)fori=1,xdoa[i]=table.rep(y,0)enda[x][y]=42print($"\na[{x}][{y}] = {a[x][y]}")a=nil
Sample input/output (note: 1 based indexing):
Enter the dimensions of the array: First dimension : 3 Second dimension : 4a[3][4] = 42
vars itemrep;incharitem(charin) -> itemrep;;;; Read sizesvars n1 = itemrep(), n2= itemrep();;;; Create 0 based arrayvars ar = newarray([0 ^(n1 - 1) 0 ^(n2 - 1)], 0);;;; Set element value15 -> ar(0, 0);;;; Print element valuear(0,0) =>;;; Make sure array is unreferenced0 -> ar;
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.
Pop11 arrays may have arbitrary lower bounds, since we are given only size we create 0 based array.
functionRead-ArrayIndex([string]$Prompt="Enter an integer greater than zero"){[int]$inputAsInteger=0while(-not[Int]::TryParse(([string]$inputString=Read-Host$Prompt),[ref]$inputAsInteger)){$inputString=Read-Host"Enter an integer greater than zero"}if($inputAsInteger-gt0){return$inputAsInteger}else{return1}}$x=$y=$nulldo{if($x-eq$null){$x=Read-ArrayIndex-Prompt"Enter two dimensional array index X"}if($y-eq$null){$y=Read-ArrayIndex-Prompt"Enter two dimensional array index Y"}}until(($x-ne$null)-and($y-ne$null))$array2d=New-Object-TypeName'System.Object[,]'-ArgumentList$x,$y
Enter two dimensional array index X: 6Enter two dimensional array index Y: 6
Populate the array:
[int]$k=1for($i=0;$i-lt6;$i++){0..5|ForEach-Object-Begin{$k+=10}-Process{$array2d[$i,$_]=$k+$_}}
This is the entire array:
for($i=0;$i-lt6;$i++){"{0}`t{1}`t{2}`t{3}`t{4}`t{5}"-f(0..5|ForEach-Object{$array2d[$i,$_]})}
111213141516212223242526313233343536414243444546515253545556616263646566
Get an element of the array:
$array2d[2,2]
33
:-dynamicarray/2.run:-write('Enter two positive integers, separated by a comma: '),read((I,J)),assert(array(I,J)),ValueisI*J,format('a(~w,~w) = ~w',[I,J,Value]),retractall(array(_,_)).
width=int(raw_input("Width of myarray: "))height=int(raw_input("Height of Array: "))myarray=[[0]*widthforiinrange(height)]myarray[0][0]=3.5print(myarray[0][0])
Note: Some people may instinctively try to write myarray as [[0] * width] * height, but the * operator createsn references to [[0] * width]
You can also use a two element tuple to index a dictionary like so:
myarray={(w,h):0forwinrange(width)forhinrange(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.5print(myarray[(0,0)])
[ witheach peek ] is {peek} ( { p --> x ) [ dip dup witheach [ peek dup ] drop ] is depack ( { p --> * ) [ reverse witheach [ dip swap poke ] ] is repack ( * p --> { ) [ dup dip [ rot dip [ depack drop ] ] repack ] is {poke} ( x { p --> { ) [ 0 swap of nested swap of ] is 2array ( n n --> [ ) $ "Array width (at least 2): " input $->n drop $ "Array length (at least 5): " input $->n drop say "Creating " over echo say " by " dup echo say " array." cr 2array say "Writing 12345 to element {1,4} of array." cr 12345 swap ' [ 1 4 ] {poke} say "Reading element {1,4} of array: " ' [ 1 4 ] {peek} echoArray width (at least 2): 2Array length (at least 5): 5Creating 2 by 5 array.Writing 12345 to element {1,4} of array.Reading element {1,4} of array: 12345input<-readline("Enter two integers. Space delimited, please: ")dims<-as.numeric(strsplit(input," ")[[1]])arr<-array(dim=dims)ii<-ceiling(dims[1]/2)jj<-ceiling(dims[2]/2)arr[ii,jj]<-sum(dims)cat("array[",ii,",",jj,"] is ",arr[ii,jj],"\n",sep="")
Using a vector of vectors to represent arrays:
#lang racket(printf "Enter XY dimensions: ")(define xy (cons (read) (read)))(define array (for/vector ([x (car xy)]) (for/vector ([y (cdr xy)]) 0)))(printf "Enter a number for the top-left: ")(vector-set! (vector-ref array 0) 0 (read))(printf "Enter a number for the bottom-right: ")(vector-set! (vector-ref array (sub1 (car xy))) (sub1 (cdr xy)) (read))array
Output:
Enter XY dimensions: 3 3Enter a number for the top-left: 1Enter a number for the bottom-right: 9'#(#(1 0 0) #(0 0 0) #(0 0 9))
(formerly Perl 6)
Line 1: The input parse doesn't care how you separate the dimensions as long as there are two distinct numbers.
Line 2: The list replication operatorxx will automatically thunkify its left side so this produces new subarrays for each replication.
Line 3: Subscripting with a closure automatically passes the size of the dimension to the closure, so we pick an appropriate random index on each level.
Line 4: Print each line of the array.
my ($major,$minor) = prompt("Dimensions? ").comb(/\d+/);my @array = [ '@' xx $minor ] xx $major;@array[ *.rand ][ *.rand ] = ' ';.say for @array;Typical run:
Dimensions? 5x35[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @][@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @][@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @][@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @][@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
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-defineddimensions. They will make memory-efficient matrix storage and matrix operations possible.
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;Typical run:
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]]
matrix: array/initial [5 3] 0 ;; 5 rows, 3 colsmatrix/1/1: 1matrix/3/3: 2?? matrixprint ""foreach row matrix [ probe row ]
matrix: [[1 0 0] [0 0 0] [0 0 2] [0 0 0] [0 0 0]][1 0 0][0 0 0][0 0 2][0 0 0][0 0 0]
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: 3b: 2matrix/2/4: 27 ; use path syntax to access or assignmatrix/1/1: 99 ; series are 1-indexed in Red; there is no matrix/0/0matrix/(a)/(a): 10 ; accessing elements with words requires special carematrix/:b/:b: 33 ; alternativeprint mold matrix
What is the width of the array? 5What is the height of the array? 3[[99 0 0 0 0] [0 33 0 27 0] [0 0 10 0 0]]
IncludeHow to use
IncludeSource code
A two-dimensional array is just a stem variable with 2 tails: head.tail1.tail2. This mimics an array head[tail1,tail2].
In REXX, a callable part of the program may be a routine (no 'procedure' clause) or a procedure (with 'procedure' clause). In a routine, all vars are global. In a procedure, all vars are local except the ones mentioned in the expose clause. Local vars are always disposed of at return. A not initialized var has its name in upper case as value.
An array may be disposed of by the clause 'drop var'.
All these concepts are demonstrated in below program.
-- 23 Aug 2025include Settingsignal off novaluesay 'CREATE AN TWO-DIMENSIONAL ARRAY AT RUNTIME'say versionsaycall CreateMultcall ShowMult 'Global'call CreateAddicall ShowAddi 'Global'call CreateSubtcall ShowSubt 'Global'exitCreateMult:procedure expose Mult.arg xxdo i = 1 to 9 do j = 1 to 9 Mult.i.j=i*j endendreturnShowMult:parse arg xxsay ' 'xx 'multiplication table'say ' 'Copies('-',25)say ' 1 2 3 4 5 6 7 8 9'say ' 'Copies('-',25)do i = 1 to 9 call CharOut ,i do j = 1 to 9 call CharOut ,Right(Mult.i.j,3) end sayendsay ' 'Copies('-',25)sayreturnCreateAddi:proceduredo i = 1 to 9 do j = 1 to 9 Addi.i.j=i+j endendcall ShowAddi 'Local'returnShowAddi:parse arg xxsay ' 'xx 'addition table'say ' 'Copies('-',25)say ' 1 2 3 4 5 6 7 8 9'say ' 'Copies('-',25)if DataType(Addi.1.1) = 'CHAR' then do call CharOut ,' 'Addi.1.1 Addi.2. Addi.3.3'...' sayendelse do do i = 1 to 9 call CharOut ,i do j = 1 to 9 call CharOut ,Right(Addi.i.j,3) end say endendsay ' 'Copies('-',25)sayreturnCreateSubt:procedure expose Subt.do i = 1 to 9 do j = 1 to 9 Subt.i.j=i-j endendcall ShowSubt 'Global'drop Subt.returnShowSubt:parse arg xxsay ' 'xx 'subtraction table'say ' 'Copies('-',25)say ' 1 2 3 4 5 6 7 8 9'say ' 'Copies('-',25)if DataType(Subt.1.1) = 'CHAR' then do call CharOut ,' 'Subt.1.1 Subt.2. Subt.3.3'...' sayendelse do do i = 1 to 9 call CharOut ,i do j = 1 to 9 call CharOut ,Right(Subt.i.j,3) end say endendsay ' 'Copies('-',25)sayreturninclude AbendCREATE AN TWO-DIMENSIONAL ARRAY AT RUNTIMEREXX-Regina_3.9.7(MT) 5.00 18 Mar 2025 Global multiplication table ------------------------- 1 2 3 4 5 6 7 8 9 -------------------------1 1 2 3 4 5 6 7 8 92 2 4 6 8 10 12 14 16 183 3 6 9 12 15 18 21 24 274 4 8 12 16 20 24 28 32 365 5 10 15 20 25 30 35 40 456 6 12 18 24 30 36 42 48 547 7 14 21 28 35 42 49 56 638 8 16 24 32 40 48 56 64 729 9 18 27 36 45 54 63 72 81 ------------------------- Local addition table ------------------------- 1 2 3 4 5 6 7 8 9 -------------------------1 2 3 4 5 6 7 8 9 102 3 4 5 6 7 8 9 10 113 4 5 6 7 8 9 10 11 124 5 6 7 8 9 10 11 12 135 6 7 8 9 10 11 12 13 146 7 8 9 10 11 12 13 14 157 8 9 10 11 12 13 14 15 168 9 10 11 12 13 14 15 16 179 10 11 12 13 14 15 16 17 18 ------------------------- Global addition table ------------------------- 1 2 3 4 5 6 7 8 9 ------------------------- ADDI.1.1 ADDI.2. ADDI.3.3... ------------------------- Global subtraction table ------------------------- 1 2 3 4 5 6 7 8 9 -------------------------1 0 -1 -2 -3 -4 -5 -6 -7 -82 1 0 -1 -2 -3 -4 -5 -6 -73 2 1 0 -1 -2 -3 -4 -5 -64 3 2 1 0 -1 -2 -3 -4 -55 4 3 2 1 0 -1 -2 -3 -46 5 4 3 2 1 0 -1 -2 -37 6 5 4 3 2 1 0 -1 -28 7 6 5 4 3 2 1 0 -19 8 7 6 5 4 3 2 1 0 ------------------------- Global subtraction table ------------------------- 1 2 3 4 5 6 7 8 9 ------------------------- SUBT.1.1 SUBT.2. SUBT.3.3... -------------------------
See 'Enter width : ' give widthSee 'Enter height : ' give heightwidth=0+width height=0+heightaList = list(height) for x in aList x = list(width) nextaList[1][2] = 10 See aList[1][2] + nl
« "# rows?" "3" INPUT "# columns?" "5" INPUT@ ask for size, with 3 and 5 as default values 2 →LIST STR→ 0 CON@ create array in stack { 1 2 } TIME PUT@ put current time at array[1,2] { 1 2 } GET@ read array[1,2] and remove array from the stack» 'TASK' STO
puts 'Enter width and height: 'w=gets.to_iarr = Array.new(gets.to_i){Array.new(w)}arr[1][3] = 5p arr[1][3]use std::env;fn main() { let mut args = env::args().skip(1).flat_map(|num| num.parse()); let rows = args.next().expect("Expected number of rows as first argument"); let cols = args.next().expect("Expected number of columns as second argument"); assert_ne!(rows, 0, "rows were zero"); assert_ne!(cols, 0, "cols were zero"); // Creates a vector of vectors with all elements initialized to 0. let mut v = vec![vec![0; cols]; rows]; v[0][0] = 1; println!("{}", v[0][0]);}var a, b = integerprint "Two-Dimensional Array Example"input "Size of first dimension"; ainput "Size of second dimension"; bdim integer test_array(a, b)test_array(1,1) = 99 rem S-BASIC arrays are indexed from 1print "Value stored at 1,1 ="; test_array(1,1)end
Two-Dimensional Array ExampleSize of first dimension? 7Size of second dimension? 7Value stored at 1,1 = 99
object Array2D{ def main(args: Array[String]): Unit = { val x = Console.readInt val y = Console.readInt val a=Array.fill(x, y)(0) a(0)(0)=42 println("The number at (0, 0) is "+a(0)(0)) }}There is no two-dimensional array-type built in to Scheme, but there is a vector.
(import (scheme base) (scheme read) (scheme write));; Read x/y from user(define x (begin (display "X: ") (flush-output-port) (read)))(define y (begin (display "Y: ") (flush-output-port) (read)));; Create a vector, and fill it with a vector for each row(define arr (make-vector x))(do ((i 0 (+ 1 i))) ((= i x) ) (vector-set! arr i (make-vector y 0)));; set element (x/2, y/2) to 3(vector-set! (vector-ref arr (floor (/ x 2))) (floor (/ y 2)) 3)(display arr) (newline)(display "Retrieved: ")(display (vector-ref (vector-ref arr (floor (/ x 2))) (floor (/ y 2))))(newline)
X: 3Y: 5#(#(0 0 0 0 0) #(0 0 3 0 0) #(0 0 0 0 0))Retrieved: 3
There are SRFI libraries providing arrays. This example uses SRFI 63.
(import (except (scheme base) equal?) (scheme read) (scheme write) (srfi 63) ; an array SRFI );; Read x/y from user(define x (begin (display "X: ") (flush-output-port) (read)))(define y (begin (display "Y: ") (flush-output-port) (read)));; Create an array(define array (make-array #(0) x y));; Write to middle element of the array(array-set! array 3 (floor (/ x 2)) (floor (/ y 2)));; Retrieve and display result(display (array-ref array (floor (/ x 2)) (floor (/ y 2)))) (newline)
X: 3Y: 53
The array will be destroyed by the garbage collector, when it is no longer needed.
$ include "seed7_05.s7i";const proc: main is func local var integer: numRows is 0; var integer: numCols is 0; var array array integer: anArray is 0 times 0 times 0; begin write("Give me the numer of rows: "); readln(numRows); write("Give me the numer of columns: "); readln(numCols); anArray := numRows times numCols times 0; anArray[1][1] := 3; writeln("The number at place [1, 1] is " <& anArray[1][1]); end func;Output:
Give me the numer of rows: 5Give me the numer of columns: 7The number at place [1, 1] is 3
func make_matrix(x, y) { y.of { x.of(0) };}var y = Sys.scanln("rows: ").to_i;var x = Sys.scanln("cols: ").to_i;var matrix = make_matrix(x, y); # create the matrixmatrix[y/2][x/2] = 1; # write something inside itsay matrix; # display the matrixrows: 3cols: 4 [[0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]]
BEGIN INTEGER N,M; M := ININT; N := ININT; BEGIN INTEGER ARRAY A(1:M,1:N); A(M,N) := 99; OUTINT(A(M,N),0); OUTIMAGE; END; ! ARRAY A OUT OF SCOPE ;END.
10 20
99
(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"))
m := (FillInTheBlankMorph request: 'Number of rows?') asNumber.n := (FillInTheBlankMorph request: 'Number of columns?') asNumber.aMatrix := Matrix rows: m columns: n.aMatrix at: (aMatrix rowCount // 2) at: (aMatrix columnCount // 2) put: 3.4.e := aMatrix at: (aMatrix rowCount // 2) at: (aMatrix columnCount // 2).Transcript show: 'Entry is', e printString.
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.
|num1 num2 arr|num1 := stdin nextLine asInteger.num2 := stdin nextLine asInteger.arr := MultidimensionalArray new: { num1. num2 }.1 to: num1 do: [ :i | 1 to: num2 do: [ :j | arr at: { i. j } put: (i*j) ]].1 to: num1 do: [ :i | 1 to: num2 do: [ :j | (arr at: {i. j}) displayNl ]].A possible implementation for aBidimensionalArray class is the following (changingMulti intoBi and using this class, the previous code runs fine):
Object subclass: BidimensionalArray [ |biArr| <comment: 'bidim array'>].BidimensionalArray class extend [ new: biDim [ |r| r := super new. r init: biDim. ^ r ]].BidimensionalArray extend [ init: biDim [ biArr := Array new: (biDim at: 1). 1 to: (biDim at: 1) do: [ :i | biArr at: i put: (Array new: (biDim at: 2)) ]. ^ self ] at: biDim [ ^ (biArr at: (biDim at: 1)) at: (biDim at: 2) ] at: biDim put: val [ ^ (biArr at: (biDim at: 1)) at: (biDim at: 2) put: val ]].
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 specificdimension of the "array"). The final effect is the same as using an array (almost in theAWK sense) and the approach has some advantages.
|num1 num2 pseudoArr|num1 := stdin nextLine asInteger.num2 := stdin nextLine asInteger."we can 'suggest' an initial value for the number of ''slot'' the table can hold; anyway, if we use more than these, the table automatically grows"pseudoArr := LookupTable new: (num1 * num2).1 to: num1 do: [ :i | 1 to: num2 do: [ :j | pseudoArr at: {i. j} put: (i * j). ]].1 to: num1 do: [ :i | 1 to: num2 do: [ :j | (pseudoArr at: {i. j}) displayNl. ]].Note: trim(input) is needed for Snobol4+.
* # Get user X,Y dimensions output = 'Enter X,Y:'; xy = trim(input) xy break(',') . x ',' rem . y* # Define and create array, 1-based arr = array(x ',' y) ;* Or arr = array(xy)* # Display array prototype output = 'Prototype: ' prototype(arr) * # Assign elements, angle or square brackets* # Same array can hold ints, strings, etc. arr<x,y> = 99; arr[1,1] = 'dog' * # Display elements output = 'arr[' xy '] = ' arr[x,y] output = 'arr[1,1] = ' arr[1,1] * # Release array for garbage collection arr =endOutput:
Enter X,Y:5,5Prototype: 5,5arr[5,5] = 99arr[1,1] = dog
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");
display "Number of rows?" _request(nr)display "Number of columns?" _request(nc)matrix define a=J($nr,$nc,0)matrix a[1,2]=1.5matrix list amatrix drop a
This is also possible in Mata, except that console input is still done from Stata:
matamata stata display "Number of rows?" _request(nr)mata stata display "Number of columns?" _request(nc)nr = strtoreal(st_global("nr"))nc = strtoreal(st_global("nc"))a = J(nr,nc,0)a[1,2] = 1.5amata drop aendimport Foundationprint("Enter the dimensions of the array seperated by a space (width height): ")let fileHandle = NSFileHandle.fileHandleWithStandardInput()let dims = NSString(data: fileHandle.availableData, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString(" ")if let dims = dims where dims.count == 2{let w = dims[0].integerValuelet h = dims[1].integerValueif let w = w, h = h where w > 0 && h > 0 {var array = Array<[Int!]>(count: h, repeatedValue: Array<Int!>(count: w, repeatedValue: nil))array[0][0] = 2println(array[0][0])println(array)}}Enter the dimensions of the array seperated by a space (width height): 3 42[[2, nil, nil], [nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
Maps can have any item (except floating point numbers) as keys; key order is undefined.
tpl =: 'one' -> 1, 2 -> 'two' map =: tuple tpl as map \ 'map' is not a keyword print join map map as pairs \ converts to row, then joins values
(2, two) (one, 1)
Printed strings are not quoted.
puts "Enter width:"set width [gets stdin]puts "Enter height:"set height [gets stdin]# Initialize arrayfor {set i 0} {$i < $width} {incr i} {for {set j 0} {$j < $height} {incr j} {set arr($i,$j) ""}}# Store valueset arr(0,0) "abc"# Print valueputs "Element (0/0): $arr(0,0)"# Cleanup arrayunset arrToka 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.
[ ( x y -- address ) cells malloc >r dup cells >r [ r> r> r> 2dup >r >r swap malloc swap i swap array.put >r ] iterater> r> nip] is 2D-array[ ( a b address -- value ) array.get array.get] is 2D-get-element[ ( value a b address -- ) array.get array.put] is 2D-put-element
And a short test:
5 5 2D-array >r #! Create an array and save the pointer to it10 2 3 r@ 2D-put-element #! Set element 2,3 to 102 3 r@ 2D-get-element #! Get the element at 2,3r> drop #! Discard the pointer to the array
⋕&sc &pf "Enter a width: "⋕&sc &pf "Enter a height: "˜↯0⊟ # create 2D array filled with 0⍜⊡⋅3 1_2 # store 3 at row 1, col 2⟜&s # show array non-destructively⊡1_2 # retrieve element at row 1, col 2 # this also destroys the array
Enter a width: 4Enter a height: 2╭─╷ 0 0 0 0 0 0 3 0 ╯3
decl int width heightout "width: " consoleset width (in int console)out "height: " consoleset height (in int console)decl int<><> twodstreamfor (decl int i) (< i height) (inc i) append (new int<>) twodstreamend forfor (set i 0) (< i height) (inc i) decl int j for (set j 0) (< j width) (inc j) append 0 twodstream<i> end forend forset twodstream<0><0> 5out twodstream<0><0> endl console
Option ExplicitSub Main_Create_Array()Dim NbColumns As Integer, NbRows As Integer 'Get two integers from the user, Do NbColumns = Application.InputBox("Enter number of columns : ", "Numeric only", 3, Type:=1) NbRows = Application.InputBox("Enter number of rows : ", "Numeric only", 5, Type:=1) Loop While NbColumns = 0 Or NbRows = 0 'Create a two-dimensional array at runtime ReDim myArray(1 To NbRows, 1 To NbColumns) 'Write some element of that array, myArray(LBound(myArray, 1), UBound(myArray, 2)) = "Toto" 'and then output that element. MsgBox myArray(LBound(myArray, 1), UBound(myArray, 2)) 'destroy the array Erase myArrayEnd Sub" Create a two-dimensional array with r rows and c columns." The optional third argument specifies the initial value" (default is 0).function MakeArray(r, c, ...) if a:0 let init = a:1 else let init = 0 endif let temp = [] for c in range(a:c) call add(temp, init) endfor let array = [] for r in range(a:r) call add(array, temp[:]) endfor return arrayendfunctionlet rows = input("Enter number of rows: ")let cols = input("Enter number of columns: ")echo "\n"let array = MakeArray(rows, cols)let array[rows - 1][cols - 1] = rows * colsecho array[rows - 1][cols - 1]unlet arrayimport osfn 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 sizemut arr2d := [][]int{len: row.int(), init: []int{len: col.int()}}// assign valuesarr2d[0][0] = 7// viewprintln(arr2d)// cleararr2d.clear()}enter rows: 3enter cols: 3[[7, 0, 0], [0, 0, 0], [0, 0, 0]]
import "io" for Stdin, Stdoutvar xvar ySystem.print("Enter the dimensions of the array:")while (true) { System.write(" First dimension : ") Stdout.flush() x = Num.fromString(Stdin.readLine()) if (x && (x is Num) && (x.isInteger) && (x > 0) ) { System.write(" Second dimension : ") Stdout.flush() y = Num.fromString(Stdin.readLine()) if (y && (y is Num) && (y.isInteger) && (y > 0) ) break System.print("Dimension must be a positive integer.") } else { System.print("Dimension must be a positive integer.") }}// create the 2d arrayvar a = List.filled(x, null)for (i in 0...x) a[i] = List.filled(y, 0)// write an elementa[x - 1][y - 1] = 42// print itSystem.print("\na[%(x-1)][%(y-1)] = %(a[x-1][y-1])")// make the array eligible for garbage collectiona = nullExample session:
Enter the dimensions of the array: First dimension : 3 Second dimension : 4a[2][3] = 42
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;[X:= IntIn(0); Y:= IntIn(0); \get 2 dimensions from userA:= Reserve(X*IntSize);for I:= 0 to X-1 do A(I):= Reserve(Y*IntSize);A(X/2, Y/2):= X+Y;IntOut(0, A(X/2, Y/2)); CrLf(0);]
Space allocated by the Reserve intrinsic is automatically released whenthe procedure that calls Release returns.
Example of a 12000x100 integer array for a total of 1.2 million integers:
12000 10012100
zkl doesn't have a native array type but lists of lists can do the same thing. It is garbage collected so things are cleaned up implicitly.
This code creates a 2d row major zero filled array.
Since the array is row major, sub-scripting works as expected: [row][col].
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();The createLong method pre-allocates a list, optionally filled with a constant or computation.
Rows: 3columns: 4L(L(0,0,0,0),L(0,0,123,0),L(0,0,0,0))123
If you want Matrix/linear algebra, you can use the GNU Scientific Library:
var [const] GSL=Import("zklGSL");// libGSL (GNU Scientific Library)rows:=ask("Rows: ").toInt();cols:=ask("columns: ").toInt();m:=GSL.Matrix(rows,cols);m[1,2]=123;m.format().println();println(m[1,2]);Again, garbage collected.
Rows: 3columns: 4 0.00, 0.00, 0.00, 0.00 0.00, 0.00, 123.00, 0.00 0.00, 0.00, 0.00, 0.00123
module Main;typeMatrix = array *,* of integer;varm: Matrix;i,j: integer;beginwrite("first dim? ");readln(i);write("second dim? ");readln(j);m := new Matrix(i,j);m[0,0] := 10;writeln("m[0,0]:> ",m[0,0]);writeln("m[0,1].> ",m[0,1])end Main.first dim? 10second dim? 10m[0,0]:> 10m[0,1].> 0