• Status: Solved
• Priority: Medium
• Security: Public
• Views: 330

# 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;
}
0
dandeliondream
1 Solution

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

Commented:
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

Commented:
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

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.