Lets take the below code snippet:
int i = 0;
while ( i <= 10 )
{
System.out.println(i);
if ( i == 8 )
{
continue;
}
i++;
}
What changes do I have to make in the code to avoid infinite loop?
Lets take the below code snippet:
int i = 0;
while ( i <= 10 )
{
System.out.println(i);
if ( i == 8 )
{
continue;
}
i++;
}
What changes do I have to make in the code to avoid infinite loop?
Do your increment at the beginning instead of at the end:
int i = -1;
while ( i <= 10 )
{
i++;
System.out.println(i);
if ( i == 8 )
{
continue;
}
// Presumably there would be some code here, or this doesn't really make much sense
}
Or, depending on the language, you could do it right in the while
statement (keeping in mind operator precedence in whether you choose i++
or ++i
)
int i = 0
while ( i++ <= 10 )
{
System.out.println(i);
if ( i == 8 )
{
continue;
}
// Presumably there would be some code here, or this doesn't really make much sense
}
I would question the use of a while
loop for this kind of structure though. If you want to use a counter in a loop, a for
loop is typically more appropriate.
instead of a quickfix solution, lets see your code for a minute and step through it line by line:
int i = 0;
while ( i <= 10 )
{
System.out.println(i);
if ( i == 8 )
{
continue;
}
i++;
}
i
at first is 0, its less than 10 and hence it enters the loop, prints 0 and increments to 1. Then i
becomes 2, 3, 4, .. 8
When it becomes equal to 8, instead of incrementing, it pops back to the beginning of the loop, printing 8 again.. checks for the value of i
(which is 8) and continues again, printing 8.. and it will keep doing this until eternity.
Hence, increment the number before testing and it will work as expected.
Change your code to something like this
int i = 0;
while ( i <= 10 )
{
if ( i != 8 )
{
System.out.println(i);
}
i++;
}
I like Eric Petroelje's answer. I suggest doing something like this:
if (++i >= 8) continue;
In addition, these days compilers are good enough to warn you about this as a possible infinite loop. There are also code analysis tools that will also detect this for you.
While this is not code I would ever recommend using in most cases, it does serve the purpose:
int i = 0;
while ( i <= 10 )
{
Console.WriteLine(i.ToString());
if ( i == 8 )
{
// Do some work here, then bail on this iteration.
goto Continue;
}
Continue: // Yes, C# does support labels, using sparingly!
i++;
}