In: Computer Science
Write a RARS assembly language program to solve the following:
For a set of integers stored in an array, calculate the sum of the positive numbers and the sum of the negative numbers, storing the results into memory.
In the data segment of the program, define an array consisting of 25 integers (words) that are a mix of positive and negative values. You can select any values you wish but try to create a balance of positive and negative numbers. Also create data definitions for the two sums that you will calculate in your program. These values should also be defined as words and initialized to zero.
In the text segment, read the numbers from the array one at a time. Include in your program the necessary logic to correctly add the values to the appropriate sum. After all the values have been read and the sums calculated, store the sums to memory in the locations you allocated in the data segment.
Reading the array and calculating the sums should be done within a single loop. Storing the values to memory should be done after the loop.
Greetings!!
Code:
#VARIABLE AND MESSAGES
.data
array: .word 0:25
prompt: .ascii "Enter a positive or negative number \n"
sum_pos: .word 0
possum: .ascii "\nSum of positive numbers: "
sum_neg: .word 0
negsum: .ascii "\nSum of negative numbers: "
#CODE SEGMENT
.text
#MAIN STARTS HERE
main:
#DISPLAY PROMPT MESSAGE
la x10,prompt #load the address of prompt message
li x17,4 #parameter for display message
ecall #display system call
#INITIALIZATION
la x6,array #load the address of the array into x6
li x30,25 #load count into x30
#PROCESSING….
loop:
beq x30,x0,done #check loop count is 0 or not. If 0 then goto done
#READ NUMBER FROM THE USER
li x17,5 #paramter for reading integer from the user
ecall #read number into register 10
add x5,x0,x10 #save the number read into register x5
sw x5,0(x6) #store the number into the array
andi x7,x5,0x80 #check the MSB
beq x7,x0,pos #if the MSB is 0, number is positive and goto label pos
add x28,x28,x5 #otherwise the number is negative and add it to register x28
j skip #skip the next line
pos:
add x29,x29,x5 #if the number is positive add it to register x29
skip:
addi x6,x6,4 #increment the array index
addi x30,x30,-1 #decrement the loopcount
j loop #repeat the loop
done:
#DISPLAY SUM OF POSITIVE NUMBERS MESSAGE
la x10,possum #address of the message
li x17,4 #paramter
ecall #display
$DISPLAY SUM OF POSITIVE NUMBERS
add x10,x0,x29 #load the sum into register x10
li x17,1 #parameter for display integer
ecall #display
#DISPLAY SUM OF NEGATIVE NUMBERS MESSAGE
la x10,negsum #load address
li x17,4 #parameter
ecall
$DISPLAY SUM OF POSITIVE NUMBERS
add x10,x0,x28 #load the sum of -ve numbers to x10
li x17,1 #parameter
ecall #display
#EXIT FROM THE PROGRAM
li x17,10 #exit code into register x17
ecall
Output screenshots:
Hope this helps