In: Computer Science
Prompt user to enter an integer number from console. Use 3
methods to check if this number is even or odd. Display
result.
This is required to be done in MIPS assembly language.
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
even: .asciiz "Number is even.\n"
odd: .asciiz "Number is odd.\n"
prompt: .asciiz "Enter number : "
.text
main:
#call method to get input from
user
#user input from return from
function stored in $v0
jal getInput
#$a0 is argument register
addi $a0,$v0,0 #move user
input($v0) in $a0
#pass user input to function
checkEvenOdd
#if value is even it will 1 else
return 0
#return value in $v0
jal checkEvenOdd
#move return value in $a0
addi $a0,$v0,0
#call displayResult to print number
is even or odd
jal displayResult
#terminate program using syscall
10
li $v0,10
syscall
#method getInput
getInput:
la $a0,prompt #load address of prompt string in $a0
register
li $v0,4 #syscall 4 to print string
syscall
#read input stored in $v0
li $v0,5
syscall
#return to address save in $ra (address of code
section from it called)
jr $ra
#function to check user input odd or even
checkEvenOdd:
li $t0,2 #load 2 in $t0 register
div $a0,$t0 #divide user input $a0 by 2($a0) and
result stored in lo(quotient) and hi(reminder) register
mfhi $t0 #store reminder of above divide in $t0
seq $v0,$t0,0 #if $t0==0 set 1 to $v0 else set 0 to
$v0
jr $ra #return value of $v0 and go to addres from it
called
#function displayResult to print result
displayResult:
#if argument $a0 is 0 than jump to printOdd label else
go to next line print even
beq $a0,0,printOdd
la $a0,even #load address of even in $a0
li $v0,4 #syscall 4 to print string
syscall
j return #jump to return label
printOdd: #print odd label
la $a0,odd #load address of odd
string
la $v0,4 #syscall 4 to print
string
syscall
return: #return label
jr $ra
Output :
Please comment if you want any changes . up vote ,