Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a for loop be written to create an infinite loop or is it only while loops that do that?

Tags:

java

for-loop

Can a for loop be written in Java to create an infinite loop or is it only while loops that cause that problem?

like image 209
Genki Avatar asked Jun 14 '11 17:06

Genki


People also ask

Can a while loop always be written as a for loop?

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.

Is for loop finite or infinite?

The simplest case of a finite loop is the for loop within a range, as in the example appearing here.

Can we make infinite loop with for loop in Python?

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.

Can for each loops be infinite?

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 .


2 Answers

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>
}
like image 97
tsm Avatar answered Oct 22 '22 11:10

tsm


for(;;){}

is same as

while(true){}
like image 28
Bala R Avatar answered Oct 22 '22 10:10

Bala R