On this page
Sum of Array Elements
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
| |
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
- MOV BX, [SI]: Load current array element into BX
- ADD AX, BX: Add element to running sum in AX
- INC SI: Move pointer to next element
- DEC CX: Decrement element counter
- 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 50Execution Trace:
| Iteration | SI | BX | AX (Sum) | CX |
|---|---|---|---|---|
| Initial | 2000H | 00 | 0000H | 05 |
| 1 | 2000H | 0AH | 000AH | 05 |
| 2 | 2001H | 14H | 001EH | 04 |
| 3 | 2002H | 1EH | 003CH | 03 |
| 4 | 2003H | 28H | 0064H | 02 |
| 5 | 2004H | 32H | 0096H | 01 |
| End | 2005H | 32H | 0096H | 00 |
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:
| |
Overflow Handling
For larger sums that may exceed 16 bits:
| |
Applications
- Calculate average (sum ÷ count)
- Find checksum for data validation
- Compute statistics on datasets
- Accumulate sensor readings
Average Calculation
| |