In: Computer Science
Write assembly code for the following C procedure:
i = 1; sum = 0;
while (i ≤ n) {
sum += i;
++i;
}
i and sum corresponds to $s1 and $s2. n is preloaded into $s3
Hope this will help you. If you have any doubt please let me know.
Notes: You specified only Assembly language based on $s1 and $2 and $s3 register I am assuming you want it in Mips code. I have made 2 versions of this program. In 1st version n’s value is taken from user while in case of 2nd version n’s value is predefined. Both are working perfectly fine in Mars tool.
Please let me know if you want any modification in this program.
Commenting is also done with in code.
Please feel free to ask me if you need anything else or you have any doubt.
Please also see the screenshot (for both code 2nd version is simplest)
----------------------------------------------------------------Version1----------------
.text
.globl main
main:
# Print string msg1
li $v0,4 #
printing string syscall code = 4
la $a0, msg1 # load the
address of msg1
syscall
# read a input from use
li $v0,5 #
to read int we need syscall code = 5
syscall
move $s3,$v0
# syscall results returned in $v0 storing user
value into $s3 user input value in $s3
addi $s1,$zero,1 #i's vale in $s1=1
addi $s2,$zero,0 # sum's value in $s2=0
loop:
slt $s4,$s1,$s3 # if i's value is less than n 's
value, $s4's value is set to 1 otherwise it is zero
beq $s4,$0,end #if both are equal jump to end
block
add $s2,$s2,$s1 # adding i's value in sum
addi $s1,$s1,1 #incrementing i
j loop
end:
add $s2,$s2,$s1 # adding a last value of i into
sum
# Print string msg2
li $v0, 4 #printing sting syscall =4
la $a0, msg2 #loading the address of
msg2
syscall
# Print output in decimal
li $v0,1 #
printing a dec syscall code = 1
move $a0, $s2
syscall
li $v0,10 #
exit
syscall
.data
msg1: .asciiz "Enter Number that you to
store in $s3 (or you want to sum upto that number): "
msg2: .asciiz "the sum is= "
---------------------------------------------Version2-----------------------------
.text
.globl main
main:
add $s3,$zero,5 # $s3 value set to 5 ,you can change
value directy from here
addi $s1,$zero,1 # i's vale in $s1=1
addi $s2,$zero,0 # sum's value in $s2=0
loop:
slt $s4,$s1,$s3 # if i's value is less than n 's
value, $s4's value is set to 1 otherwise it is zero
beq $s4,$0,end #if both are equal jump to end
block
add $s2,$s2,$s1 # adding i's value in sum
addi $s1,$s1,1 #incrementing i
j loop
end:
add $s2,$s2,$s1 # adding a last value of i into
sum
li $v0,1 #
printing a dec syscall code = 1
move $a0, $s2
syscall
li $v0,10 #
exit
syscall
-------------------------------------
screenshot-----------------------