11. Program to Finding Multiples of K in Assembly Language using Visual Studio

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

Comments

  1. Thank you so much for the useful information.

    ReplyDelete
    Replies
    1. Please subscribe and share the blog if you find it helpful.

      Delete
  2. Thank you so much for this solution

    ReplyDelete
    Replies
    1. Please subscribe and share the blog if you find it helpful.

      Delete
  3. this was helpful but i get an error when i ran the code

    ReplyDelete

Post a Comment