1
votes

I'm writing a program to determine if an integer is even or odd. The program begins by asking the user for an integer and is supposed to print "Even" and "Odd" depending on what that integer is. I'm having trouble creating the If-else statement.

The statement should be, if $t2=$t0, output "Odd", else, output "Even". This is the code I have now that isn't working ($t1=1, $t2=user's integer AND'd with 1, odd_str="Odd", even_str= "Even"):

bne $t2, $t1, L1
    li $v0, 4
    la $a0, odd_str
    syscall
L1: 
    li $v0, 4
    la $a0, even_str
    syscall

The output for an odd integer is "OddEven" and the output for an even integer is "Even". Any ideas how to fix this?

1
The code looks to work for me. (the output is not correct, but code works). You can also check in debugger, how your code works, and why the output is not as expected. But it definitely works, actually I have yet to see valid machine code, which would make CPU refuse it to execute, never happens. It always executes it, and does what the instructions specify. To avoid some code from executing, don't execute it. For example jump elsewhere. Also for advanced programmers it is easy to create this task without if/else, just by using small pointer array, so the code will have just single exec.flow. - Ped7g
single-step your code in a debugger to see how it falls through. Also notice that the two blocks are the same except for which pointer they pass to syscall, so you could factor that out. - Peter Cordes

1 Answers

0
votes

The output for an odd integer is "OddEven"

Of course, since there's nothing after the syscall that prints the "Odd" string that would make the program terminate. Labels aren't barriers - they're just convenient names for locations in your program.

Any ideas how to fix this?

At the point where you want your program to terminate, execute system call 10. Either directly or by jumping to some other location in your code which executes that system call.