Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent using for-loop instead do-while-loop

I was wondering instead of using a do-while loop, what is the equivalent for-loop or any other combination of loops in c?

like image 955
deathshot Avatar asked Dec 22 '13 23:12

deathshot


2 Answers

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.

like image 148
Sergey Kalinichenko Avatar answered Sep 21 '22 20:09

Sergey Kalinichenko


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.

like image 23
Guntram Blohm Avatar answered Sep 21 '22 20:09

Guntram Blohm