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.
There is no other loop that executes the loop content at least once, as do-while does. Of course you could emulate do-while with a flag and a while loop:
do {
A;
} while (B)
becomes
int flag=1;
while (flag || B) {
flag=0;
A;
}
but that's not really an alternative, it just obscures your original intent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With