Can a for loop be written in Java to create an infinite loop or is it only while loops that cause that problem?
You can always convert a while loop to a for loop. The while loop and the do loop are equivalent in their expressive power; in other words, you can rewrite a while loop using a do loop, and vice versa. You can always write a program without using break or continue in a loop.
The simplest case of a finite loop is the for loop within a range, as in the example appearing here.
We can create infinite loops in Python via the while statement. In a loop, the variable is evaluated and repeatedly updated (while the given condition is True). We can create an infinite loop in Python if we set the condition in a way that it always evaluates to True.
You cannot make an infinite foreach loop. foreach is specifically for iterating through a collection. If that's not what you want, you should not be using foreach .
Apart from issues of scope and one other thing, this:
for(<init>; <test>; <step>) {
<body>
}
is the same as:
<init>
while(<test>) {
<body>
<step>
}
As other people have alluded to, in the same way that you can have a while
loop without an <init>
form or <step>
form, you can have a for
loop without them:
while(<test>) {
<body>
}
is the same as
for(;<test>;) {
<body>
} //Although this is terrible style
And finally, you could have a
for(;true;) {
<body>
}
Now, remember when I said there was one other thing? It's that for
loops don't need a test--yielding the solution everyone else has posted:
for(;;) {
<body>
}
for(;;){}
is same as
while(true){}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With