//---------------------------------------------------------------- // fact.s // // This program tests a recursive function which is used to // compute the value of N-factorial for N from zero to ten. // // assemble and link using: gcc fact.s -o fact // // programmer: ALLAN CRUSE // written on: 30 NOV 2003 //---------------------------------------------------------------- .equ MAXN, 10 # entries to be displayed .data number: .int 0 # holds function argument result: .int 0 # holds value of function header: .ascii "\n" .ascii " n n! \n" border: .asciz "--------------------\n" nxline: .asciz " %2d %-10d \n" .text #----------------------------------------------------------------- factorial: # # This procedure employs recursion to compute N-factorial for an # unsigned integer N whose value is pushed onto the stack by the # caller. The function-value is returned in register EAX. Note # that the function-argument is discarded from the stack by this # routine, rather than by the calling routine. # push %ebp # preserve frame-pointer movl %esp, %ebp # setup local stackframe push %edx # save register contents cmpl $0, 8(%ebp) # argument equals zero? jne recur # no, perform recursion movl $1, %eax # else setup value = 1 jmp factx # and return to caller recur: movl 8(%ebp), %eax # get function argument dec %eax # reduce argument value push %eax # push (N-1) onto stack call factorial # and get its factorial mull 8(%ebp) # multiply N * (N-1)! factx: pop %edx # recover reg contents pop %ebp # restore frame-pointer ret $4 # exit/discard argument #----------------------------------------------------------------- main: # print the table heading pushl $header call printf addl $4, %esp # print the table entries nxarg: push number call factorial movl %eax, result pushl result pushl number pushl $nxline call printf addl $12, %esp incl number cmpl $MAXN, number jle nxarg # print the lower border pushl $border call printf addl $4, %esp ret .globl main # make entry-point visible