-1

I'm writing a MIPS program for enter a number and print N, N-1, N-2, ..., 1 on MARS 4.5

My code look have right logic but syntax is quite weak.

The problem is program not working:

  • Input: 3
  • Expected: 321
  • Actual: "-- program is finished running (dropped off bottom) --

Help me fix it:

.text 

.data
msg: .ascii "Enter a number: "
msg1: .ascii "Final result: "

.globl main
main:
    # Print the msg
    li $v0, 4   # $v0 code 4 mean syscall print an string
    la $a0, msg # la = load address of the msg
    syscall     # calling
    
    
    # Get number from keybroad
    li $v0, 5   # $v0 code 5 mean read integer
    syscall     # calling
    move $t0, $v0   # store number to $t0
    
    
    # Calling the callee (function for print 1,2,3,..,Number)
    jal function
    

# Function for print N, N-1, ..., 1
function:
    li $v0, 1   # Calling a print
    move $a0, $t0   # Store current number in $a0
    syscall     
    sub $t0, $t0, 1 # Number = number - 1 after print (t0 = t0 - 1)
    
    beq $t0, 1, exit:   # If number == 1 -> exit
    j function      # Calling

exit:
    # Exit program
    li $v0, 10
    syscall

Thank you all.

Tu Le Anh
  • 91
  • 1
  • 7

1 Answers1

0

Final answer:

.data
msg: .asciiz "Enter a number: "
msg1: .asciiz "Final result: "
char: .asciiz ", "

.text 
.globl main
main:
    # Print the msg
    li $v0, 4   # $v0 code 4 mean syscall print an string
    la $a0, msg # la = load address of the msg
    syscall     # calling
    
    # Get number from keybroad
    li $v0, 5   # $v0 code 5 mean read integer
    syscall     # calling
    move $t0, $v0   # store number to $t0
    
    # Print the msg
    li $v0, 4   # $v0 code 4 mean syscall print an string
    la $a0, msg1    # la = load address of the msg
    syscall 
    
    # Calling the callee (function for print 1,2,3,..,Number)
    jal function
    

# Function for print N, N-1, ..., 1
function:   
    li $v0, 1   # Calling a print
    move $a0, $t0   # Store current number in $a0
    syscall
        
    sub $t0, $t0, 1 # Number = number - 1 after print (t0 = t0 - 1)
    
    li $t3, 0
    beq $t0, $t3, exit  # If number == 1 -> exit
    
    li $v0, 4   # $v0 code 4 mean syscall print an string
    la $a0, char    # la = load address of the msg
    syscall
    
    j function      # Calling

exit:
    # Exit program
    li $v0, 10
    syscall

Tu Le Anh
  • 91
  • 1
  • 7