In: Computer Science
7. Ask the user to type in a number and compare this number with 8. The user could try twice.
If the first user input was 8 then print out “Correct!” and terminate the program, otherwise ask user to type in a number for the second time. If the second input was 8 then print out “Correct”, otherwise print “Game over!”
Finish the assembly code segment for the above requirement.
.data
message: .asciiz "Please enter a random number:"
right_str: .asciiz "Correct!\n"
wrong_str: .asciiz "Game over! \n"
.text
li $t0,8 # true answer
li $t1,0 #counter, two chances
loopcheck:
la $a0, message # ask user type in
li $v0, 4
syscall
li $v0, 5
syscall
move $s1, $v0 # s1 is the user input
…. # your answer here
…. # your answer here
printGameOver:
la $a0, wrong_str
li $v0, 4
syscall
j done
printright:
la $a0, right_str
li $v0, 4
syscall
done: #exit
li $v0, 10
syscall
Note: Register used and branch names are arbitrary. These can be changed according to the user's choice. Please refer to code snippets for a better understanding of comments and indentations.
IDE Used: MARS
Program Code
.data
message: .asciiz "Please enter a random number:"
right_str: .asciiz "Correct!\n"
wrong_str: .asciiz "Game over! \n"
.text
li $t0,8 # true answer
li $t1,0 #counter, two chances
# two iteration for the loop
loopcheck:
# check if number of chances are equal to 2
beq $t1, 2, printGameOver
# prompt number from the user
li $v0, 4
la $a0, message
syscall
# get integer value
li $v0, 5
syscall
move $s1, $v0 # s1 is the user input
#answer code starts here
# check if number is equal to 8
# if correct go to printright branch
beq $s1, 8, printright
# increment loops
addi $t1, $t1, 1
# jump to loopcheck
j loopcheck
# branch for Gameover
printGameOver:
# print the wrong gameover
statement
la $a0, wrong_str
li $v0, 4
syscall
# jump to done label i.e end of
program
j done
# print right branch
printright:
# print the right statement
la $a0, right_str
li $v0, 4
syscall
done:
# end of program
li $v0, 10
syscall
Code Snippets
Sample Output Runs