# calculate x to the n # # read x (float) and n (int) from keyboard # calculate and print x to the n # repeat until user enters 0 for x # # f4: x # s1: n # f5: result # .data prompx: .asciiz "\n Enter x (0 to end): " prompn: .asciiz "\n Enter n: " powmsg: .asciiz " to the power " ismsg: .asciiz " is " .globl main .text main: sub.s $f6, $f6, $f6 # $f6 = 0, use to compare for loop exit # read x and n read: li $v0, 4 # print prompt for x la $a0, prompx syscall li $v0, 6 # system call code for read float syscall # read x into $f0 c.eq.s $f0, $f6 # check if user entered 0 bc1t done # exit if so mov.s $f4, $f0 # f4 = x li $v0, 4 # print prompt for n la $a0, prompn syscall li $v0, 5 # system call code for read int syscall # read n into $v0 move $s1, $v0 # s1 = n # call power function to calculate x^n mov.s $f12, $f4 # move x to f12 for passing to power func move $a0, $s1 # move n to a0 for passing to power func jal power # call power function mov.s $f5, $f0 # save return value in f5 # print x, n, and result mov.s $f12, $f4 # f12 is x li $v0, 2 # syscall code to print float syscall # print x la $a0, powmsg li $v0, 4 syscall # print power msg move $a0, $s1 # a0 is n li $v0, 1 syscall # print n la $a0, ismsg li $v0, 4 syscall # print is msg mov.s $f12, $f5 # f12 is result li $v0, 2 syscall # print result # 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, return in $v0 # # $f12: x (input parm) # $a0: n (input parm) # $t0: loop counter # $f0: x to the n (return value) # # this is a leaf function so no need to save anything on stack # power: move $t0, $a0 # i = n li $v0, 1 # pow = 1 mtc1 $v0, $f0 # copy 1 to $f0 cvt.s.w $f0, $f0 # convert $f0 to 1, use for power ploop: blez $t0, pdone # exit loop when i <= 0 mul.s $f0, $f0, $f12 # pow = pow * x addi $t0, $t0, -1 # i = i - 1 b ploop # loop again pdone: jr $ra # return to caller