'Can everything which can be done with "while" loops be done with "for" loops and vice versa? [duplicate]

Is it true that, in C, we can do anything using while loop which can be done using for loop and vice versa?



Solution 1:[1]

Yes, it can be used vice-versa. But for a code to be more readable, its wise to use the appropriate one.

while loop usage : loop until a condition is met. the condition is met due to the actions inside the loop.

for loop usage : loop until a condition is met. Here the condition is met be more or less increment/decrement operator present in for loop syntax iteself.

Solution 2:[2]

Yes, a for loop can be constructed with a while loop.

{   int i = 0;
    while(i < 10){
// statement block without continue.
        ++i;
    }
}

and a for loop can replace a while loop trivially by omitting the init and increment sections.

This doesn't mean it's a good idea. They have different semantics. The for loop is used to iterate over a given set of elements, i.e.

for(auto e: collection)...

while is used for other non counting iterations.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saran
Solution 2