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;
}
LVL 3
dandeliondreamAsked:
Who is Participating?
 
ravenplConnect With a Mentor Commented:
initially num=4 res=1
num > 0 == true
 res=1*4=4, num=3
num > 0 == true
 res =4*3=12, num =2
num > 0 == true
 res =12*2=24, num =1
num > 0 == true
 res =24*1=24, num =0
num > 0 == false -> end of loop.

If You use
 res = res * num--; the multiplication is done on original numbers, then num is decreased. It equals to
 res = res * num; num--;

If You use
 res = res * --num; the decreasion is done first, then multiplication. It eqals to
 --num; res = res * num;
0
 
Infinity08Commented:
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.
0
 
CPlusJavaCSharpCommented:
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--;
      }
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.