Search code examples
arraysassemblyx86-16masm

How to search inside an array for a number and tell how many times it appears in assembler?


I am looking for help because I am making a program where the user enters the size of an array and the array, then it will ask for a number and that number will be searched inside the array and it will print if the number is found or not in case it is found it will say how many times it appears.

.model small

.data 
    
    arreglo1 db ?
    nl equ 0dh, 0ah  
    msj1 db 10,13,"Ingrese el no. de elementos","$"
    msj2 db 10,13,nl,"Ingrese los numeros","$"
    msj3 db 10,13,"Ingrese el numero", "$"
    sizeArreglo db ?
    

.code
    begin proc    
        ;segmentacion de datos
        mov ax, @data
        mov ds, ax   
        ;pregunta por el size del array
        lea dx, msj1
        mov ah, 9
        int 21h
        
        mov ah,1
        int 21h
        mov sizeArreglo, al
        sub sizeArreglo, 30h  ;convierte el input
        
        lea dx, msj2
        mov ah, 9
        int 21h
        
        lea si, arreglo1
        mov ah,1
        mov cl,sizeArreglo   
        ;pide y llena el array con el numero de datos dados por el usuario
        
        
    array_input: 
    
        int 21h
        mov [si],al
                                        
        inc si
        dec cl
        
    jnz array_input
    
        
       ; lea dx, msj3
       ; mov ah, 9
       ;int 21h 
       ;pide el numero que se quiere buscar
    
    
    
    
    terminar_programa:
    mov ah, 4ch
    int 21h

    begin endp
end
    

The problem is that I'm not sure how to make it look for the number inside the array and put how many times it appears inside. If someone could explain me how to do it I would appreciate it very much.


Solution

  • With arreglo1 db ? you are reserving only one byte for the array, it should be something like
    arreglo1 db 10 DUP ? (or whatever syntax your assembler likes for array reservation).

    Instruction SCAS is dedicated to look for a byte|word|dword value in an array.

        push ds
        pop es
        lea di,[arreglo1]      ; Initialize ES:DI to point at the 1st byte of array.
        movzx cx,[sizeArreglo] ; Initialize CX with populated size of the array.
        cld                    ; Tell SCASB to scan forward.
        mov al,[elNumero]      ; The digit which you search for.
        repne scasb            ; Compare AL with ES:DI, increment DI, decrement CX.
        jz NumeroFound         ; When AL=[ES:DI-1].
        jnz NumeroNotFound     ; When CX=0 and still not found.