Checking number of zeros in a MIPS array

1k Views Asked by At

I have a question as follows:

Given an array of 32-bit signed integers in the memory and its length in one of the registers, write a MIPS program that counts how many zeros the array contains. Assume that the array starts at Ox12345678, and the length of the array is already stored in $1. The number of zeros should be stored in $2, which mayor may not be initialised with zero at the beginning. Refer to Table 1 for MIPS assembly instructions.

Here is where I have got to in my own head but I have one main question:

1) I think that if I have subroutines, I need to be pushing and then popping data from a stack by using sw $ra, 4($sp) and addi $sp,$sp,-8and sw $fp, 0($sp). However, using my program, I have a break clause which only moves to a subroutine on a condition (if something is $0). So I don't jal to the subroutine, I beq to the subroutine. How can I modify my code to do this?

Here is my current code:

Add $3, $0, $0 #Set a counter to 0, the start of the array
Lui $4, 0x1234
Ori $4, $4, 0x5678  #Store register $4 to start of the array so you can offset
Add $2, $0, $0 #Sets $2 to $0 which is the total number of zeros

Start_for:  Beq $3, $1, end_for #If counter is equal to the array length, go to end
            Lw $5, 0x0($4) Load the current value of array into temp register $5
            Addi $4, $4, 4 #Increment array pointer to next value
            Beq $5, $0, increment #Increment the sum by 1 if the array[i] is zero
            Addi $3, $3, 1 #Increment counter by 1
            J start_for     
increment:
            Addi $2, $2, 1 #Increment the number of zeros by 1 and add to sum
            Jr $ra
End_for:    Lui $8, 0xffff
            Ori $8, $8, 0xf004 Load the outtray into $8
            Lw $8, 0x0($2) Store the number of zeros in the array to the outtray
0

There are 0 best solutions below