Q. Find the Largest and the Smallest Array Values?
Write down a program to find the largest as well as the smallest numbers from a given array. This program uses JGE (jump greater than or equal to) instruction since we have presumed the array values as signed. We haven't used JAE instruction that works correctly for unsigned numbers.
; Program: Initialise the smallest as well as the largest variables as first number in array. They are then compared with the other array values one by one. If valuecomes about to be smaller than assumed smallest number or larger than presumed largest value, the smallest and the largest variables are altered with the new values correspondingly. Let's use register DI to point the current array value and LOOP instruction for looping.
DATA SEGMENT
ARRAY DW -1, 2000, -4000, 32767, 500, 0
LARGE DW?
SMALL DW?
DATA ENDS
END.
CODE SEGMENT
MOV AX, DATA
MOV DS, AX ; Initialize DS
MOV DI, OFFSET ARRAY; DI points to the array
MOV AX, [DI]; AX contains the first element
MOV DX, AX; initialize large in DX register
MOV BX, AX; initialize small in BX register
MOV CX, 6 ; initialize loop counter
A1: MOV AX, [DI]; get next array value
CMP AX, BX;is the new value smaller?
JGE A2 ; if greater then (not smaller) jump to
; A2, to check larger than large in DX
MOV BX, AX; Otherwise it is smaller so move it to
; The smallest value (BX register)
JMP A3 ; as it is small, thus no need
; To compare it with the large so jump
; To A3 to continue or terminate loop.
A2: CMP AX, DX; [DI] = large
JLE A3 ; if less than it implies not large so
; Jump to A3
; To continue or terminate
MOV DX, AX; otherwise it is larger value, so move
; It to DX that store the large value
A3: ADD DI, 2 ; DI now points to next number
LOOP A1 ; repeat the loop until CX = 0
MOV LARGE, DX
MOV SMALL, BX; move the large and small in the
; Memory locations
MOV AX, 4C00h
INT 21h ; halt, return to DOS
CODE ENDS