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

Popular posts from this blog

12. Write a program to convert NFA to DFA.

Converting a Non-Deterministic Finite Automaton (NFA) to a Deterministic Finite Automaton (DFA) involves creating a new DFA where each state corresponds to a set of NFA states reachable under certain conditions. Below is a simple Python program to perform this conversion. I'll explain each line of code: ```python from collections import defaultdict def epsilon_closure(states, transitions, epsilon):     closure = set(states)     stack = list(states)          while stack:         state = stack.pop()         for next_state in transitions[state].get(epsilon, []):             if next_state not in closure:                 closure.add(next_state)                 stack.append(next_state)          return closure def nfa_to_dfa(nfa_states, nfa_transitions, alphabet, start_state, n...