Finding sum of n positive number

40 Views Asked by At

How do I write a program in assembly language? I want to input 15 two-digit decimal numbers (including positive numbers, negative numbers, and 0) , and then the program will calculate the sum of all positive numbers from this string of numbers.

tried this code but it keeps showing error:

section .data
    prompt db "Enter a two-digit number: $"
    newline db 0Ah, 0Dh, "$"

section .bss
    numbers resb 30  ; Allocate space for 15 two-digit decimal numbers
    sum resb 2       ; Space to store the sum

section .text
    global _start

_start:
    ; Display prompt and get input
    mov ecx, 15  ; Loop counter for 15 numbers
    mov esi, numbers

input_loop:
    mov edx, prompt
    mov eax, 09h  ; DOS interrupt to print string
    int 21h

    ; Input two-digit decimal number
    mov edx, esi
    mov eax, 03h  ; DOS interrupt to input string
    int 21h

    ; Convert string to number
    mov ah, byte [esi]
    sub ah, '0'
    inc esi

    mov al, byte [esi]
    sub al, '0'
    shl ah, 4
    add ah, al
    movzx eax, ah

    ; Check if the number is positive and add to the sum if positive
    test al, 80h  ; Check the sign bit (most significant bit)
    jnz negative_number  ; If sign bit is set, it's a negative number
    add [sum], al

negative_number:
    loop input_loop  ; Repeat the loop until 15 numbers are input

    ; Display the sum of positive numbers
    mov eax, [sum]
    call print_number

    ; Exit the program
    mov eax, 1  ; DOS interrupt to exit the program
    int 21h

print_number:
    ; Function to print a single two-digit number
    push eax
    mov edx, 0  ; Reset count of digits to print

    mov ecx, 10  ; Divide by 10 to get tens place digit
    div ecx
    add dl, '0'
    mov [newline + 2], dl  ; Store tens place digit

    mov eax, edx  ; Get remainder (ones place digit)
    mov dl, al
    add dl, '0'
    mov [newline + 3], dl  ; Store ones place digit

    mov edx, newline
    mov eax, 09h  ; DOS interrupt to print string
    int 21h

    pop eax
    ret

is there any way to make this code works?

0

There are 0 best solutions below