0

i have to write a function to calculate the total income from a csv file but I have no idea how to complete it

totalIncome:
#finds the total income from the file
#arguments: a0 contains the file record pointer array location (0x10040000 in our example) But your code MUST handle any address value
#       a1:the number of records in the file
#return value a0:the total income (add up all the record incomes)

    #if empty file, return 0 for  a0
    bnez a1, totalIncome_fileNotEmpty
    li a0, 0
    ret

totalIncome_fileNotEmpty:
    
    # Start your coding from here!

    li a0, 0
    #if no student code entered, a0 just returns 0 always :(
    
# End your  coding  here!
    
    ret

this is my code:

int arraysum(int a[], int size) {
    int ret = 0;
    int i;
    for (i = 0;i < size;i++) {
        ret = ret + a[i];
    }
    return ret;
}
.section .text
.global arraysum
arraysum:
    # a0 = int a[]
    # a1 = int size
    # t0 = ret
    # t1 = i
    addi  t0, zero, 0  # ret = 0
    addi  t1, zero, 0  # i = 0
1:  # For loop
    bge   t1, a1, 1f   # if i >= size, break
    slli  t2, t1, 2    # Multiply i by 4 (1 << 2 = 4)
    add   t2, a0, t2   # Update memory address
    lw    t2, 0(t2)    # Dereference address to get integer
    add   t0, t0, t2   # Add integer value to ret
    addi  t1, t1, 1    # Increment the iterator
    jal   zero, 1b     # Jump back to start of loop (1 backwards)
1:
    addi  a0, t0, 0    # Move t0 (ret) into a0
    jalr  zero, 0(ra)

can someone help me to check if this is right? and did i miss something?

  • You've got the right idea, but I'm pretty sure that CSV files store their data as text. You'd have to convert that text into an integer before adding it up. – puppydrum64 Nov 28 '22 at 15:48

0 Answers0