# The following data go into the data segment .data string1: .asciiz "Inserisci un array di interi positivi (max 100 numeri, 0 per terminare).\n" string2: .asciiz "Dammi un intero: " string3: .asciiz "Il risultato è: " .align 2 array: .space 400 # array with 100 elements # Here begins the text (code) segment .text main: # Ask for the array li $v0, 4 # Select print_string la $a0, string1 # $a0 contains the address of string1 syscall # launch print_string # Prepare for reading add $s0, $zero, $zero # $s0 = 0 la $t1, array # Base address of array in $t1 # Read the array (while) while: # Ask for the number li $v0, 4 # Select print_string la $a0, string2 # $a0 contains the address of string2 syscall # launch print_string #Read int li $v0, 5 # Select read_int syscall # launch read_int (read int in $v0) add $t0, $v0, $zero # $t0 = $v0 # Break for $t0=0 beq $t0, $zero, endwhile # if $t0==0, break # Add element to array sw $t0, 0($t1) # array[$s0] = $t0 addi $t1, $t1, 4 # Memory address of the next element addi $s0, $s0, 1 # $s0 = $s0+1, array index # While j while # jump to while endwhile: # Call the sumArray procedure la $a0, array # $a0 = base address of array add $a1, $zero, $s0 # $a1 = number of elements of the array jal sumArray # Call sumArray move $t2, $v0 # $t2 = $v0 = sum of array # Show result li $v0, 4 # Select print_string la $a0, string3 # $a0 contains the address of string3 syscall # launch print_string li $v0, 1 # Select print_int move $a0, $t2 # $a0 = $t2 syscall # launch print int # Exit li $v0, 10 # Select exit syscall # Exit # ------------------------------------ # Procedures # Procedure sumArray # Input : $a0 -> base addred of the array of integers # Input : $a1 -> number of elements of the array # Output: $v0 -> sum of the elements of the array sumArray: # Prepare for sum addi $t0, $zero, 0 # $t0 = 0 add $t1, $zero, $a1 # $t1 = number of elements of the array add $t2, $zero, $a0 # $t2 = base address # Do sum (for) for: # Load value from memory, add to sum lw $t3, 0($t2) # $t3 = array[index] add $t0, $t0, $t3 # $t0 = Sum = Sum + array[index] # Decrease the number of elements, increase the address addi $t2, $t2, 4 # $t2 = $t2 + 4 -> index++ addi $t1, $t1, -1 # St1-- # for? bne $t1, $zero, for # Return to for # Prepare output move $v0, $t0 # $v0 = $t0 = Sum of array # Return jr $ra # Return to return address