In C# a question has been bugging me for a while and its what is that actual major difference between a While and For Loop. Is it just purely readability ie; everything you can essentially do in a for loop can be done in a while loop , just in different places. So take these examples:
int num = 3;
while (num < 10)
{
Console.WriteLine(num);
num++;
}
vs
for (int x = 3; x < 10; x++)
{
Console.WriteLine(x);
}
Both code loops produce the same outcome and is the only difference between the two that the for loop forces you to declare a new variable and also set the iteration value each loop cycle at the start? Maybe I'm missing something else in terms of any major differences but it would good if someone can set me straight regarding this. Thanks.
is the only difference between the two that the for loop forces you to declare a new variable and also set the iteration value each loop cycle at the start?
The for loop forces you to nothing. You can omit any of the 3 elements. The smallest form is
for(;;) // forever
{
DoSomething();
}
But you can use the 3 elements to write more concise code:
for(initializer; loop-condition; update-expression)
{
controlled-statements;
}
is equivalent to:
{
initializer;
while(loop-condition)
{
controlled-statements;
continue_target: // goto here to emulate continue
update-expression;
}
}
Note the outer {}
braces, in for(int i = 0; ...; ...)
the i
is local to the for-loop. A clear benefit.
But the major difference in usage is when you call continue;
inside the loop, much easier to get the logic wrong in a while-loop than in a for-loop.
Yes, they're exactly the same in the background (in Assembly, that is).
Usually, it is more common to use the for
loop when the number of repeats is known and we're not going to change our counter(index).
while
loop also has the advantage of a sentinel loop which is easier for example when taking inputs from a user until something specific is given.
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