0
Can't differentiate ++b, b and b++
When I wrote the program with the input a as 5 b as 3 and c as 2 { int a,b,c,d; cout <<"a="; cin>>a; cout<<"b="; cin>>b; if(b++<a){ cout<<"c="; cin>>c; cout<<"your ans:"<<a+b*c<<endl; } d= a%b; cout<<"d="<<d<<endl; return 0; } It kept giving me the answer for "your ans:" as 13 instead of 11 and the answer for d as 1 instead of two even though I didn't declare b=b++ or ++b, why?
2 Answers
+ 3
Read about "pre-increment" and "post-increment"
0
The pre increment (--a) and post increment (a++) operators will actually make more sense when used in expressions.
Both operators increment a variable by one but the difference is about the order of events in which they happen. ie what comes first.
For example
a = 0
b = ++a
print(a, b) // 1 1
Before b is assigned the 'a' variable is first incremented by one and then b is assigned the new value of a.
a = 0
b = a++
print(a, b) // 0 1
So you see the difference, the later assigned b to the value of a and then a was incremented by one.
I hope this helps you to differentiate the two operators.