-3

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

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

3 Answers3

3

Yes, except for definition of variables inside for

for (init; cond; incr) { body; }

If body does not contain a continue statement, the for statement above is completely equivalent to the while loop below.

init;
while (cond) {
    body;
    incr;
}

If you add an extra set of curly braces, even the definition of variables can be converted from for to while

for (int i = 0; i < 100; i++) { printf("%d\n", i); }

is the same as

{
    int i = 0;
    while (i < 100) {
        printf("%d\n", i);
        i++;
    }
}
pmg
  • 106,608
  • 13
  • 126
  • 198
0

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.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
0

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.

Saran
  • 1