assemblymipsmars-simulator

How to print a message in the console when the user inputs a negative number in assembly


I am starting with assembly language and I want to print a message in the console if the user inputs a negative number.

My code:

.globl  main

.data
# program output text constants
prompt:
.asciiz "Please enter a positive integer: "

.text

main:
    li      $v0,    4                   # issue prompt
    la      $a0,    prompt
    syscall 

    li      $v0,    5                   # get input from the user
    syscall 

    blt     $v0,    $zero,      main    # input must be positive

    # rest of the code that's executed when the input is positive

From what I know, I can compare between two values and go to a specific target in my code, which in this case, I used blt: "branch less than", which checks if the input by the user $v0 is less than 0 or not, if it is less than 0, the code starts reading from main again.

The output of this code:

Please enter a positive integer: -2
Please enter a positive integer: -3
Please enter a positive integer: 

I was able to achieve the looping of the input prompt whenever the user inputs a negative value but I also want to print an error message to the console. How can I do that?


Solution

  • Thanks to Peter's first comment, this does ring a bell. I would like to print the error prompt only when the input is less than zero. The second comment is a bit difficult to understand at my current knowledge of assembly language, but I came up with a solution of using a function for this. Simplifying my question, I want to perform two tasks, first one is printing an error message to the console and the second one is starting the code from main. I put the code to do both of them inside a function

    func:
        li      $v0,    4
        la      $a0,    "Error: Invalid input"
        syscall 
    
        b       main
    

    and call it whenever the user inputs a negative number

    main:
        li      $v0,    4                   # issue prompt
        la      $a0,    prompt
        syscall 
    
        li      $v0,    5                   # get n from user
        syscall 
    
        blez    $v0,    func                # n must be positive
    

    Also thanks again for your third comment, I did realize now a mistake I was making, I wasn't checking if the user inputs 0 or not.