
Hiep L. answered 04/27/19
Adjunct Professor at HCC - teaching C++/C#/Java/Python
The first thing I recommend is not to have equal signs all written in the same expression like what you have now. Instead, break the whole thing down into the format: someNumber = someNumber + anotherNumber; OR someNumber += anotherNumber; where you only have one assignment per executable statement. This will make debugging a lot easier and also clearer on the intention of the statement.
Next, if you are trying to understand pre- and post- increment, then here is the explanation on increment:
* The number that you want to increment will always be one value higher at the end of the executable statement.
* The difference between the pre- and post- increment is what "value" is being assigned to the variable on the left of the assignment (= sign). In other words:
- For pre-increment, the value of the right variable is incremented BEFORE assigned to the left variable.
- For post-increment, the value of the right variable is assigned to the left THEN its value gets incremented.
- Note that the order of execution by the system is always from left to right.
Let's do some examples to make things clearer:
int i, j; // j will be used as the left variable (left side of the assignment), and i is the right variable.
i = 5;
j = ++i; // order of execution is from left to right. Thus, i is incremented to 6 first. Then, its value (6) is assigned to j. Thus, j now has the value 6, and i is also 6.
i = 5; // reset i back to 5 for the next example
j = i++; // order of execution is from left to right. Thus, value of i is assigned to j first. Then, i is incremented. Thus, j now has the value of 5, while i has the value 6.
i = 5; // reset i back to 5 for the next example
j = 1; // set j to 1 for the next example
j += i; // this statement is equivalent to: j = j + i. Thus, j has the final value of 6 => (1 + 5) where 1=orig value of j and 5=value of i. The variable i remains at 5.
Hope this helps.