Write a MIPS Assembly program that computes the sum of all the odd numbers from 1 ..99 and print out the answer
Please make sure the program runs in QTSpim and prints the results. Also explain, thanks.
# Compute the sum of N integers: 1 + 3 + ... + N
# Here take Input N as 99
main:
# Input N from user
li $v0,5 # read_int syscall code = 5
syscall
move $t0,$v0 # syscall results returned in $v0
# Initialize registers
li $t1, 0 # initialize counter (i)
li $t2, 0 # initialize sum
# Loop begins
loop: addi $t1, $t1, 2 # i = i + 2 increment 2 every time eg. 1 3
5
add $t2, $t2, $t1 # sum = sum + i take sum of odd numbers
beq $t0, $t1, exit # if i = N terminating condition
j loop
# Exit begins
exit: li $v0, 4 # print_string syscall code = 4
la $a0, msg1
syscall
# Print sum
li $v0,1 # print_string syscall code = 4
move $a0, $t2
syscall
# Print newline
li $v0,4 # print_string syscall code = 4
la $a0, lf
syscall
li $v0,10 # exit
syscall
# Start .data segment (data!)
.data
msg1: .asciiz "Sum = "
lf: .asciiz "\n"
#code Ends
I have added explanation in form of comments.
Get Answers For Free
Most questions answered within 1 hours.