The MASM Forum Archive 2004 to 2012

Miscellaneous Forums => 16 bit DOS Programming => Topic started by: purifier on April 20, 2006, 09:53:42 AM

Title: The Recursive Factorial!!!
Post by: purifier on April 20, 2006, 09:53:42 AM
Hi,

I could write the code for recursive factorial in assembly by referring material and somehow got it to work ut i'm unable to get the real essence of the code... Can someone please explain me the following as to what exactly is the theme?

Quote
Data Segment
        var1 db 03H
        var2 db ?
Data Ends

Stack_Seg Segment
        Stack db 40 Dup(0)
        Stack_Top LABEL WORD
Stack_Seg Ends


Code Segment
Assume CS:Code,DS:Data,SS:Stack_Seg
Start:  MOV AX,Data
        MOV DS,AX
        MOV AX,Stack_Seg
        MOV SS,AX
        LEA SP,Stack_Top
        XOR AX,AX
        MOV AL,var1
        PUSH AX
        CALL FACTORIAL
        MOV var2,AL
        MOV AX,4C00H
        INT 21H                                        Understood till here

The Alien Zone Starts here

FACTORIAL PROC NEAR
        PUSH BP
        MOV BP,SP
        MOV AX,[BP+4]           ;Get n
        CMP AX,1                ;n<=1?
        JNZ RECUR                ;no:continue
        MOV AX,1                ;yes:return 1
        JMP EXIT

RECUR:  DEC AX
        PUSH AX                 ;factorial(n-1)
        CALL FACTORIAL
        MOV BX,[BP+4]           ;get n
        MUL BX                  ;AX=AX*BX

EXIT:   POP BP
        RET 2                    ;AX=result - I didn't get what this means

FACTORIAL ENDP

Code Ends
End Start
Title: Re: The Recursive Factorial!!!
Post by: Rockphorr on April 20, 2006, 10:01:54 AM
ret 2 is equal ret, add SP,2
Title: Re: The Recursive Factorial!!!
Post by: purifier on April 20, 2006, 10:09:46 AM
Thank you so much.. is there anyway i could watch this program run in a graphical way? I mean, how the stack gets filled and how the pointers get affected and stuff ..that way i'm sure i'll get a complete picture...and i'll be able to write code completely on my own...
Title: Re: The Recursive Factorial!!!
Post by: MichaelW on April 20, 2006, 10:54:04 AM
To see what is going on you could step through the program with a debugger. For this, the 16-bit DEBUG program that comes with Windows should work OK. If you don't know how to use it, there is a tutorial here:

http://www.masmforum.com/simple/index.php?topic=1993.msg16019#msg16019

Title: Re: The Recursive Factorial!!!
Post by: purifier on April 20, 2006, 02:37:32 PM
Oh thank you so much... Now I'll get into some debugging.... :boohoo:
Title: Re: The Recursive Factorial!!!
Post by: Mark Jones on April 20, 2006, 06:45:26 PM
I also heard EMU8086 can simulate code. See: http://www.emu8086.com/