Wednesday, March 11, 2020

Even or Odd number in MIPS

This is a simple MIPS assembler code to check whether the integer entered by the user is even or odd. This is accomplished by simply and-ing the number with 0x00000001. The code is fully commented.

Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS, the MIPS assembler editor & simulator. Assemble, Run.


# - Check if the number entered by the user is even or odd - #

.text

main:

# .......................................................... #

    # print "Please enter a number: "
    li $v0, 4
    la $a0, szPrompt
    syscall

# .......................................................... #

    # get input integer
    li $v0, 5
    syscall
    # integer entered is held by $v0

# .......................................................... #

    # Check if odd or even
    andi $s0, $v0, 1     # if $v0 AND 1 = 0 -> $v0 is even
                         # if $v0 AND 1 = 1 -> $v0 is odd
    beq $s0, $zero, IsEven

# .......................................................... #

IsOdd:
    # print "The number you entered is odd\n"
    li $v0, 4
    la $a0, szIsOdd
    syscall
    j exit

# .......................................................... #

IsEven:
    # print "The number you entered is even\n"
    li $v0, 4
    la $a0, szIsEven
    syscall

# .......................................................... #

exit:
    # Exit program
    li $v0, 10
    syscall

# ---------------------------------------------------------- #

.data
szPrompt: .asciiz "Please enter a number: "
szIsEven: .asciiz "The number you entered is even\n"
szIsOdd:  .asciiz "The number you entered is odd\n"

# ---------------------------------------------------------- #


Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment