# Add the numbers in an array # C program: # # sum = 0; # for (i=0; i<5; i++) # sum = sum + a[i]; # # # MARS has a unified memory for code and data, so both cannot start at address 0. # However, our MIPS has distinct memories for both, and we need both to start at 0. # Here's what I did: Choose the "Compact, Text at 0" memory configuration, which # puts data starting at address 0x2000. Then, after compiling, manually edit the # machine code to adjust all lw/sw memory references (adjusting the immediate # downwards by 0x2000). .data 0x2000 sum: .space 4 i: .space 4 a: .word 7,8,9,10,8 .text 0x0000 # Be sure to set memory configuration Compact, Text at 0 main: sw $0, 0x2000($0) # sum = 0; sw $0, 0x2004($0) # for (i = 0; lw $9, 0x2004($0) # allocate register for i lw $8, 0x2000($0) # choose register $8 to hold value for sum loop: sll $10, $9, 2 # covert "i" to word offset lw $10, 0x2008($10) # load a[i] add $8, $8, $10 # sum = sum + a[i]; sw $8, 0x2000($0) # update variable in memory addi $9, $9, 1 # for (...; ...; i++ sw $9, 0x2004($0) # update memory slti $10, $9, 5 # for (...; i<5; bne $10, $0, loop end: j end # infinite loop "trap" because we don't have syscalls to exit