An array is just a row of bytes (or words) in memory, and a string is an array of characters. Both are handled the same way in 8086 assembly: point an index register at the first element and step through it. This tutorial assumes you know branches and loops and have Emu8086 installed; see the install guide.
Defining an array
The DB directive lays bytes down one after another. The label in front of it is the address of the first byte, and the following bytes sit at the next addresses. There is no length stored anywhere: your program has to know, or count, how many elements there are.
Summing an array
The program below adds the five numbers in numbers and leaves the total in AX. SI starts at the first element, CX counts the elements, and each pass adds the byte SI points at, then moves SI on by one. Note the order: the value is added before SI is incremented, so the first element is not skipped.
ORG 100h LEA SI, numbers MOV CX, 5 XOR AX, AX add_next: ADD AL, [SI] INC SI LOOP add_next RET numbers DB 3, 1, 4, 1, 5
What you should see
AX should end at 14, which is 3 + 1 + 4 + 1 + 5. If you get a different total, the usual cause is an off-by-one error: either SI was incremented before the first add, so the first element was missed, or CX was loaded with the wrong count. Single-step the first two passes and check SI and AL after each one.
Printing a string character by character
A string printed with DOS function 02h needs one character at a time in DL. The loop below walks a string that ends with a zero byte, printing each character until it reaches that terminator. The zero byte itself is never printed, because the loop tests for it first. This version uses no macros, so it needs no include line.
ORG 100h LEA SI, text print_next: MOV DL, [SI] CMP DL, 0 JE finished MOV AH, 02h INT 21h INC SI JMP print_next finished: RET text DB 'Hi, 8086!', 0
What you should see
The emulator window should show Hi, 8086! and nothing after it. If extra characters appear, the string probably has no zero terminator, so the loop ran on into whatever bytes followed it. If nothing appears, check that SI was loaded with the address of the string and that DL, not AL, carries each character into function 02h.
Arrays of words, briefly
A word array uses DW instead of DB, and each element is two bytes, so SI must advance by two per element instead of one. The pattern is identical; only the step size changes. Mixing the two up, stepping by one through a word array, reads the high byte of one element as if it were the next element, and the results look mysteriously halved or doubled.
Next steps
Sorting is the natural next exercise: sorting numbers rearranges an array in place. For the ideas behind the loop, revisit branches and loops. The opcode reference covers the addressing modes used here, and the home page links the full series.
