+ 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
6 odpowiedzi
+ 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! :)
+ 2
x+=1 is x=x+1
+ 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
+ 1
thanks all for your answers
+ 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.
0
x+= 1 means x=x+1,it's called ''self assignment operator" and we use it for less consumption of time and memory.