# summarray.s -- First example using an array and a loop # The object is to sum a 100-element array of integers. # This program introduces several concepts, such as # writing a loop (including branches and jumps to implement it) # calculating the address of array element # data transfer (load vs. store) # managing different numbers in registers # When you look at the finished product, it may be interesting # to consider how the code could be improved or optimized. # # The original C code is: # # sum = 0; # for (i = 0; i < 100; ++i) # sum += a[i]; # # Register use: # $s0 = i # $s1 = sum # $s2 = base address of a # $s3 = 100 # $s4 = value of a[i] # $s5 = address of a[i] # $t0 = offset in bytes .data a: .word 3:100 output: .asciiz "The sum of the elements is " nl: .asciiz "\n" .text main: li $s0, 0 # i = 0 li $s1, 0 # sum = 0 la $s2, a # set the base address of a li $s3, 100 # set the maximum value of i loop: beq $s0, $s3, endloop # are we done with the loop (i==100) ? add $t0, $s0, $s0 # compute 2*i add $t0, $t0, $t0 # 4*i is the offset for array element add $s5, $s2, $t0 # total address = base + offset lw $s4, 0($s5) # obtain array element's value add $s1, $s1, $s4 # add element to sum addi $s0, $s0, 1 # ++i (don't forget this!) j loop # Time for output... endloop: li $v0, 4 # 4 is I/O function code to print string la $a0, output # specify which string to print syscall # wake up the OS to perform I/O li $v0, 1 # 1 is I/O function code to print int move $a0, $s1 # specify we want to print the sum syscall # write the output now li $v0, 4 # print newline... la $a0, nl syscall li $v0, 10 # end of program syscall