Skip to main content

Program 5: Counting Digits in a Number

 **Program 5: Counting Digits in a Number**


```assembly

.model small

.stack 100h


.data

    num dw 12345

    count db 0


.code

    main proc

        mov ax, num           ; Load the number into AX

        mov bx, 10


            ; Divisor for digits

        

    count_digits:

        xor dx, dx             ; Clear DX for division

        div bx                 ; Divide AX by BX

        inc count              ; Increment digit count

        test ax, ax            ; Check if quotient is zero

        jnz count_digits       ; If not zero, loop again

        

        mov ah, 4Ch            ; Exit program

        int 21h

    main endp

end main

```


Explanation:

1. `.model small` and `.stack 100h`: Memory model and stack size definitions.

2. `.data` section: Declares the data segment.

   - `num dw 12345`: Defines a word-sized variable named "num" with value 12345.

   - `count db 0`: Defines a byte-sized variable named "count" with initial value 0.

3. `.code` section: Contains the main code.

   - `mov ax, num`: Move the value of "num" into the AX register.

   - `mov bx, 10`: Load the divisor 10 into BX.

   - `count_digits:`: Label for the loop.

   - `xor dx, dx`: Clear DX register for division.

   - `div bx`: Divide AX by BX (quotient in AX, remainder in DX).

   - `inc count`: Increment the "count" variable for each digit encountered.

   - `test ax, ax`: Test if quotient (AX) is zero.

   - `jnz count_digits`: Jump to "count_digits" label if quotient is not zero.

   - `mov ah, 4Ch`: Set the exit code for DOS.

   - `int 21h`: Call DOS interrupt to exit the program.


Comments