Wednesday, May 5, 2010

Calculating the average of 3 given numbers


Home|Assembly Language Programming|
This program will find the average of three numbers given by the user. If the sum of these numbers are not divisible by 3 then approximate average will be shown i.e. the nearest integer will be displayed. Detailed explanation of the code is given as comment. The program is done in Emu8086.


data SEGMENT
msg1 DB 'Enter 1st number: $' ;Initializes the strings
msg2 DB 0dh,0ah,'Enter 2nd number: $';to be printed to assist

msg3 DB 0dh,0ah,'Enter 3rd number: $';user to enter 3 numbers
msg4 DB 0dh,0ah,'The average is: $' ;and print the average.

n1 DB ? ;Defines variables, a '?' means
n2 DB ? ;no value is entered,values will
avg DB ? ;stored at the time of execution.

ten DB 10

ENDS

code SEGMENT
start:

MOV AX, data ;Initializes data segment
MOV DS, AX

print MACRO msg ;Define a macro "print".
MOV AH,09h ;Prints the string 'msg'
MOV DX,OFFSET msg ;whose starting offset is
INT 21h ;stored in DX.
ENDM

print msg1 ;Prints the first message
MOV AH,01h ;Asks user for an input

INT 21h ;stores the ASCII value in AL
SUB AL,'0' ;Calculates true binary value
MOV n1,AL ;Stores the value in 'n1'

print msg2 ;Prints the second message
MOV AH,01h ;Asks user for second input
INT 21h ;and stores the ASCII in AL

SUB AL,'0' ;Calculates true binary value
MOV n2,AL ;Stores the value in 'n2'

print msg3 ;Prints the third message
MOV AH,01h ;Asks user for third input
INT 21h ;and stores the ASCII value in AL

SUB AL,'0' ;Calculates the true binary value

ADD AL,n1 ;Add 'n1'to the content of AL
ADD AL,n2 ;Add 'n2' to the sum in AL

MOV AH,00h ;Clears AH
MOV BL,3 ;Moves the divisor 3 into BL
DIV BL ;Divide AX by 3 and get average

MOV avg,AL ;Stores result in 'avg'

print msg4
MOV AL,avg ;Brings result in AL
MOV AH,0 ;Clears AH

DIV ten ;If the result is not valid BCD
MOV DL,AL ;divide the result by 10 to get
MOV CL,AL ;the first digit and stores it in DL and CL

ADD DL,'0' ;Get the ASCII code
MOV AH,02h
INT 21h ;Prints the first digit

MOV AL,CL ;Mov the first digit to AL
MUL ten ;Multiply it by 10
SUB avg,AL ;get the second digit

XCHG DL,avg ;stores second digit in DL
ADD DL,'0' ;Get the ASCII value
MOV AH,02h
INT 21h ;Print the second digit..Voila!

MOV AX, 4c00h ;Exit to operating system.
INT 21h
ENDS

END start


The output of this program will be as follows,

For this I've the input 7,9 and 8. The average is calculated as 08.

1Now for numbers whose sum is not divisible by 3, the approximate average will be displayed as,

2

0 comments:

Post a Comment