Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I have this method

Private int recur(int X){
if (X==0)
return 1;
else
return X*recur(X-1);
}

I'm trying to convert to a while loop but it's not working accordingly. taking 5 as a parameter I get different answers.

Private int recur(int x){
C#
int i = 0; int val=0;
       while(i<X){
           if(X==0)
               val= 1;
           else{
               val+= X*(X-1);
               i++;
           }

        }
       return val;
Posted
Updated 16-Dec-13 21:45pm
v2
Comments
H.Brydon 17-Dec-13 8:28am    
Minor point but when you make the code recursive, I'd suggest "if(x<= 0)" instead of "if(x==0)"...

1 solution

Um.
Java
Private int recur(int X){
if (X==0)
return 1;
else
return X*(X-1);
}

Isn't recursive...
It always returns X*(X-1), so if you give it "5", it will always return 20, not Factorial(5) or 120...
And your loop version doesn't return a factorial either: The factorial version using a loop would be:
Java
int val = 1;
while (X > 0)
    {
    val *= X--;
    }
 
Share this answer
 
Comments
SandraCy 17-Dec-13 3:47am    
my bad, I made a typing error it's actually "return X* recur(X-1); "
OriginalGriff 17-Dec-13 3:55am    
Never type it in - *always* copy and paste!
That way, we get to see what you wrote, rather than what you meant to write - and in my case the two of those can be significantly different! :laugh:

The loop version I showed will work, anyway...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900