When we change the prefix increment(++i) to the postfix increment(i++) it outputs 60 instead of 12. Why ? | SoloLearn: Learn to code for FREE!

+6

When we change the prefix increment(++i) to the postfix increment(i++) it outputs 60 instead of 12. Why ?

https://code.sololearn.com/cXkauFN9t8T1/?ref=app Prefix:- int f=1,i=2; while(++i<5){ f*=i; } cout<<f<<"\n"; Output = 12 Postfix:- int f=1,i=2; while(i++<5){ f*=i; } cout<<f<<"\n"; Output = 60 Why ?

6/25/2020 11:35:17 AM

Salman

5 Answers

New Answer

+7

Step 1:- while(2++<5){ //postfix,2 is less than 5 f=1*3 //2++ =2+1 =3 } Step 2:- while(3++<5){ //true f=3*4 } Step 3:- while(4++<5){ //true f=12*5 } So, f = 60

+6

But how 60 ?

+6

Da2 Thanks

+3

Postfix computes before evaluation, prefix after evaluating

+3

The loop gets one extra cycle 12*5 is 60