5

What are the differences between a while loop and a for loop? It seems to me that they are the same.

yannis
  • 39,597
  • 1
    Try to use both for multiple "challenges". You'll quickly see that one loop construct is better suited for some situation than other loop constructs. And actually there are two types of while loops in some languages (as in Javascript) with their own (special) use cases. In fact both / all three can be used to accomplish a goal, but only one might do the job without too much semantical "overhead" (making it easier to understand e.g.). – try-catch-finally Jun 09 '14 at 07:53
  • They are basically the same. A for loop is just syntax sugar, supporting a subset of use cases that while supports. Sometimes "syntax sugar" is looked down upon, but it should really be looked at as a way to create cleaner, easier to understand code. – Gort the Robot Jun 09 '14 at 16:48
  • Up-voted! No question is too silly when you are learning. – glampert Jun 10 '14 at 02:15
  • @StevenBurnap: they are not basically the same. A language with only while loops and conditionals is Turing-complete, a language with only for loops isn't. A language with while loops can compute any µ-recursive function, a language with for loops can only compute primitive-recursive functions. A language with for loops can only express programs that always terminate, it cannot express non-termination. – Jörg W Mittag Jun 10 '14 at 09:35
  • @JörgWMittag Well, that depends on the for loop, now, doesn't it. Although one could argue that a C for loop is actually a while loop in fancy clothing. – Vatine Jun 10 '14 at 10:57
  • Which languages are you talking about? C style? In pascal for loops are quite different from C for loops and in some other languages for also allows you to write for each loops. – CodesInChaos Jun 10 '14 at 14:57
  • @JörgWMittag I was unclear...as I said, a for loop is a subset of a while loop. – Gort the Robot Jun 10 '14 at 20:00
  • @JörgWMittag: if the language admit a for loop as general as in C, then it trivially has a while loop.... – Basile Starynkevitch Aug 10 '15 at 16:38

2 Answers2

11

The while loop is usually used when you need to repeat something until a given condition is true:

inputInvalid = true;
while(inputInvalid)
{
    //ask user for input
    invalidInput = checkValidInput();
}

On the other hand, the for loop is usually used when you need to iterate a given number of times:

for(var i = 0; i < 100; i++)
{
    ...//do something for a 100 times.
}

You can use them interchangeably if you like:

inputInvalid = true;
for(;;)
{
    if(!inputInvalid)
    {
        break;
    }
    //ask user for input
    invalidInput = checkValidInput();
}

Or

inputInvalid = true;
for(;inputInvalid;)
{        
    //ask user for input
    invalidInput = checkValidInput();
}

And:

var i = 0;
while(i < 100)
{
    //do your logic here
    i++;
}
npinti
  • 1,654
  • 3
    As you can see though, these non-standard usages produce less elegant, harder to read code. Under the hood, the different loop types are all the same conditional goto, so try to use the one that syntactically best fits what you are trying to achieve. – Mr Cochese Jun 09 '14 at 10:49
  • In the below code, I can also say do something 10 times. (It fills your argument as for loop @npinti)

    var count = 0;

    while (count < 10) { document.writeln("looping away!");

    count++;
    

    }

    – mistichor Jun 09 '14 at 14:32
  • Note that in C, you can rewrite your third example as for(invalidInput = checkValidInput();inputInvalid;invalidInput = checkValidInput()){}. But yes, your basic point is entirely correct, and a for loop is really just syntax sugar. Some languages do without it entirely. The C for loop is a strange beast, really more of a bastardized while unlike languages like Pascal, where the for loop can only be used to step through discrete integers. – Gort the Robot Jun 09 '14 at 16:47
  • what does it for(;;) mean. I cannot find explaination of for(;;) it . – mistichor Jun 10 '14 at 14:32
  • @mistichor the C/C++ for loop takes 3 statements for(;;) is a for loop with 3 empty statements, the semicolon separates the blank statements. – esoterik Aug 10 '15 at 17:33
0

There is a fundamental difference between the two: with a for loop, you need to know beforehand how often the loop body will be executed. This is a major restriction, since there are many problems where you simply don't know that. Sometimes you don't even know whether or not that number is finite at all!

Consider, for example, a program asking the user to input a series of names. Say, a patient management system for a dentist. How would you know beforehand how many patients the dentist is going to enter? You don't! You can't write a for loop for that.

Jörg W Mittag
  • 103,514
  • 1
    There are several ways to terminate a for loop early, so you only need to know the maximum times you intend to iterate around the loop. Further, if you're willing to mis-use the conditional part of the for loop, you can make it do anything that a while loop could. – Simon B Jun 10 '14 at 10:42
  • Which language are you talking about? In pascal your argument has some merit (hardcoding a large number as limit is ugly), but in C you can use arbitrary conditions with for. No difference between for(;xxx;) and while(xxx). – CodesInChaos Jun 10 '14 at 15:00
  • 2
    down arrow. Chaos is precisely correct. initializer; followed by while(condition){ ... increment;} is the same as for(initializer; condition; increment){ ... }. – robert bristow-johnson Aug 10 '15 at 23:16