+ 1

Please explain what the purpose of an x += operation is and what it's doing

This is the one part of the course that is stumping me. I cant seem to understand why this would be used/how it works

2nd Aug 2016, 5:06 PM
Austin Shepard
Austin Shepard - avatar
6 ответов
+ 16
"x += 1" would increase x by 1 every time it is run. it is the same as "x = x + 1". You can of course also use other numbers. This operator is very useful in loops, where you run a bit of code a few times according to a pre-defined condition,where you likely want to use some kind of counter to track how many times the code ran. Other similar operators are "-=", "*=" and "/=" (among others). The first one reduces a number by a certain value every time, the second multiplies and the third divides. So, to give another example: 64 /= 2 would result in x becoming 32 after running once, then 16, then 8, etc. I hope that clears it up for you! :)
2nd Aug 2016, 5:27 PM
Jasper Ro
Jasper Ro - avatar
+ 2
x+=1 is x=x+1
5th Aug 2016, 3:05 PM
Slimani Mohammed
Slimani Mohammed - avatar
+ 1
I think it saves your time from typing too long. x+=4 is x=x+4, instead of you typing x twice just adding the "+" operator after the first x does the work
14th Aug 2016, 4:30 PM
Negedu Samson
Negedu Samson - avatar
+ 1
thanks all for your answers
24th Aug 2016, 1:28 PM
philemon
philemon - avatar
+ 1
Everyone is basically correct. It's called a 'self-assignment' operator, and it is a shorthand way of assigning a value to a variable after using the prior value of that same variable in a computation.
3rd Nov 2016, 4:31 AM
Andre Burte
Andre Burte - avatar
0
x+= 1 means x=x+1,it's called ''self assignment operator" and we use it for less consumption of time and memory.
30th Jan 2017, 10:41 AM
Anubhav Ranjan
Anubhav Ranjan - avatar