CSC231 Recursion with Factorials
--D. Thiebaut 10:32, 16 November 2012 (EST)
;;; factorial.asm
;;;
;;; demo of the recursive factorial program
;;; uses the stack to pass parameters.
%include "dumpRegs.asm"
section .data
n dd 5 ;n
factN dd 0 ;we'll put n! here
section .text
global _start
_start: push eax ;make room in stack for resut
push dword[n] ;pass n
call fact
pop eax ;put result in eax
mov dword[factN],eax ;and in global
call dumpRegs
;;; exit
mov eax, 1
mov ebx, 0
int 0x80
;;; --------------------------------------------------------
;;; fact: computes the factorial of n, where n is passed in
;;; eax. Returns the result in edx
;;; --------------------------------------------------------
fact: push ebp
mov ebp, esp
pushad
mov eax, [ebp+8] ;get n
cmp eax, 1
jne .recurse
mov dword[ebp+12], 1 ;set result to 1
popad
pop ebx
ret 1*4 ;get rid of n param
.recurse:
dec eax
push eax ;make room for result
push eax ;pass n-1
call fact
pop eax ;get fact(n-1)
mul dword[ebp+8] ;mult by n
mov dword[ebp+12],eax
;pass result back
popad
pop ebp
ret 1*4