Nithya Mohan anand wrote:i could not understand why the value of "i" is reinitialized to 0 everytime the loop executes?
First of all, let's rewrite the code snippet using a
for loop with update statement
If you execute this code snippet, you'll notice that the result is exactly the same: the code contains an infinite loop and does not terminate. So it's definitely not related to the fact that the
for loop doesn't have an update statement.
Let's change the post-increment operator to a pre-increment operator as illustrated in this code snippet
When this code is executed,
"Hello World" will be printed 10 times. So the post-increment operator is responsible for the infinite loop.
Now let's introduce another loop variable
j to assign the result of the post-increment operator and see what happens. This is the adjusted code snippet
When you execute this code snippet,
"Hello World" will be printed 10 times.
The statement
is equivalent to
And that's why
i is not incremented and remains 0 all the time (and that's why
i will never be greater than 10 and you have an infinite loop). If you want to learn more about the post-increment operator, you can read the article mentioned by Joe. And in
this topic you'll find an extensive discussion with lots of code examples. Definitely worth reading!
Hope it helps!
Kind regards,
Roel