# calculate x to the n # # read x and n from keyboard # calculate and print x to the n # repeat until user enters 0 for x # # s0: num # s1: exponent # t2: result # .data prompt: .asciiz "\n Enter number and exponent (0 0 to end): " powmsg: .asciiz " to the power " ismsg: .asciiz " is " .globl main .text main: # read the num and exponent read: li $v0, 4 # system call code for print string la $a0, prompt # load addr of prompt in $a0 syscall # print prompt li $v0, 5 # system call code for read int syscall # read num into $v0 beqz $v0, done # if user entered 0, exit move $s0, $v0 # t0 = num li $v0, 5 # system call code for read int syscall # read exp into $v0 move $s1, $v0 # t1 = exp # call power function to calculate num raised to exp power move $a0, $s0 # move num to a0 for passing to power func move $a1, $s1 # move exp to a1 for passing to power func jal power # call power function # branch back to top of loop b read # branch back to top of loop # exit from program done: li $v0, 10 # terminate execution and syscall # return control to system ##################################################################### # power function # # compute x to the nth power, call prpower function to print the result # # $a0: x (input parm) # $a1: n (input parm) # $s0: loop counter # $a2: x to the n (using a2 since it will be a parm to the print func) # # save registers: # $ra save our return addr before calling prprint # $s0 save callers s0 before we use it # # no return value # power: addi $sp, $sp, -8 # allocate space on stack (save $ra and $t0) sw $ra, 0($sp) # save $ra on the stack since we are calling another func (push) sw $s0, 4($sp) # save $s0 on the stack since we use it (push) move $s0, $a1 # i = n li $a2, 1 # pow = 1 ploop: blez $s0, pdone # exit loop when i <= 0 mult $a2, $a0 mflo $a2 # pow = pow * x addi $s0, $s0, -1 # i = i - 1 b ploop # loop again # call prprint to print the results. parms are already set up in a0, a1, and a2 pdone: jal prprint # call prprint func to print results lw $ra, 0($sp) # restore $ra from stack lw $s0, 4($sp) # restore $s0 from stack addi $sp, $sp, 8 # deallocate stack space used (pop) # return to main jr $ra # return to caller ##################################################################### # prprint function # # print x, n, and x to the n # # $a0: x (input parm) # $a1: n (input parm) # $a2: x to the n (input parm) # # return value: none # # save registers: none needed since this is a leaf & doesn't use s registers prprint: li $v0, 1 # syscall code to print num, num is already in a0 syscall # print num la $a0, powmsg li $v0, 4 syscall # print power msg move $a0, $a1 # copy exponent to a1 li $v0, 1 syscall # print exponent la $a0, ismsg li $v0, 4 syscall # print is msg move $a0, $a2 # move result to a0 li $v0, 1 syscall # print result jr $ra # return to caller