If a= 20 then a+=a + + + a; comes out to be 60.... how??? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

If a= 20 then a+=a + + + a; comes out to be 60.... how???

please explain

10th Aug 2016, 2:36 PM
Soutik
Soutik - avatar
5 Antworten
+ 3
wow... C++ is amazing!
10th Aug 2016, 3:23 PM
Piyush Yadav
Piyush Yadav - avatar
+ 2
Because of the way you have spaced out your additions, the compiler is reading it as: a += a + a; Which is just: a = a + (a + a); Which is 60. If you was to space out your additions differently, of course you'll get different answers: a += a++ + a; or a = a + a++ + a; This will leave a with a value of 62, because it's first adding a to a++, which gives 40, and increments to 41. It then increments a by 1, making a 21. Then adds a to 21, forming 62. a += a + ++a; or a = a + a + ++a; This will leave a with a value of 63, because it will first increment a by 1, making it 21. Then it will simply do a + a + a, forming 63.
10th Aug 2016, 3:06 PM
Cohen Creber
Cohen Creber - avatar
+ 1
actually I got the correct answer... the compiler first reads it.. then executes as + and + is + then again + and + is +.. so 60 if I had written a+= a - - - a.. then the compiler would have done - and - is + then + and - is - so.. he would just subtract it... answer would be 20. if I had written a+= a + - + - + - a. then he would execute it as + and - is -,,,, then - and + is - ,,,,then - and - is +,,,, then + and + is +,,,, then + and - is -... therefore answer would be 20........ Just a space....
12th Aug 2016, 10:33 AM
Soutik
Soutik - avatar
0
Thanks Cohen.. I was wondering why 60 is coming as the answer
10th Aug 2016, 3:14 PM
Soutik
Soutik - avatar
0
I see. Thank you, that makes sense :) The first part of my answer I was taking a wild guess, as I hadn't seen anything like it before. The other parts still stand true. You learn something new everyday I guess😁
12th Aug 2016, 11:58 AM
Cohen Creber
Cohen Creber - avatar