Sum of Array - muneeb-mbytes/computerArchitectureCourse GitHub Wiki

C code for sum of array

s=0;               
i=0;               
L:s=s+A[i];        
i++;
if(i<n) goto L;

MIPS code for sum of array

move $s0,$zero       # Initialize s0 to 0
move $t0,$zero       # Initialize t0 to 0
L:muli $t1,$t0,4     # multiplying the value in $t1 with constant 4 and storing it in $t1 
add $t1,$t1,$s1      # here $s1=&A[0], addition of values in $t1 and $s1 and storing it in $t1  
lw $t2,0($t1)        # Load the value at the address stored in $t1 into $t2
add $s0,$s0,$t2      # Add the value in $t2 to the sum in $s0
add $t0,$t0,1        # Increment t0 by 1
blt $t0,$s2,L        #here $s2=n, Branch back to L if t0 is less than s2

RISC-V code for sum of array

mv s0,zero         # Initialize s0 to 0
mv t0,zero         # Initialize t0 to 0
L:muli t1,t0,4     # multiplying the value in $t1 with constant 4 and storing it in t1 (refer figure below)
add t1,t1,s1       # here s1=&A[0], addition of values in t1 and s1 and storing it in t1  
lw t2,0(t1)        # Load the value at the address stored in t1 into t2
add s0,s0,t2       # Add the value in t2 to the sum in s0
add t0,t0,1        # Increment t0 by 1
blt t0,s2,L        #here s2=n, Branch back to L if t0 is less than s2

Figure by considering &A[0] = 64'h0,A[0] = 2 and A[1]=3