2

I cannot figure it out why the for loop is created in spite of having while loop. In my opinion, they are the same even through someone says that the while loop is used when we do not know an iteration number. In that case, we can also use for loop, can't we?

For example,

For loop:

for (;true;)
{
    document.write("Hello World <br>");
    if(somecondition){
       break;
    }
}

While loop:

while (true)
{
    document.write("Hello World <br>");
    if(somecondition){
       break;
    }
}

Moreover, the complexity of the two kinds of loops are the equal. So, why the loops do not be deleted and rest only one kind?

lvarayut
  • 13,963
  • 17
  • 63
  • 87
  • 13
    Assembly can do all the work, why do we have all those languages? – Yu Hao Jun 24 '13 at 12:23
  • probably for loop reduces initialization, condition check and iteration to a single step . But I heard a lot of times that for loop is not efficient – Zigma Jun 24 '13 at 12:23
  • There's also a do while. – Darren Jun 24 '13 at 12:23
  • 1
    in some languages, you can even do `for(;;)` – Uooo Jun 24 '13 at 12:34
  • 1
    @Zigma: `for` and `while` end up being mapped to very similar, if not identical, code. "`for` is not efficient" was said by someone who has no clue what the compiler actually generates, or who has looked at a really crappily written compiler's output. – cHao Jun 24 '13 at 12:36
  • 1
    well now i guess we could do it all with `if ... goto` .. – agentp Jun 24 '13 at 12:37
  • 1
    @george: We could, really. Nearly all flow control is just fancy wrappers around `if`...`goto`. – cHao Jun 24 '13 at 12:38
  • I really don't think anyone would miss `while` if it wasn't there. It's just that tiny tiny little bit nicer to read than `for(;condition;)`, but what does that matter? – firefrorefiddle Jun 24 '13 at 12:42
  • @w4rumy: In at least one language (PowerShell) you can even do `for(){}` for an endless loop. No need for those pesky semicolons ;) – Joey Jun 24 '13 at 13:00

5 Answers5

3

Short answer: They are both syntactic sugar that make interpreting the code easier for a programmer, not a machine.

Neither approach you given is no more or less valid than the other, and its true that every for loop can be written as a while loop. The difference is that it makes it more readable to another programmer.

Lets look at Python for an example:

for line in file.readline():

I don't need to see anything else in this block of code to know its intent. Its reading a file, where as in this example:

readline = file.readline()
while readline != "":
    # some code
    readline = file.readline()

It is much less clear what is happening, but the intent is there. Worst still is this:

while true:
    readline = file.readline()
    if readline == "":
        break

I now need to read further into the loop to gain the same insight. As stated above, while loops and for loops offer programmers ways to make more readable and thus more maintainable code.

2

Indeed, anything you can do using a for loop can also be accomplished with a while loop. The following two are equivalent:

for (initialCondition; test; nextStep) {
  doSomething;
}

and

initialCondition;
while (test) {
  doSomething;
  nextStep;
}

So why do we have the for loop at all? There are two reasons.

First, the pattern in the second code snippet is very common (initialize something, then loop while updating on each step until a condition fails). Because it's so common, many language designers considered it worthwhile to have a special syntax for it.

Second, moving iteration variables (e.g. i or j) out of the loop body and inside the for makes it easier for compilers and interpreters to detect certain classes of error (or perhaps even forbid them). For example, if I write (in MATLAB because I happen to have it open)

for i = 1:10
  i = i + 5;   // The body of
  disp(i);     // the loop.
end

then MATLAB presents me with a warning -- "Line 2: Loop index 'i' is changing inside a FOR loop". If I instead wrote it as a while loop:

i = 1;
while i <= 10
  i = i + 5;   // The body of
  disp(i);     // the loop.
  i = i + 1;
end

Uh-oh! Not only do I no longer get a warning from MATLAB, now my code is incorrect! Modifying the iteration variable in the body of the loop is dangerous, and it's rarely the case that you mean to do it. Writing "initialize, test, update" loops as for loops rather than while loops helps protect you from this class of error.

Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
1

They're semantically the equivalent. for(x;y;z) { foo; } is equivalent to x; while (y) { foo; z; }. They're not exactly equivalent in further versions of the standard, in the example of for (int x = 0; y; z), the scope of x is the for block and is out of scope after the loop ends, whereas with int x; while (y) x it's still in scope after the loop ends.

Another difference is that for interprets missing y as TRUE, whereas while must be supplied with an expression. for (;;) { foo; } is fine, but while() { foo; } isn not.

Source

Author

Community
  • 1
  • 1
Jayram
  • 18,820
  • 6
  • 51
  • 68
1

You are correct, for-loops can be converted to while-loops and vice-versa. You can even convert them to do-while loops.

It is the same with if and switch. Why having a switch when the same can be done with an if as well?

I guess it mainly exists for readability and maintainance reasons. Consider the following code:

int i=0;
while(i < array.length){
    doStuff(array[i]);
    i++;
}

Now, another developer adds functionality around this loop:

int i=0;
do();
some();
i = other(); // oops, didn't see that i was used for the loop
stuff();
while(i < array.length){
    doStuff(array[i]);
    i++;
    doMoreStuff(array[i]); // oops, did't see i was already incremented
}

With

for(int i=0; i<array.length; i++){
    doStuff(array[i]);
    doMoreStuff(array[i]);
}
  • It is easier to read (you know when the loop starts and when it ends)
  • It is more error robust (i is scoped to the for loop)
  • Therefore, it is easier to maintain
Uooo
  • 6,204
  • 8
  • 36
  • 63
  • can you sir, start a while loop without expression? But we can start the for loop without it. – Jayram Jun 24 '13 at 12:38
  • @Jayram if you mean `for(;;)` by "expression", that's the same as `for(;true;)`. It is an implizit expression, and probably not the reasonon why `for`-loops exist. – Uooo Jun 24 '13 at 12:44
1

Yes, I think you don't need neither of them:

Label1:
document.write("Hello World <br>");
if(somecondition) goto Label2;
goto Label1;

Label2:
ja_mesa
  • 1,971
  • 1
  • 11
  • 7
  • 3
    I can't in good conscience give this a vote, but I appreciate your humour. –  Jun 24 '13 at 12:41