230k views
0 votes
Arithmetic Instructions: Activity: Execute a formula (Assembly code)

Read 3 numbers, add the first two, then subtract the third number from the sum. Final value should not be less than 0 or greater than 9

Sample
Input

4+1-2

Output

3

1 Answer

6 votes
Here's an example Assembly code that reads 3 numbers, adds the first two, subtracts the third number, and ensures that the final value is not less than 0 or greater than 9:

```
ORG 0x100

START:
; Read the first number
MOV AH, 1
INT 21h
SUB AL, '0'
MOV BL, AL

; Read the second number
MOV AH, 1
INT 21h
SUB AL, '0'
ADD BL, AL

; Read the third number
MOV AH, 1
INT 21h
SUB AL, '0'

; Add the first two numbers and subtract the third number
SUB BL, AL
CMP BL, 0
JL SET_ZERO
CMP BL, 9
JG SET_NINE
JMP PRINT_RESULT

SET_ZERO:
MOV BL, 0
JMP PRINT_RESULT

SET_NINE:
MOV BL, 9
JMP PRINT_RESULT

PRINT_RESULT:
; Print the result
ADD BL, '0'
MOV AH, 2
MOV DL, BL
INT 21h

; Exit the program
MOV AH, 4Ch
INT 21h

END START
```

In this program, we first read the first number using the DOS interrupt `INT 21h` with function `AH=1`. We subtract the character code for '0' to convert it to a numeric value and store it in the `BL` register. We then read the second number and add it to the first number in `BL`. We read the third number and subtract it from the sum of the first two numbers in `BL`. We then compare the result to 0 and 9 to ensure that it is not less than 0 or greater than 9, respectively. If it is less than 0, we set it to 0. If it is greater than 9, we set it to 9. We then print the final result using the DOS interrupt `INT 21h` with function `AH=2`. Finally, we exit the program using the DOS interrupt `INT 21h` with function `AH=4Ch`.
User David Thompson
by
7.5k points