An example of a While loop, which may not be for a loop

I know that a while loop can do everything it can for a loop loop, but can a for loop do anything in a while loop?

Please provide an example.

+6
loops for-loop while-loop
source share
5 answers

Yes Easy.

while (cond) S; for(;cond;) S; 
+16
source share

The while and classic for loop are interchangeable:

 for (initializer; loop-test; counting-expression) { … } initializer while (loop-test) { … counting-expression } 
+3
source share

If you have a fixed binding and step and do not allow modification of the loop variable in the loop body, then for loops there correspond primitive recursive functions.

From a theoretical point of view, they are weaker than general ones, while loops, for example, you cannot calculate the Ackerman function with only such cycles.

If you can provide an upper bound for a condition in a while loop to become true, you can convert it to a for loop. This shows that in a practical sense there is no difference, since you can easily provide an astronomically high boundary, for example, longer than the life of the Universe.

+1
source share

In C-like languages, you can declare for loops like this:

 for(; true;) { if(someCondition) break; } 

In languages ​​where for is more stringent, infinite loops would be the case when a while is required.

0
source share

While loop does not have as much flexibility as for loop has and are more readable for loops than while. I would demonstrate my point of view by example. The for loop can take the form:

 for(int i = 0, j = 0; i <= 10; i++, j++){ // Perform your operations here. } 

The while loop cannot be used, as indicated above for the loop, and today most modern languages ​​also allow for each loop .

In my opinion, I could be biased, please forgive me for this, you cannot use While loop if you can write the same code with for loop .

0
source share

All Articles