15,940,550 members
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
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)"...

## Solution 1

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--;
}```

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...