I'm trying to write a nested loop in Mips Assembly that prints out, for example, if user input x was 5:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
(spaces in between)
So far my code is :
li $v0, 5 #Ask for integer
syscall
move $t5, $v0
addi $t0, $zero, 0
For1:
slt $t1, $t0, $t5
beq $t1, $zero, Exit
add $s0, $s0, $t0
addi $t0, $t0, 1
li $v0, 1
move $a0, $t0
syscall
j For1
Exit:
li $v0, 10
syscall
And this currently accepts user input integer and prints out from 1 to n without space (i.e. 12345)
How would I implement and incorporate the second For for the nested loop so I would achieve the desired result?
Please up vote,comment if any query . Thanks for Question . Be safe .
Note : check attached image for output ,code compiled and tested in MARS MIPS simulator.
Program Plan :
Program :
.data
prompt : .asciiz "enter a integer(n): "
space : .asciiz " "
newLine: .asciiz "\n"
.text #code section
main: #main function
#print prompt string
la $a0,prompt
li $v0,4
syscall
#syscall 5 to read input
integer
li $v0, 5 #Ask for
integer
syscall
addi $t5, $v0,0 #move user input
into $t5
addi $t0, $zero, 1 #outer loop index i=1
for1: #outer loop
bgt
$t0, $t5, Exit #if t0(x)>t5(x) go to exit label
li
$t1,1 #loop index j=1 inner loop
for2: #inner loop
bgt
$t1,$t0,endOfFor2 #if j($t1)>i($t0) go to endOfFor2
loop
#print j
li
$v0,1 #syscall 1 to print integer
addi $a0,$t1,0 #add $a0=$t1+0
syscall
#print space
la
$a0,space #load address of space in $a0
li
$v0,4 #syscall 4 to print string
syscall
#increment j inner loop index
addi $t1,$t1,1
j
for2 #jump to for2
endOfFor2:#if
inner loop ends
la $a0,newLine #print new line
li $v0,4 #syscall 4
syscall
addi $t0,$t0,1 #increment i outer loop index
j for1 #jump to for1 label
Exit:#terminate program
li $v0, 10
#syscall 10 to terminate program
syscall
Output :
Please up vote ,comment if any query . Be safe .
Get Answers For Free
Most questions answered within 1 hours.