I was wondering instead of using a do-while loop, what is the equivalent for-loop or any other combination of loops in c?
Any sort of a loop can be constructed from a combination of an infinite "forever" loop, and a conditional break
statement.
For example, to convert
do {
<action>
} while (<condition>);
to a for
loop, you can do this:
for (;;) {
<action>
if (!<condition>) break;
}
You can use the same trick to convert a do
/while
loop to a while
loop, like this:
while (true) {
<action>
if (!<condition>) break;
}
Moreover, the loop is not needed at all: any of the above can be modeled with a label at the top and a goto
at the bottom; that is a common way of doing loops in assembly languages. The only reason the three looping constructs were introduced into the language in the first place was to make the language more expressive: the do
/while
loop conducts author's idea much better than any of the alternatives shown above.