The use of ++ and zero | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

The use of ++ and zero

I'm new to the use of ++ before/after a variable and the impact on zero. The code segment I'm trying to review is: int i = 0; int x = 0; int y; while (i<3) {x=x+5;i++;} Does this increment 0 to 1 and then increment 5 to 6? And is y = 0, by the lack of value assignment? My reasoning would have i=1, x=6 and y=0. Am I close or way off? Many thanks!!

8th Feb 2017, 7:28 PM
Ted Q.
3 Answers
+ 1
loop 1 i = 0 so x = x + 5. (or x = 0 + 5) x is now 5 i++ (i adds 1) i is now 1 loop 2 i = 1 x = x + 5 (or x = 5 + 5) x is now 10 i++ (i adds 1) i is now 2 loop 3 i = 2 x = x + 5 (or x = 10 + 5) x is now 15 i++ (i adds 1) i is now 3 loop 4 i = 3 so it doesnt run y has not been touched, so it has no value yet. I hope this helps!
8th Feb 2017, 7:50 PM
Peter
0
x initial value is 0 and then 5 is added to it so x = 5 after the first loop iteration. During the second iteration it gets added 5 again and becomes 10, and finally 15. Variable i gets icremented by 1 with each loop iteration so it's equal to 1, then 2 and finally 3. y is never assigned any value. Programming languages will treat it differently. For example, C# won't let you use it until you assign a value to it.
8th Feb 2017, 7:40 PM
Zilvinas Steckevicius
Zilvinas Steckevicius - avatar
0
Wow! Pretty rookie of me to see the loop but not factor the incremental cycle of the variables final value! Thank you both for your time and input!!
9th Feb 2017, 5:57 AM
Ted Q.