This program calculates the sum of all elements in an array and stores the result in memory.

Description

The program iterates through an array, adding each element to an accumulator, and stores the final sum.

Memory Layout

  • Array: Starts at address 2000H (5 elements)
  • Result: Stored at address 2010H

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
MOV CX,05H
MOV AX,0000H
MOV BX,0000H
MOV SI , 2000H

REPEAT: MOV BX , [SI]
ADD AX,BX
INC SI
DEC CX
JNZ REPEAT
MOV DI , 2010H
MOV [DI] , AX
HLT

Explanation

Initialization

  • CX = 5: Number of array elements
  • AX = 0: Sum accumulator (initialized to 0)
  • BX = 0: Temporary register for current element
  • SI = 2000H: Pointer to array start

Summation Loop

  1. MOV BX, [SI]: Load current array element into BX
  2. ADD AX, BX: Add element to running sum in AX
  3. INC SI: Move pointer to next element
  4. DEC CX: Decrement element counter
  5. JNZ REPEAT: Continue if more elements remain

Store Result

  • MOV DI, 2010H: Set destination address
  • MOV [DI], AX: Store sum at 2010H

Example

Array in Memory:

Address:  2000H  2001H  2002H  2003H  2004H
Value:    [0A]   [14]   [1E]   [28]   [32]
Decimal:   10     20     30     40     50

Execution Trace:

IterationSIBXAX (Sum)CX
Initial2000H000000H05
12000H0AH000AH05
22001H14H001EH04
32002H1EH003CH03
42003H28H0064H02
52004H32H0096H01
End2005H32H0096H00

Result: Sum = 0096H = 150 decimal (10+20+30+40+50)

Memory After Execution

Address 2010H: [96H] (Lower byte of sum)
Address 2011H: [00H] (Higher byte of sum)

16-bit Array Handling

For an array of 16-bit words:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
MOV CX, 05H
MOV AX, 0000H
MOV SI, 2000H

REPEAT:
    ADD AX, [SI]    ; Directly add word from memory
    ADD SI, 2       ; Move to next word (2 bytes)
    DEC CX
    JNZ REPEAT
    
MOV [2010H], AX
HLT

Overflow Handling

For larger sums that may exceed 16 bits:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
MOV CX, 05H
MOV AX, 0000H
MOV DX, 0000H      ; Extended sum (higher 16 bits)
MOV SI, 2000H

REPEAT:
    MOV BX, [SI]
    ADD AX, BX
    JNC NO_CARRY   ; Jump if no carry
    INC DX         ; Increment upper word on carry
NO_CARRY:
    INC SI
    DEC CX
    JNZ REPEAT

; Store 32-bit result
MOV [2010H], AX    ; Lower 16 bits
MOV [2012H], DX    ; Upper 16 bits
HLT

Applications

  • Calculate average (sum ÷ count)
  • Find checksum for data validation
  • Compute statistics on datasets
  • Accumulate sensor readings

Average Calculation

1
2
3
4
5
; After getting sum in AX
MOV BX, 05H        ; Number of elements
DIV BX             ; AX = AX / BX
; AX now contains the average
; DX contains the remainder