what would be the recursive implementation of the following c program:
int fact(int n)
{
if (n == 0) return (1);
else return(n*fact(n – 1));
}

what would be the recursive implementation of the following c program:

int fact(int n)
{
    if (n == 0) return (1);
    else return(n*fact(n – 1));
}

That is recursive. You've defined fact --a function that calls itself.

Did you mean "what would be the non-recursive implementation"?

Also, this should probably be moved to the C forum.

no i want to know how would you write it in mips language.

what would be the recursive implementation of the following c program:
int fact(int n)
{
if (n == 0) return (1);
else return(n*fact(n – 1));
}

Well,this code is already the recursive implementation of factorial,Since it calls itself in the last line.The other approach for factorial would be the iterative one.
int fact(int n)
{
int i=1;
while(n!=0)
{
i*=n;
n--;
}
}

what you wrote is a c++ code..but i need assembly code for this(i.e-MIPS)

what you wrote is a c++ code..but i need assembly code for this(i.e-MIPS)

Ah. It helps if you say what you want when you post a question.

Well,this code is already the recursive implementation of factorial,Since it calls itself in the last line.The other approach for factorial would be the iterative one.

Almost... the return statement is missing, and we can optimize away the multiplication by 1:

int fact(int n)
{
    int i = 1; 

    while(n > 1)
    {
        i *= n;
        n--;
    }

    return i;
}

what you wrote is a c++ code..but i need assembly code for this(i.e-MIPS)

I don't know MIPS assembly, so you're on your own there... I'd recommend the iterative approach if you're doing it in assembly. In any case, the C functions should be more than adequate as pseudocode for your MIPS program.

I don't know MIPS but i now it in x86 assembly, if you convert the statements into MIPS you have your MIPS implementation

//if (n == 0) 
cmp         dword ptr [n],0 
jne         L2 

//return 1;
mov         eax,1 
jmp         End_Fact

//else 
//return n * fact(--n);
L2:
mov         eax,dword ptr [n] 
sub         eax,1 
push        eax  
call        fact
add         esp,4                ; C calling convention for cleaning up stack
imul        eax,dword ptr [n] 

End_Fact:

MOV AX, 1 ; set AX=1

XOR CX, CX ; clear CX
MOV CX, BX ; set CX=BX

@LOOP: ; loop label
MUL CX ; multiply CX with AL i.e. AX=AL*CX
LOOP @LOOP ; jump to label @LOOP if CX!=0

MOV BX, AX ; set BX=AX

RET ; return control to the calling procedure
FACTORIAL ENDP

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.