I have a question about Loop coding

In the picture, there are 2 loops.
The top one will log the result " 0,1,3,6,10’
The bottom one will log the result “0,1,2,3,4”
Why the difference results happen?
In my sense, these 2 loops should get the same result.

Could someone give me a help?

In line 7, before logging, x is increasing by i with each iteration, while after logging, i is increasing by 1. also with each iteration.

x = 0
i = 0
  x = x + i  =>  0
  i++  =>  1
  x = x + i  =>  1
  i++  =>  2
  x = x + i  =>  3
  i++  =>  3
  x = x + i  =>  6
  i++  =>  4
  x = x + i  =>  10
  i++  =>  5

Bottom line, the two loops are very different from one another.

‘+’ means slightly different things depending on what type of variables you’re using it with.

In your first loop, x and i are both integers. so when you ‘+’ them together you get another number.
Your second loop j is a number, but countString is a string. So, when you use the ‘+’ here in this context, it’ll treat j as if it was also a string and append it to the end of countString.
e.g
10 + 10 = 20
“10” + “10” = “1010”

Not as the code is written. As @pluginmaybe has pointed out, the string will be concatenated with each number value treated as a string. The ouput will not have commas in it since none are inserted.

"01234"

will be the final value of countString.

Hi mtf, thanks for your help.

But my confuse point is this:

it seems like in the first loop. X will keep the new value(reassiged value) after every iteration, and use the new value in the next iteration. For example, when x = 0 and i = 1, the x get the result 1. Then, the next iteration will be X = 1 and i =2, i can’t understand why x = 1 here, i think it should be still x = 0.

however, in the second loop, countString’s value is constantly, it’s ’ ’ in every lteration.

im not sure whether i claim my question clearly.

thanks for your help and i learn some new things~ Thanks

The example above shows the value of X in each iteration. i is growing by 1, but x is growing by i, so grows faster as I increases.

In the second value countString is growing by one character each iteration. It is not constant, but being replaced with a new string.

Got it, Thanks for your help @mtf

1 Like