Need help with y+=1, how to solve it? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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++?

18th Jun 2019, 3:27 PM
Aivaras
Aivaras - avatar
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
18th Jun 2019, 3:40 PM
Airree
Airree - avatar
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;
18th Jun 2019, 3:46 PM
Aivaras
Aivaras - avatar
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.
18th Jun 2019, 3:55 PM
Airree
Airree - avatar
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.
18th Jun 2019, 4:04 PM
Aivaras
Aivaras - avatar
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
18th Jun 2019, 4:11 PM
Airree
Airree - avatar
0
Stupid question, but how you get 16? Doesn't y adds to 8 in every loop? Or how it works?
18th Jun 2019, 4:13 PM
Aivaras
Aivaras - avatar
0
Yes, but it adds 8 twice, and 8 * 2 is 16
18th Jun 2019, 4:14 PM
Airree
Airree - avatar
0
And *2 because 2 loops right?
18th Jun 2019, 4:17 PM
Aivaras
Aivaras - avatar
0
Yes.
18th Jun 2019, 4:19 PM
Airree
Airree - avatar
0
So y adds to last loop value, or how it calls, yes?
18th Jun 2019, 4:21 PM
Aivaras
Aivaras - avatar
0
I'm sorry, I didn't understand your question
18th Jun 2019, 4:43 PM
Airree
Airree - avatar