Chapter 5
Procedures
Assembly Language Programming Exercise
Problem # 11:
In a byte array of size N, write a procedure that finds all multiples of K that are less than N. Initialize the array to all zeros at the beginning of the program, and then whenever a multiple is found, set the corresponding array element to 1. Your procedure must save and restore any registers it modifies. Call your procedure twice, with K = 2, and again with K = 3. Let N equal to 50. Run your program in the debugger and verify that the array values were set correctly.
Solution:
.386
.model flat,stdcall
.stack 4096
ExitProcess PROTO, dwExitCode:DWORD
N = 50
.data
array BYTE N DUP(0)
K DWORD ?
.code
main PROC
mov K, 2
call multiplesOfK
; re-initialize the array to zero
MOV ECX, N
L2:
MOV BYTE PTR [ESI], 0
ADD ESI, TYPE array
LOOP L2
mov K, 3
call multiplesOfK
INVOKE ExitProcess,0
main ENDP
multiplesOfK PROC
; save all registers
push ECX
push ESI
push EBX
push EDX
MOV ESI, OFFSET array
MOV ECX, N ; loop thorugh array
MOV EDX, 1 ; compare array index 1 to 50
MOV EBX, K ; multiple of K
L1:
CMP EBX, EDX
jne next
; multiple found
MOV BYTE PTR [ESI], 1
ADD EBX, K ; next multiple of K
next:
INC EDX
ADD ESI, TYPE array
Loop L1
; retrieve all registers
pop EDX
pop EBX
pop ESI
pop ECX
ret
multiplesOfK ENDP
END main
.model flat,stdcall
.stack 4096
ExitProcess PROTO, dwExitCode:DWORD
N = 50
.data
array BYTE N DUP(0)
K DWORD ?
.code
main PROC
mov K, 2
call multiplesOfK
; re-initialize the array to zero
MOV ECX, N
L2:
MOV BYTE PTR [ESI], 0
ADD ESI, TYPE array
LOOP L2
mov K, 3
call multiplesOfK
INVOKE ExitProcess,0
main ENDP
multiplesOfK PROC
; save all registers
push ECX
push ESI
push EBX
push EDX
MOV ESI, OFFSET array
MOV ECX, N ; loop thorugh array
MOV EDX, 1 ; compare array index 1 to 50
MOV EBX, K ; multiple of K
L1:
CMP EBX, EDX
jne next
; multiple found
MOV BYTE PTR [ESI], 1
ADD EBX, K ; next multiple of K
next:
INC EDX
ADD ESI, TYPE array
Loop L1
; retrieve all registers
pop EDX
pop EBX
pop ESI
pop ECX
ret
multiplesOfK ENDP
END main
Let me know in the comment section if you have any question.
Previous Post:
Program to Fibonacci Generator in Assembly Language using Visual Studio
Thank you so much for the useful information.
ReplyDeletePlease subscribe and share the blog if you find it helpful.
DeleteThank you so much for this solution
ReplyDeletePlease subscribe and share the blog if you find it helpful.
Deletethis was helpful but i get an error when i ran the code
ReplyDelete