2014年1月21日 星期二

MIPS programing : evaluate factorial

wirte a MIPS assembly program to evaluate factorial.

factorial:
F(0)=1
F(1)=1
F(i)=i X (i-1) X (i-2) X .... X 1, if i>=2

1. user should input an interger 'i' in the console window.
2. output F(1), F(2),...,F(i) to the console window
3. hte program should include procedure call

ex. 
input: 5
outut: 1, 2, 6, 24, 120

.text
.globl main

fac:                        #遞迴函式名稱

addi  $t0, $zero, 1         #$t0 = 1  
beq   $a0, $t0, label       #if($a0 == 1)         
addi  $sp, $sp, -8          #else push堆疊
sw    $a0, 0($sp)
sw    $ra, 4($sp)
addi  $a0, $a0, -1          #$a0--
jal   fac                   #繼續遞迴  
lw    $a0, 0($sp)
lw    $ra, 4($sp)
addi  $sp, $sp,8
mul   $t0, $v0, $a0         #$t0放回傳值

la    $a0, spa_str          #printf ","
li    $v0, 4
syscall

add   $a0, $zero, $t0       #print mul 
li    $v0, 1       
syscall

add   $v0, $zero, $t0       #回傳 mul
jr    $ra

label:

addi  $a0, $zero, 1         #print 1 
li    $v0, 1       
syscall

addi  $v0, $zero, 1         #return 1
jr    $ra                   

main:

li     $v0, 5                #讀數字
syscall

move   $a0, $v0              #$a0存取數字
jal    fac                   #呼叫遞迴函式      
 
jr   $ra                     #結束程式

.data
spa_str: .asciiz","

沒有留言:

張貼留言