A procedure takes its inputs and gives its result in registers by agreement. This one is called with n in CX and answers in AX.
What to build
Read a digit n and print 2 to the power n, using a procedure.
Requirements
- Write a procedure that gets
nin CX and returns 2ⁿ in AX. - Print the result in decimal. The result can have up to 3 digits.
n= 0 gives 1.
Input
One digit n, then Enter.
Output
One number: 2ⁿ.
Constraints
0 ≤ n ≤ 9, so the result is from 1 to 512.
Example
Input:
3
Output:
8
Why it works
Doubling n times from 1 gives 2ⁿ, and SHL AX, 1 is a doubling. The procedure uses CX as its counter, which the caller may still need; here the caller no longer needs it, so it does not save it. The result is printed by the usual dividing loop, where the digits are pushed and popped to reverse them.
Examples
3
8
0
1
Hints
Hint 1
Write a procedure POW2 that takes n in CX and returns 2ⁿ in AX. Start with AX = 1 and double it n times: SHL AX, 1 inside a LOOP.
Hint 2
Guard against CX = 0 with JCXZ, since LOOP with CX = 0 would run 65,536 times.
Hint 3
Print AX in decimal with the divide-by-10 method: DX = 0, DIV BX with BX = 10, push the remainder, count the digits, then pop and print.
Solution
Show one correct solution (try it yourself first)
; A power of two
.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
MOV AH, 1
INT 21H
SUB AL, '0'
MOV CL, AL
MOV CH, 0 ; CX = n
CALL POW2 ; AX = 2 to the n
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
POW2 PROC ; in: CX = n; out: AX = 2 to the n
MOV AX, 1
JCXZ DONE
DOUBLE:
SHL AX, 1
LOOP DOUBLE
DONE:
RET
POW2 ENDP
END MAIN
▶ Open this solution in the compiler, then press Visualize to watch it run step by step