This task is about arrays.

For hashes or associative arrays, please see Creating an Associative Array.

For a definition and in-depth discussion of what an array is, see Array.



Task

Show basic array syntax in your language.

Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).

Please discuss at Village Pump:   Arrays.

Please merge code in from these obsolete tasks:

   Creating an Array
   Assigning Values to an Array
   Retrieving an Element of an Array


Related tasks

   Collections
   Creating an Associative Array
   Two-dimensional array (runtime)


; constant array (elements are unchangeable) - the array is stored in the CODE segment
myarray db 'Array' ; db = define bytes - initializes 5 bytes with values 41, 72, 72, etc. (the ascii characters A,r,r,a,y)
myarray2 dw 'A','r','r','a','y' ; dw = define words - initializes 5 words (1 word = 2 bytes) with values 41 00 , 72 00, 72 00, etc.
; how to read index a of the array
        push acc
        push dph
        push dpl
        mov dpl,#low(myarray) ; location of array
        mov dph,#high(myarray)
        movc a,@a+dptr	; a = element a
        mov r0, a	; r0 = element a
        pop dpl
        pop dph
        pop acc		; a = original index again
 
; array stored in internal RAM (A_START is the first register of the array, A_END is the last)
; initalise array data (with 0's)
	push 0
	mov r0, #A_START
clear:
	mov @r0, #0
	inc r0
	cjne r0, #A_END, clear
	pop 0
; how to read index r1 of array
	push psw
	mov a, #A_START
	add a, r1	; a = memory location of element r1
	push 0
	mov r0, a
	mov a, @r0	; a = element r1
	pop 0
	pop psw
; how to write value of acc into index r1 of array
	push psw
	push 0
	push acc
	mov a, #A_START
	add a, r1
	mov r0, a
	pop acc
	mov @r0, a	; element r1 = a
	pop 0
	pop psw
 
; array stored in external RAM (A_START is the first memory location of the array, LEN is the length)
; initalise array data (with 0's)
	push dph
	push dpl
	push acc
	push 0
	mov dptr, #A_START
	clr a
	mov r0, #LEN
clear:
	movx @dptr, a
	inc dptr
	djnz r0, clear
	pop 0
	pop acc
	pop dpl
	pop dph
; how to read index r1 of array
	push dph
	push dpl
	push 0
	mov dptr, #A_START-1
	mov r0, r1
	inc r0
loop:
	inc dptr
	djnz r0, loop
	movx a, @dptr	; a = element r1
	pop 0
	pop dpl
	pop dph
; how to write value of acc into index r1 of array
	push dph
	push dpl
	push 0
	mov dptr, #A_START-1
	mov r0, r1
	inc r0
loop:
	inc dptr
	djnz r0, loop
	movx @dptr, a	; element r1 = a
	pop 0
	pop dpl
	pop dph
 
 