For loop help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

For loop help

I’m stumped on this problem I ran into in one of the SoloLearn challenges (look at the JS tab in the code below): https://code.sololearn.com/WrXtRjvf0E5d/?ref=app The output is 10, but I am having trouble wrapping my head around this. In the body of the for loop, I would expect x to be set to 0 and then incremented to 1 due to the x++ in the body. After the iteration completes, I would then expect x to be incremented to 2 due to the for loop’s x++. This would continue for each iteration and x would be incremented by 2 each time. However, this would result in an incorrect output. What am I missing?

10th Dec 2019, 3:24 AM
Derek Epic Cow
4 Answers
+ 3
Ok I figured it out. On line 2 in the code (x += x - x++ ), the x++ does not increment the value of x. The resulting computation always evaluates to x += 0. I would have thought x would be post-incremented after line 2 finishes executing, but I guess not. In this scenario, the x++ in the for loop condition on line 1 is the only one that will increment the value of x. Here's a primer on the difference between x++ vs x = x++: https://www.codecademy.com/forum_questions/514995a07272221a5b001f32
10th Dec 2019, 8:34 PM
Derek Epic Cow
+ 5
For loop continue till x is less than or equal to 8.... So, when you're out of execution from for loop, x is 9... While printing , you prints x+1 means 9+1...so, 10 is output
10th Dec 2019, 3:52 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Thank you for the detailed code snippet! This was actually a challenge in the SoloLearn app. I guess I’m trying to understand why the output of the original code is 10, not how to increment x by 2.
10th Dec 2019, 3:47 AM
Derek Epic Cow
0
Why does it not increment twice when there are two x++’s?
10th Dec 2019, 6:06 AM
Derek Epic Cow