The simple answer to your question is "yes, they will compile to the same code." Sometimes. It's going to depend on the language and on the compiler. As far as C# is concerned, any difference in the generated code will be so small as to be irrelevant in terms of running time.
Any for
loop can be re-coded as a while
, and vice-versa. For example, this while
loop:
bool done = false;
while (!done)
{
// do stuff
}
Can be re-coded as a for
:
for (bool done = false; !done;)
{
// do stuff
}
for
and while
are just abstractions. Sometimes it's easier for us to think of stepping through a list, which is the basis (although certainly not the only use) of the for
statement. Other times we want to do something while some condition remains true--thus we use while
. And some languages have an until
(or, in C, the do ... while
), which puts the condition at the end.
These are all just different ways of structuring a solution. The three types of loops can be interchanged, usually with minimal difficulty, but you'll typically find that one more clearly expresses your intent than the other two.