Search for an element in an array

In the following program example we will search for an element in an array. The program returns the index of the found element in the accumulator. If the element is not found, it returns the value -1 in the accumulator.

Program source code

; Author: Evgeny Sergeevich Dovgopolov

array: db 01h, 02h, 03h, 04h, 05h, 06h, 07h, 08h, 09h, 0Ah, 0Bh, 0Ch, 0Dh, 0Eh, 0Fh,
       db 10h, 11h, 12h 13h, 14h

main:
    mvi     c, 14h    ; Set the loop counter C to 20
    mvi     d, 00h    ; Index of the found element
    lxi     h, array  ; Load the address of the variable array into the HL register pair

FindLoop:
    mov     a, m      ; Copy the memory value pointed to by the HL register pair into A
    cpi     04h       ; Compare the value in register A with the immediate value 04h
    jz      Found     ; If Z=1, then jump to the label Found

    inx     h         ; Increment the HL register pair by 1
    inr     d         ; Increment the value in the index register D by 1
    dcr     c         ; Decrement the C counter register by 1
    jnz     FindLoop  ; Jump to the label FindLoop until register C becomes 0

    mvi     a, 0FFh   ; If the element was not found, return the value -1 in the accumulator
    hlt               ; Stop program execution

Found:
    mov     a, d      ; If the element was found, return its index in the array in the accumulator
    hlt               ; Stop program execution

Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".