I am trying to write code for a program to calculate the average of an array but I get the divide by zero error, I googled the error and it seems that it is a divide overflow but I didn't understand what should I do in my program to work. Here is my code:
`DATA SEGMENT
msg1 db 0dh,0ah,"Please enter the length of the array: $"
msg2 db 0ah,0ah,"Enter number: $"
msg3 db 0dh,0ah,"Array average is: $"
val db ?
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA
START:
mov ax,data
mov ds,ax
mov dx,offset msg1
mov ah,09h
int 21h
mov ah,01h
int 21h
sub al,30h
mov bl,al
mov cl,al
MOV AL,00
MOV VAL,AL
lbl1:
mov dx,offset msg2
mov ah,09h
int 21h
mov ah,01h
int 21h
sub al,30h
add al, val
mov val,al
loop lbl1
lbl2:
mov dx,offset msg3
mov ah,09h
int 21h
mov al, val
div bl
add ax,3030h
mov dx,ax
mov ah,02h
int 21h
mov ah,4ch
int 21h
Code ends
end Start
CODE ENDS`
div bl
divides ax
by bl
and stores the quotient in al
, and the remainder in ah
. The quotient must be in the range 0x00..0xFF, or you'll get a division overflow.
The last thing you set ah
to before the division is 9. Since ah
is the most significant part of ax
that means ax
will have the value 0x9XY (where XY are any hexadecimal digits) when you do the division. So to get a quotient that's <=0xFF you would have to divide by at least 10.
The solution is to clear ah
before the division (xor ah,ah
or mov ah,0
).