Link to home
Start Free TrialLog in
Avatar of dandeliondream
dandeliondreamFlag for Singapore

asked on

c++ post-decrement

I have a query. When i enter 4, why is the result 24? Can someone explain in details?

#include <iostream>
using namespace std;

int main()
{
      int num, result =1;
      cout << "Enter a number: ";
      cin >> num;
      
      while (num > 0)
      {
      result = result * num--;
      }
      cout << "Result is: " << result << endl;
      return 0;
}
ASKER CERTIFIED SOLUTION
Avatar of ravenpl
ravenpl
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Infinity08
This sounds like homework. Is it, dandeliondream ?

If so, ravenpl might have given a bit too much info there :) Do you understand his explanation ? I would suggest going over the code yourself, and trying to understand what happens. The one important thing to realize is that a post-decrement uses the value first, and then decrements it.
Avatar of CPlusJavaCSharp
CPlusJavaCSharp

So as mentioned from above...
This code:
while (num > 0)
      {
      result = result * num--;
      }
could be written as (to get the same result)
while (num > 0)
      {
      result = result * num;
      num--;
      }