0
Need help with y+=1, how to solve it?
Hi im new here and i have couple misunderstandings with some statements. How to solve y+=1 case. And btw what are differences between the ++x and x++?
11 Answers
0
+= is an assignment operator. The line
x = x + 1;
is equal to
x += 1;
so it is just a shortcut for it.
++x is prefix, and x++ is postfix.
The difference is, that prefix first increments the number, then assigns it, while postfix assigns it first, then increments it.
Example:
int x = 0;
int y = ++x;
// -> x is 1 and y is 1
-----
int x = 0;
int y = x++;
// -> x is 1 and y is 0
0
Thanks. Hmmm.. so what is output of this code?
Int x = 0;
Int y = 5;
While ( x < 2 ) {
X++;
Y+=8;
}
Cout << y/3;
0
Well, it would be an error if all the lines start with a capital letter. Otherwise, it would be 8. Prefix or postfix only matters when an assignment happens. The loop runs 3 times, (when x is 2, 3, 4), so y will be 24. 24 / 3 is 8.
0
Sorry, my fault. I asked this because between learning c++ language I'm playing challenge's to check my knowledge, and there was this question with right answer 7 so i didn't get it why and really want to know why it's 7.
0
Oh, my bad, I just didn't see the numbers well for some reason. The loop executes twice, so 16 gets added to 5, which is 21, and 21 / 3 equals to 7
0
Stupid question, but how you get 16? Doesn't y adds to 8 in every loop? Or how it works?
0
Yes, but it adds 8 twice, and 8 * 2 is 16
0
And *2 because 2 loops right?
0
Yes.
0
So y adds to last loop value, or how it calls, yes?
0
I'm sorry, I didn't understand your question