In c What is the output of the following int n 3 forint m
In c++, What is the output of the following?
int n = 3;
for(int m = 0; m < 5; m++){
n += m++;
}
cout << n << endl;
Solution
intially m=0
on line n+=m++; means that n=n+m++. Since m++ is postfix so, first m isadded to n and then post increment is done therefore n=3+0 i.e. n=3 and m becomes equal to 1. when it checks condition there m is again incremented and now m becomes 2. Since 2<5 again inside loop n+=m++ is run
Here m=2 and n is 3 so,now n=3+2=5 and m becomes here equal to 3 and when it goto check condition it is again incremented so m now become equal to 4, Since 4<5 again n+=m++ is executed. Now n=5 and m=4 is there so now n=5+4=9. and m becomes equal to 5. now it go to for block for incrementing m which makes it . Now since 6> 5 the condition is false and it is out of loop . The value of n is now equals 9. So, it does print 9.
