Abdullah - Jhatial - Module R2 - RISC - V Programming Task 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Module R2_RISC_V Programming Task 1

Convert the c code in assembly


int i, a = 7, b[3];

for (i = 0; i < 3; i++) {

b[i] = a + (i * a);

The output of code . it print 21 because i add an extra instruction to


print b[3]

Code
CODE
.text
main:
# Allocate space for local variables on the stack
addi sp, sp, -12 # Allocate 12 bytes on the stack
addi s0, x0, 0 # Initialize s0 to 0
addi s1, x0, 7 # Initialize s1 to 7
# Initialize loop counters
addi t2, x0, 3 # Initialize t2 to 3 (loop condition)
addi t4, x0, 1 # Initialize t4 to 1 (accumulator)
loop:
# Check loop condition
beq s0, t2, end # If s0 == t2, branch to end
# Calculate t4 = s0 * s1 + s1
mul t4, s0, s1 # Multiply s0 by s1, result in t4
add t4, t4, s1 # Add s1 to t4, result in t4
# Increment loop counter s0
addi s0, s0, 1 # Increment s0 by 1
# Store result t4 on the stack
sw t4, 0(sp) # Store t4 at the top of the stack
addi sp, sp, 4 # Move the stack pointer to the next position
# Jump back to loop
j loop # Jump to loop label
end:
# Deallocate stack space
addi sp, sp, 12 # Deallocate 12 bytes from the stack
# Prepare arguments for ecall
addi a0, x0, 1 # Set a0 to 1 (exit syscall code)
addi a1, t4, 0 # Set a1 to t4 (exit status)
# Perform syscall to exit and print b[3]
ecall # Exit program

You might also like