Pandya's Bot
Pandya's Bot

Reputation: 49

While ⇋ For convertibility and feasibility

We know that while and for are the most frequently used loop syntax for many programming and scripting languages. Here I would like to ask some questions regarding convertibility and feasibility of using while vs for loop.

Is for to while and vice versa transformation or conversion always possible? I mean suppose one used while loop for some functionality and I want to replace while with for or say vice-versa, then Is while ⇋ for transformation/conversion always possible (also interested in knowing the feasibility)? It would be helpful of I can refer If any research regarding this carried out.

I'm also interested in getting the general guidance for using while vs for. Also want to know if while has some advantages over for and vice versa.

Note: I've this question for log time, I thought -- being a great programming site, this question can be useful here. If the question is not suitable here. I'm unsure if this question is acceptable here, so requesting to consider it liberal; you can ask me to remove if such question hurts the quality of site :)

Upvotes: 0

Views: 30

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521103

I will answer using Java as a reference, though this answer should also be completely valid for C, C#, C++ and many others. If we consider the following for loop:

for (int i=0; i < 10; ++i) {
    // do something, maybe involving i
}

We can see that the loop has 3 components:

int i=0;     initialization of loop counter
i < 10       criteria for loop to execute
++i          increment to loop counter

The following while loop is functionally equivalent to the above for loop:

int i=0;
while (i < 10) {
    // do something, maybe involving i
    ++i;
}

We can see that the main difference between this while loop and the for loop are that the declaration and initialization of the loop counter is outside the loop in the former case. Also, we increment the loop counter inside the actual while loop. The check for the loop continuing is still done inside the loop structure, as with for loops.

So a for loop can be thought of an enhanced while loop of sorts. It frees us from having to create a loop counter outside the loop, and also we can increment/change the loop counter within the loop structure, rather than mixing such logic with the code of the loop body.

Upvotes: 1

Related Questions