int i=1;
while(i<=10)
{
System.out.println(i);
i=i++;
}
Aastha Khanna
Level 5
Why does this loop print 1 indefinitely?
Under discussion
Comments (7)
- Popular
- New
- Old
You must be signed in to leave a comment
Cz Ferencz
30 November 2019, 12:03
i++ already means i = i + 1.
0
vigneswaran murugesan
13 September 2019, 14:34
int i = 1;
while (i <= 10)
{
System.out.println(i);
i++;
}
0
Ev
5 June 2019, 02:26
You're constantly keeping i at basically 1 + 1, you're referencing the value stored at i, then adding 1 to it, and resetting i to 1 each loop.
0
Dmitrii
31 May 2019, 12:15
Because your expression
doesn't work the way u think it does.
i++ is postfix increment, which being alone equals to i = i + 1, but if it is used in any sort of assignment or other operation first the value i is used in that operation and only afterwards that value is incremented.
So for ur loop to work the way u want i++ is enough.
Why it works the way it works is because i is assigned a new value which equals to i, and then the old value of i (which is no longer stored in i, and kind of just hanging there) is incremented (which is useless and lost), atleast that's how i see it, might be wrong tho
If u use IDE, it should warn u of mistakes like that, and even provide some sort of information 0
Aastha Khanna
31 May 2019, 19:19
ok. Tysm.
0
Brian seidman
31 May 2019, 12:04
You are not incrementing variable properly. You have already declared it as being 1 on first line so when you increment you simply add to variable versus trying to set its value to something else
0
Aastha Khanna
31 May 2019, 19:20
got it!Tysm.
0