So I've had the following task that needs to be written in ARM Assembly
Please test the subroutine by passing the value of n equals 5. The result should equal 15. If n equals 3, the result is 6.
I was given the corresponding Java code:
int sum (int n)
{
int result;
if (n == 1)
return 1;
result = Sum (n‐1) + n;
return result;
}
And I have written the following code in ARM Assembly
NAME main
PUBLIC main
SECTION .text: CODE (2)
THUMB
main
LDR R4, =0x005 ; Value n
BL SUM
STOP B STOP
SUM
MOV R1, #0x01
PUSH {R1, LR}
ADD R5, R5, R4 ; R5 = result
CMP R5, #1 ; Compare result to 1
BEQ ADD1
ADD0
SUB R4, R4, #1 ; Value n - 1
CMP R4, #0 ; Compare n to 0
BEQ ADD1
BL SUM
ADD1
POP {R4, LR}
BX LR ; Branch and exchange instruction set
END
The code is running fine but I want to know if there could be any slight improvements/shortcuts. I am also a little unsure about the comments but I believe what I have written is correct.