## Calculating the Power of a Number Using Recursive Functions

```
.section .data
input_x_prompt : .asciz "Please enter x: "
input_y_prompt : .asciz "Please enter y: "
input_spec : .asciz "%d"
result : .asciz "x^y = %d\n"
.section .text
.balign 4
.global main
main:
// add code and other labels here
stp fp, lr, [sp, -16]! // save frame pointer and lr in stack
mov fp, sp // create new stack frame
sub sp, sp, -16 // allocate space in stack for local variables
ldr x0, =input_x_prompt // print x prompt
bl printf
ldr x0, =input_spec // load format to read integer
mov x1, sp // save read value in stack
bl scanf // read integer from user
ldr x0, =input_y_prompt // print y prompt
bl printf
ldr x0, =input_spec // load format to read integer
add x1, sp, 8 // save read value in stack
bl scanf // read integer from user
ldr w0, [sp] // load x value in x0
sxtw x0, w0 // extend word to doubleword
ldr w1, [sp, 8] // load y value in x1
sxtw x1, w1 // extend word to doubleword
bl power // calculate power(x, y)
ldr x0, =result // load format to print result
mov x1, x2 // load result for printing it
bl printf // print result
mov sp, fp // remove variables from stack
ldp fp, lr, [sp], 16 // restore frame pointer and lr from stack
// branch to this label on program completion
exit:
mov x0, 0
mov x8, 93
svc 0
ret
// power function
// power(x,y)
// Calculates x^y
// On entry: x0 = x, x1 = y
// Returns x2 = x^y
power:
stp fp, lr, [sp, -16]! // save frame pointer and lr in stack
mov fp, sp // create new stack frame
str x19, [sp, -16]! // push x19 on stack
adds x2, x0, x1 // test if both x and y are 0
beq return1 // if so, return 1
cmp x0, 0 // if x == 0
beq return0 // return 0
cmp x1, 0 // if y < 0
bge else1
return0:
mov x2, 0 // return 0
b powerEnd
else1:
cmp x1, 0 // if y == 0
bne else2
return1:
mov x2, 1 // return 1
b powerEnd
else2:
mov x19, x0 // save x in x19
sub x1, x1, 1 // calculate y - 1
bl power // recurse power(x, y - 1)
mul x2, x2, x19 // multiply x * power(x, y - 1)
powerEnd:
ldr x19, [sp], 16 // pop x19 from stack
ldp fp, lr, [sp], 16 // restore frame pointer and lr from stack
ret
```