Reputation: 1153
I want to implement the factorial algorithm, and the following code gives me wrong result for factorial(5)
int factorial(int n)
{
int i = 1, ret = 1;
while(i++<=n)
ret *= i;
return ret;
}
Looks like the code will continue to run even when i = 6, I don't understand why the while loop didn't stop.
Upvotes: 0
Views: 2240
Reputation: 245429
You are using a post-increment operator which means the final check for i <= n
happens before i
is incremented for the final time. In other words, when i
is 5 your code:
check if i <= 5 -> true
increment i -> i is now 6
execute loop -> executes for i = 6
check if i <= 5 -> false (i is now 6)
You should change to:
while(++i <= n)
Upvotes: 4
Reputation: 108958
Try to do one thing per statement.
int factorial(int n)
{
int i = 1, ret = 1;
while(i<=n)
{
i++;
ret *= i;
}
return ret;
}
Check the differences between the versions above and below this text.
int factorial(int n)
{
int i = 1, ret = 1;
while(i<=n)
{
ret *= i;
i++;
}
return ret;
}
Upvotes: 3
Reputation: 26586
You are doing one extra iteration of the loop.
Instead of (i++<=n)
, what you really want is making it (i<=n)
and then add the i++;
after the ret*=1
.
This is actually much more cleanly done using a for-loop IMHO.
Upvotes: 0
Reputation: 16226
i++
returns the value of i
and only then increments i
. (As opposed to ++i
which first incerements i
and returns incremented value)
Upvotes: 0