KeKDee
KeKDee

Reputation: 43

Print String exactly the number input by the user when asked in MIPS

Hi I would like to allow hello world to be outputted the number of times which the user has input , like if they wrote 3 , then hello world would be printed 3 times. How do I do this? This is what I am working with so far :

.data
    n:      .space 4
    msg:    .asciiz "Hello World"
    prom1:  .asciiz "How many Hello World want to be printed: "
    mychar1:.byte 'a'
    out_string:   .asciiz "\nHello World\n"

.text
    main:   li $v0, 4
            la $a0, msg
            syscall

            li $v0, 4     # print str
            la $a0, nl    # at nl
            syscall

            li $v0, 4     # print str
            la $a0, prom1  # at prom1
            syscall

            li $v0, 5     # read int
            syscall
            sw $v0, n     # store the user input in n

            li $v0, 4     # print str
            lw $t0, n
            mul $t0, $a0, 1
            la $a0, out_string   # at out_string
            syscall

Upvotes: 3

Views: 336

Answers (1)

ConnerWithAnE
ConnerWithAnE

Reputation: 1168

This is a more simple solution. I do not save the user input, instead it is just saved to another register. You could save the value to a variable and then grab it again but there is not really any point to doing so.

.data
    prom1: .asciiz "How many Hello World want to be printed: " 
    out_string: .asciiz "\nHello World\n"

.text

main:   
    
        li $v0, 4           
        la $a0, prom1       # Load address of first prompt
        syscall 

        li $v0, 5           # Read int from user
        syscall
        
        li $t1, 0       # Load 0 into $t1 for comparison
        move $t0, $v0       # Move the user input to $t0
loop:
        beq  $t1, $t0, end  # Break If Equal: branch to 'end' when $t1 == $t2
        li $v0, 4       
        la $a0, out_string  # Load address of output string
        syscall
        add $t1, $t1, 1     # Increment $t1
        j loop          # Jump back up to loop
        
end:
        li $v0, 10      # Load syscall 10 to indicate end of program
        syscall 

(also for future reference, you need to indent your code by 4 more spaces so that it is all displayed properly thus easier for people to read!)

Hope this helped!

Upvotes: 2

Related Questions