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

- 19,194
- 5
- 54
- 65

- 9
- 1
-
4Yes, it's true. – HolyBlackCat Feb 27 '22 at 17:50
-
Yup, all loop can achieve same goal with different implementations. – Darth-CodeX Feb 27 '22 at 17:53
3 Answers
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++;
}
}

- 106,608
- 13
- 126
- 198
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.

- 14,407
- 6
- 39
- 67
-
2your while loop won't be equivalent in the presence of `continue` statements – Alan Birtles Feb 27 '22 at 17:56
-
-
You seem to have the languages mixed up. The question is about C, not C++. – user17732522 Feb 27 '22 at 18:05
-
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.

- 1