问题
im trying to implement this java code into MIPS assembly language and i am quite confused. this is what i have so far:
java code:
for (int c = 1; c <= rows; c++) {
number = highestValue; // reset number to the highest value from previous line
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
highestValue = number; // setting the highest value in line
assembly code:
.text # tells the program where the code begins
move $t0, $zero # t0=0
move $t1, $zero # this will be similar to "int i = 0"
move $t2, $zero # this will be similar to "number = 0"
move $t3, $zero # this will be similar to "highestValue = 0"
add $t4, $zero, 1 # this is our c
move $t5, $a1 # this is what will have our user input thru command line (rows!)
# biggest for-loop for(int c = 1; c <= rows; c++)
for:
bgt $t4, $a1, exit
move $t2, $t3
for1: # for(i = 0; i < c; i++)
bgt $t1, $t4, exit1 # if c is greater than i
li $v0, 5
la $t2, printNum
syscall
add $t1, $t1, $1 # increment by 1
j for1
exit1:
move $t2, $t3
.data # tells to store under .data line (similar to declaring ints)
printNum: .ascii z "$t2"
回答1:
Let's follow the flow of control:
for ( int i = 0; i < n; i++ ) { body }
int i = 0;
while ( i < n ) {
body
i++;
}
Now if we nest one for-loop inside another loop, we still have to follow this pattern. Nesting of control structures in assembly is the same, you fully nest one control structure inside the other. Do not intermix piece parts from nested constructs and outer constructs. Fully start and finish the inner control structure before resuming the outer one.
for ( int i = 0; i < n; i++ ) {
for ( j = 0; j < m; j++ ) {
body
}
}
int i = 0;
while ( i < n ) {
int j = 0; <----- this must be here; we cannot hoist this outside of the outer loop
while ( j < m ) {
body
j++;
}
i++; <--------- your missing this
} <---------- and this
来源:https://stackoverflow.com/questions/61608382/mips-basic-for-loop