Add two numbers

Numbers on the keyboard arrive one digit at a time. A program multiplies what it has so far by 10 and adds the new digit to build the value, and it divides by 10 to print.

What to build

Read two whole numbers and print their sum.

Requirements

  • The two numbers are separated by one space.
  • Each number has 1 to 4 digits.
  • Print the sum in decimal.

Input

One line with two numbers separated by a space, then Enter.

Output

One number: the sum.

Constraints

Each number is from 0 to 9999, so the sum is at most 19998 and fits in a word.

Example

Input:

12 30

Output:

42

Why it works

Reading builds each number with value = value × 10 + digit, which is how decimal notation works. Printing is the reverse: dividing by 10 gives the last digit as the remainder, so the digits come out last first and the stack reverses them. A word holds up to 65535, so the sum cannot overflow.

Examples

Example 1 · Input
12 30
Expected output
42
Example 2 · Input
9999 9999
Expected output
19998

Hints

Hint 1

Read a number key by key: value = value × 10 + digit. Use MUL BX with BX = 10 (it gives DX:AX; the value is small, so DX is 0), then add the digit.

Hint 2

The first number ends with a space and the second with Enter. One procedure that reads a number and stops at any key below '0' (a space or Enter is smaller) can read both.

Hint 3

Print the sum by the divide-by-10 method: push each remainder, then pop and print them. Set DX = 0 before each DIV BX.

Solution

Show one correct solution (try it yourself first)
; Add two numbers
.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
    CALL READNUM        ; AX = the first number
    MOV SI, AX
    CALL READNUM        ; AX = the second number
    ADD AX, SI          ; the sum
    MOV BX, 10
    MOV CX, 0
DIVIDE:
    MOV DX, 0
    DIV BX
    PUSH DX
    INC CX
    CMP AX, 0
    JNE DIVIDE
PRINT:
    POP DX
    ADD DL, '0'
    MOV AH, 2
    INT 21H
    LOOP PRINT
    MOV AH, 4CH
    INT 21H
MAIN ENDP

READNUM PROC            ; reads digits up to a key below '0'; returns AX
    MOV DI, 0           ; the value so far
READ:
    MOV AH, 1
    INT 21H
    CMP AL, '0'
    JB READY            ; space or Enter ends the number
    SUB AL, '0'
    MOV AH, 0
    MOV BX, AX          ; the digit
    MOV AX, DI
    MOV CX, 10
    MUL CX              ; AX = value x 10
    ADD AX, BX
    MOV DI, AX
    JMP READ
READY:
    MOV AX, DI
    RET
READNUM ENDP
END MAIN

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Multiplication and division →