Assembly – Search for Number in Array

email me

< back

Search for a specific number in an array and return its position (if it exists). I’ve added looping, messaging, and concatenation (MSG1 + RES1), just to demonstrate some assembly functionality.

MSG is the relative message. The $ at the end of MSGs means terminate message. 10,13 is a carriage return.

TRY is the loop.

ABOV is checking whether the first operand is above or equal to second operand.

GOOD means it found the specified number in the array.

NOPE means it did not find the specified number in the array.

DONE is the terminating message.

Tested in emu8086 emulator.

See addition and subtraction & multiplication. Learning: 1  2  3  4  5  6  book

DATA SEGMENT
     ARR DW 0000,0001,0002,0003,0004,0005,0006,0007,0008,0009
     LEN DW ($-ARR)/2
     KEY EQU 0006
     MSG1 DB "0006 at Position:",0     
     RES1 DB " ",10,13,10,13,"Great Success!$"               
     MSG2 DB '0006 not found!',10,13,10,13,"Bad Luck!$"
     MSG3 DB 10,13,10,13,"- terminate program -$" 
     
DATA ENDS

CODE SEGMENT 
    ASSUME DS:DATA CS:CODE

START:
       MOV AX, DATA
       MOV DS, AX    
       MOV BX, 00
       MOV DX, LEN
       MOV CX, KEY

TRY:
       CMP BX, DX
       JA NOPE
       MOV AX, BX
       ADD AX, DX
       SHR AX, 1
       MOV SI, AX
       ADD SI, SI
       CMP CX, ARR[SI]
       JAE ABOV
       DEC AX
       MOV DX, AX
       JMP TRY

ABOV:
       JE GOOD
       INC AX
       MOV BX, AX
       JMP TRY

GOOD:
       ADD AL, 01
       ADD AL, '0'
       MOV RES1, AL
       LEA DX, MSG1
       MOV AH, 09H
       INT 21H
       JMP DONE     

NOPE:
       LEA DX, MSG2
       MOV AH, 09H
       INT 21H
       JMP DONE

DONE:
       LEA DX, MSG3
       MOV AH, 09H
       INT 21H     
       MOV AH, 4CH
       INT 21H
           
CODE ENDS
END START

 

Screenshot