Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Ritual II: Sum an Array

Eight bytes mark each step.
A dwindling count guides the path.
One register remains.

Write an RV64 function named sum. It receives the address of an array of 64-bit integers in a0 and its element count in a1. Return their wrapping sum in a0.

An empty array must return zero. Use only caller-saved registers and do not modify memory.

Reveal solution
.globl sum
sum:
    mv      t0, a0
    mv      t1, a1
    li      a0, 0
.Lsum_loop:
    beqz    t1, .Lsum_done
    ld      t2, 0(t0)
    add     a0, a0, t2
    addi    t0, t0, 8
    addi    t1, t1, -1
    j       .Lsum_loop
.Lsum_done:
    ret

t0 walks through memory while t1 counts down. Initializing a0 before the loop handles an empty array and leaves the result in the return register.