start:
ld a, 0 ; Clear accumulator
ld b, 0 ; Clear register B
ld c, 0 ; Clear register C
ld d, 0 ; Clear register D
ld e, 0 ; Clear register E
ld h, 0 ; Clear register H
ld l, 0 ; Clear register L
call read_input ; Read input from user
cp '0' ; Check if input is a digit
jr c, start ; If not, read input again
loop:
call read_input ; Read next input from user
cp '+' ; Check if input is addition sign
jr z, add ; If so, perform addition
cp '-' ; Check if input is subtraction sign
jr z, sub ; If so, perform subtraction
cp '*' ; Check if input is multiplication sign
jr z, mul ; If so, perform multiplication
cp '/' ; Check if input is division sign
jr z, div ; If so, perform division
cp '=' ; Check if input is equals sign
jr z, display ; If so, display result
cp 'C' ; Check if input is clear command
jr z, start ; If so, clear registers and start over
jr loop ; Otherwise, read next input
add:
add a, b ; Add register B to accumulator
ld b, 0 ; Clear register B
jr loop ; Continue reading input
sub:
sub b ; Subtract register B from accumulator
ld b, 0 ; Clear register B
jr loop ; Continue reading input
mul:
ld c, a ; Store accumulator in register C
ld b, 0 ; Clear register B
mul_loop:
add a, c ; Add register C to accumulator
djnz mul_loop ; Repeat until register B is zero
jr loop ; Continue reading input
div:
ld c, a ; Store accumulator in register C
ld b, 0 ; Clear register B
div_loop:
cp c ; Compare accumulator with register C
jr c, div_end ; If accumulator is less than register C, division is complete
sub c ; Subtract register C from accumulator
inc b ; Increment register B
jr div_loop ; Repeat until accumulator is less than register C
div_end:
ld a, b ; Move quotient to accumulator
jr loop ; Continue reading input
display:
call print_output ; Display result
jr start ; Clear registers and start over
read_input:
in a, (0) ; Read input from keyboard
cpl ; Convert to ASCII
ret
print_output:
out (1), a ; Display output on screen
ld a, 13 ; Move cursor to next line
out (1), a
ld a, 10
out (1), a
ret