Skip to content

Instantly share code, notes, and snippets.

@budijuara
Created June 6, 2023 20:48
Show Gist options
  • Save budijuara/ce03dc9fb0924d487448b90c5cb1bc76 to your computer and use it in GitHub Desktop.
Save budijuara/ce03dc9fb0924d487448b90c5cb1bc76 to your computer and use it in GitHub Desktop.
read array and calculate average in assembly (asm)
section .data
array db 10, 20, 30, 40, 50 ; Declare an array with 5 elements
len equ $-array ; Compute the length of the array
avg db 0 ; Declare a byte to store the average
section .text
global _start
_start:
mov ecx, len ; Set up loop counter with number of elements
lea esi, [array] ; Load effective address of array into ESI
xor eax, eax ; Clear EAX to use as sum
sum_loop:
add al, [esi] ; Add current array element to sum
inc esi ; Move to next array element
loop sum_loop ; Loop until all elements have been processed
mov ecx, len ; Load number of elements into ECX
idiv cl ; Divide sum by number of elements
mov [avg], al ; Store the average in 'avg'
; Exit
mov eax, 0x60 ; System call number (sys_exit)
xor edi, edi ; Exit code
syscall ; Call kernel
.MODEL small
.STACK 100h
.DATA
array DB 10, 20, 30, 40, 50 ; Declare an array with 5 elements
len EQU 5 ; Length of array
avg DW 0 ; To store average
.CODE
main PROC
; Initialize
mov ax, @data
mov ds, ax
xor bx, bx ; bx will be used to store the sum
xor si, si ; si will be used to index the array elements
; Sum all elements in the array
mov cx, len ; loop counter
sum_loop:
mov al, array[si] ; load array element into al
add bx, ax ; add it to the sum
inc si ; go to next element
loop sum_loop ; loop until all elements have been processed
; Divide the sum by the number of elements to get the average
mov ax, bx ; move the sum into ax
cwd ; Convert word to double word
idiv byte ptr len ; Divide the sum by the number of elements to get the average
mov avg, ax ; store the average
mov ax, 4c00h ; terminate program
int 21h
main ENDP
END main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment