Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How do I reject negative numbers in MIPS assembly language? My program below is

ID: 3590936 • Letter: H

Question

How do I reject negative numbers in MIPS assembly language? My program below is to find the fibonnacci of the user's input. If the user chooses to input a negative number, I want my program to respond appropriately by prompting the user that it is not possible.

.data
prompt: .ascii "Factorial Example Program "
.asciiz "Enter N value: "
results: .asciiz " Factorial of N = "
n: .word 0
answer: .word 0

.text
.globl main
main:
li $v0, 4 # print prompt string
la $a0, prompt
syscall
li $v0, 5

syscall
sw $v0, n


lw $a0, n
jal fact
sw $v0, answer

li $v0, 4 # print prompt string
la $a0, results
syscall
li $v0, 1 # print integer
lw $a0, answer
syscall

li $v0, 10 # call code for terminate
syscall # system call
.end main

.globl fact

.ent fact
fact:
subu $sp, $sp, 8
sw $ra, ($sp)
sw $s0, 4($sp)
li $v0, 1 # check base case
beq $a0, 0, factDone
move $s0, $a0 # fact(n1)
sub $a0, $a0, 1
jal fact
mul $v0, $s0, $v0 # n * fact(n1)

factDone:
lw $ra, ($sp)
lw $s0, 4($sp)
addu $sp, $sp, 8
jr $ra
.end fact

Explanation / Answer

Given below is the modiifed code. Please don't forget to rate the answer if it helped. Thank you


.data
prompt: .ascii "Factorial Example Program "
.asciiz "Enter N value: "
results: .asciiz " Factorial of N = "
n: .word 0
answer: .word 0
errmsg: .asciiz " N should be 0 or more"
.text
.globl main
main:
li $v0, 4 # print prompt string
la $a0, prompt
syscall
li $v0, 5
syscall
bge $v0, 0, proceed #if input is 0 or more, goto proceed
#otherwise display error message and goto exit
li $v0, 4
la $a0, errmsg
syscall
b exit
proceed:
  
sw $v0, n
lw $a0, n
jal fact
sw $v0, answer
li $v0, 4 # print prompt string
la $a0, results
syscall
li $v0, 1 # print integer
lw $a0, answer
syscall
exit:
li $v0, 10 # call code for terminate
syscall # system call
.end main
.globl fact
.ent fact
fact:
subu $sp, $sp, 8
sw $ra, ($sp)
sw $s0, 4($sp)
li $v0, 1 # check base case
beq $a0, 0, factDone
move $s0, $a0 # fact(n1)
sub $a0, $a0, 1
jal fact
mul $v0, $s0, $v0 # n * fact(n1)
factDone:
lw $ra, ($sp)
lw $s0, 4($sp)
addu $sp, $sp, 8
jr $ra
.end fact

output

Enter N value: 5

Factorial of N = 120
-- program is finished running --

Factorial Example Program

Enter N value: -3

N should be 0 or more
-- program is finished running --

Factorial Example Program

Enter N value: 0

Factorial of N = 1
-- program is finished running --

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote