2

Is there a difference between for and while statements? Is it just syntax?

#include <stdio.h>

void main() {
    int cent_temp = 0;
    int fah_temp;
    while (cent_temp <= 20) {
        fah_temp = (9 * cent_temp) / 5 + 32;
        printf("%d degrees C = %d degrees F\n", cent_temp, fah_temp);
        cent_temp++;
    }
}

This means to me....

While the value of cent_temp is less than 20 then calculate fah_temp. Then increase the value of cent_temp by 1 and check it is still less than 20; then go round the loop again.

Regarding the syntax:

printf("%d degrees C = %d degrees F\n", cent_temp, fah_temp);

This means %d means print to the screen, replace with a decimal number the value of cent_temp and %d means replace with a decimal number the value of fah_temp.

#include <stdio.h>

void main() {
    int cent_temp;
    int fah_temp;
    for (cent_temp = 0; cent_temp <= 20; cent_temp++) {
        fah_temp = (9 * cent_temp) / 5 + 32;
        printf("%2d degrees C = %2d degrees F\n", cent_temp, fah_temp);
    }
}

My interpretation of the above is: for cent_temp = 0 repeat while cent_temp less than 20 and then execute cent_temp+1 at the end. So cent_temp 0 goes into the loop to calculate fah_temp and gets printed to the screen. Then cent_temp goes up by one then goes round the loop again. Here I've used %2d instead of %d to signify that it should have 2 spaces for a decimal number (and they line up when executed). Both codes will not execute if cent_temp > 20.

Similarly rearranging the statement in a do while loop has a similar effect and doesn't really have an impact on the result.

Does each type of loop have a different application?

Please correct me if I wrong!

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 2
    You might want to have a look into a good C book. Most of them detail what the different loops do and specifically what the `for` statement exactly does (and that is indeed syntactic sugar). They also should detail where each statement is better suited. Write code readable by humans. Caution: The `do` loop is indeed different! – too honest for this site Oct 26 '16 at 14:46

6 Answers6

3

Is there a difference between 'for' and 'while' statements? Is it just syntax?

To me, it is just syntax.

From K&R section 3.5 Loops -- While and For, I quote:

The for statement

for (expr1; expr2; expr3)
  statement

is equivalent to

expr1;
while (expr2) {
  statement
  expr3;
}

except for the behavior of continue.

Grammatically, the three components of a for loop are expressions. Most commonly, expr1 and expr3 are assignments or function calls and expr2 is a relational expression.

Notes

As user @chqrlie has mentioned in the comments, control statements like break and continue make the situation slightly murkier.

There are some situations where the modify statement is necessary in the loop body. For example Erase-remove idiom with std::set failing with constness-related error (in C++ though)

Example

As an example, let us write a loop to print all the odd numbers between 1 and 100.

int i = 1;
while (i <= 100) {
  printf("%d\n", i);
  i += 2;
}

for (int i = 1; i <= 100; i += 2) {
  printf("%d\n", i);
}

Opinion

I am not a language expert, but in most situations in practice I find them transformable.

I personally prefer using for syntax because:

  • loop control structure is in one single place (the for header) making it easy to read, and
  • the loop variable (e.g. i) is not exposed to the outer scope.
Community
  • 1
  • 1
Arun
  • 19,750
  • 10
  • 51
  • 60
  • That's an over-simplification. :) – Sourav Ghosh Oct 26 '16 at 14:42
  • 1
    @SouravGhosh Can you provide a counter-example? – unwind Oct 26 '16 at 14:47
  • @unwind which sort of counter-example you're expecting? – Sourav Ghosh Oct 26 '16 at 14:47
  • A case where what @Arun said isn't true. I don't think there is one, I believe the above transformation works all the time. – unwind Oct 26 '16 at 14:50
  • @unwind ok, technically speaking, an `init statement` is not part of a `while loop`, that is what i tried to explain in my answer. – Sourav Ghosh Oct 26 '16 at 14:51
  • @unwind an optional decl of a for-loop init has no direct counterpart in a while-loop. The decl and init must appear outside the while-loop construct. `for(int i=...` must be done as `int i=...; while(...`. The locality of `i` is different, is it not? – WhozCraig Oct 26 '16 at 14:51
  • @WhozCraig If you are looking for something that has exact syntax as a for loop then...you'll have to use `for` loops ;-) All we are concerned with here whether it'd ever matter to write an equivalent while loop instead. The locality, if it matters, can be overcome with an additional scope: `{ int x = 0; while (x < 5) {...; x++} }`. – P.P Oct 26 '16 at 14:57
  • @unwind I certainly concur with you the *logic* is equivalent as Arun described. Likewise your example of including an enclosing scope is spot-on with full equivalence including covering object scope. *That* would make a perfect synonymous example to the for-loop Arun has in his final example. Don't think I disagree on the logic path; only whether the two junkets are synonymous. In your example, they are completely so. – WhozCraig Oct 26 '16 at 15:03
  • 2
    @unwind: it is an over-simplification in case there is a `continue` statement in the loop body as the *modify something* part would still be executed in the `for` statement and would be skipped in the proposed `while` translation. – chqrlie Oct 26 '16 at 15:03
  • Well, `do..while` construct has some other idiomatic uses than the looping. Update: Actually I see @Lundin have mentioned them in his answer.. – Eugene Sh. Oct 26 '16 at 15:06
  • Note: Please use the correct terms. _statement_ is a well-defined term, which does not apply to e.g. the conditon, and may not apply to the "init" (whatever that be). The `for` allows for a _declaration_ or an _expression_ as _clause-1_ and requires _expressions_ for the latter 2. – too honest for this site Oct 26 '16 at 15:19
2
for(cent_temp = 0; cent_temp <= 20; cent_temp++)
{ /* code */ }

is 100% equivalent to

cent_temp = 0;
while(cent_temp <= 20)
{
  /* code */
  cent_temp++;
}

But a do-while is different since it puts the condition check at the end.


As for when to use which loop, it is a matter of style and therefore a bit subjective. The industry de facto standard style, used by the majority of all C programmers, goes like this:

  • for loops should always be used when performing a known number of iterations. It is then considered the most readable form.
  • while loops should be used the the number of iterations is unknown in advance, or when the loop is turning complex for some reason. For example if you need to alter the loop iterator variable inside the loop body, then you should use a while loop instead of a for loop.
  • do while loops should be used for special cases where you need to skip the condition check the first lap of the loop, for example do { result = send(); } while(result == ok);.
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • 1
    I'd rather extend the usage of `for`: If the three parts (initialisation, condition and advance to next step) are closely related, it is preferable. All these are not hard criterions, though. Most important is readability. `do ... while` is a completely different beast, as it has different behaviour. There is not corresponding `do ... for`. – too honest for this site Oct 26 '16 at 15:10
  • @Olaf Yeah I agree. There's a good rule of thumb saying that the 3 expressions of a for loop should only concern themselves with the loop iterator and not with other, unrelated things (that's also a MISRA-C rule). – Lundin Oct 26 '16 at 15:20
  • Good orientation for beginners (MISRA is worth reading the rationales for the rules, but forget about the rules themselves). It is like cooking: A good cook and a good programmer know when to bend the rules a bit. If you fail, both can result in a terrible product:-) – too honest for this site Oct 26 '16 at 15:22
2

I looked at my Code Complete by Steve McConnell (the bible).

Here is what you can read in chapter 16:

A for loop is a good choice when you need a loop that executes a specified number of times. [...]

Use for loops for simple activities that don't require internal loops controls. Use them when the loop involves simple increments or simple decrements, such as iterating through the elements in a container. The point of a for loop is that you set it up at the top of the loop and then forget about it. You don't have to do anything inside the loop to control it. If you have a condition under which execution has to jump out of a loop, use a while loop instead.

Likewise, don't explicitly change the index value of a for loop to force it to terminate. Use a while loop instead. The for loop is for simple uses. Most complicated looping tasks are better handled by a while loop.

Damien Baldy
  • 456
  • 2
  • 7
1

In general, you would use a for loop to iterate over a finite set of values, whereas you'd use a while or do-while loop to iterate while a specific condition or set of conditions is true. In most of C's contemporaries (Basic, Pascal, Fortran, etc.), a for loop can only iterate over a scalar index:

Fortran:

      DO 10 i=1,10
        statements
   10 CONTINUE

Pascal:

for i := 1 to 10 do
begin
  statements
end;

Both of these snippets loop exactly 10 times. The index i is initialized and updated by the loop automagically. I'd have to go back and check, but I'm pretty sure you cannot write to i in the loop body.

C actually blurred the lines between a for and while loop by adding the control expression:

for ( init-expr ; control-expr ; update-expr )
  statement

In C, a for loop can iterate over a scalar just like Fortran or Pascal:

for( i = 0; i < 10; i++ )
{
  do_something_with( i );
}

Or it can iterate over multiple scalars:

for ( i = 0, j = 0; i < 10 && j < 10; i++, j++ )
{
  do_something_with( i, j );
}

Or it can iterate over the contents of a file:

for( c = fgetc( in ); c != EOF; c = fgetc( in ) )
{
  do_something_with( c );
}

Or it can iterate over a linked list:

for( cur = head; cur != NULL; cur = cur->next )
{
  do_something_with( cur );
}

In Fortran and Pascal, those last three loops would have to be expressed as while loops (which I'm not going to do, because I've pretty much exhausted my Fortran and Pascal knowledge already).

The other big difference between a C for loop and those of Fortran or Pascal is that you can write to the loop index (i, j, c, or cur) in the loop body; it's not specially protected in any way.

A while or do-while loop is used to iterate as long as a specific condition or set of conditions is true:

while( control-expr )
  statement
do
  statement
while( control-expr );

In both a for and while loop, the condition is tested before the loop body executes; in a do-while loop, the condition is tested after the loop body executes, so a do-while loop will always execute at least once.

In C, you can use either a for loop or a while loop in many circumstances:

while ( ( c = fgetc( in ) ) != EOF )
  do_something_with( c );

for ( c = fgetc( in ); c != EOF; c = fgetc( in ) )
  do_something_with( c );

Both loops do exactly the same thing; it's just a matter of which one you think more clearly expresses your intent, or which you think would be easier for other people to understand.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

From the point of view of algorithmic for and while are not the same. Shortly, in algorithmic, for should be used when bounds are known and while when you don't know if the condition can be met or when it can be. For is to repeat something n times (n known), which is exactly the case of your example computation; a for loop should be used (don't you think what the loop makes is more clearly stated in the for loop ?). If you want an example of a must be used while loop, look at something like Collatz sequence. From a point of view of computability, for loops can always be transformed in while loops but not the converse.

From the point of view of computer languages it is now common to fuse both, in C for example, it makes no difference, only syntactic. But remember that in some other language that could be very different, for example in Pascal for loops are very limited.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

Source code is written not only to be compiled and executed by computers but also to be read and understood by humans.

A computer doesn't really mind whether a for loop, a while loop or a goto is used. On the other hand, a human expects different meanings for different structures.

  • computing values over a known range of inputs is best shown with a for loop;
  • reading a file up to its end is best shown with a while loop.

Choosing which structure to use is similar as choosing a variable name.

mouviciel
  • 66,855
  • 13
  • 106
  • 140