0

I'm working on translating a C program to assembly MIPS. I have multiple conditions in a single if-statement. It's if (n == 0 || (n > 0 && n % 10 != 0)). When this condition is true, it reassign the variable ans to 0.

This is what I have done so far:

    beqz n label1

What should I do when I have multiple conditions?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
asem shaat
  • 103
  • 10
  • 1
    Draw a flowchart. Or rewrite your C code using single conditions and gotos. Or use a compiler. – Jester May 03 '22 at 00:00
  • Have you learned MIPS assembly yet? Do you know how to evaluate `n % 10` in assembly? Do you know how to compare numbers to other numbers? Do you know how to use the results of those comparisons to choose which code executes next? If a compound expression might choose to execute code in multiple ways, like one thing or another thing, how do you think you might arrange the assembly code to make that happen? – Eric Postpischil May 03 '22 at 00:05
  • @EricPostpischil I was thinking about storing each condition in available, then execute them together. However, I'm wondering if I could have a better solution. I'm still a beginner in MIPS assembly so I need your help with this, and I would really appreciate it. – asem shaat May 03 '22 at 00:10
  • Near-duplicates [Mutiple conditions in if in MIPS](https://stackoverflow.com/q/15375267) and [Mips-Assembly beq and](https://stackoverflow.com/q/58598653) – Peter Cordes May 03 '22 at 05:25
  • Also [How to write multiple condition if else statement mips](https://stackoverflow.com/q/74496686) – Peter Cordes Feb 09 '23 at 01:32

2 Answers2

1

Using pseudo-code, a solution could look like:

Compare n to zero.
If the comparison result is “equal”, go to TestIsTrue.
If the comparison result is not “greater than”, go to TestIsFalse.
Calculate the remainder of n divided by 10.
Compare the remainder to zero.
If the comparison result is “not equal”, go to TestIsTrue.
Go to TestIsFalse.

TestIsTrue:
Store 0 in ans.
Go to AllDone.

TestIsFalse:
(Put any desired code here.  Can be empty.)

AllDone:
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

An if statement directs execution to one of two locations: The start of the THEN block, or the start of the ELSE block (or immediately after the THEN block if it doesn't have an ELSE block.)

So we can break down the conditions as follows:

  • n == 0: Go to the THEN block
  • n <= 0: Go to the ELSE block or after IF
  • n % 10 == 0: Go to the ELSE block or after IF
  • Go to the THEN block
ikegami
  • 367,544
  • 15
  • 269
  • 518