[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Difference between for and while loop



Jan Trippler wrote:

> On Fre, 18 Apr 2003 at 16:40 (+0300), Aryan Ameri wrote:
> > On Friday 18 April 2003 13:46, Frank Gevaerts wrote:
> > > On Fri, Apr 18, 2003 at 12:58:43PM +0300, Aryan Ameri wrote:
> [...]
> > > > Well, the way it has been explained to me, you can also use the FOR
> > > > loop in non defined loops, and you can also set a FOR loop, in a
> > > > way that the minimum execution time might be less than 1, say 0.
> > >
> > > What language are we talking about ?
> > 
> > I was talking about C. I guess that was the OP's question.
> 
> But thers's no way to prevent the first execution of the loop body.
> The stop condition (even if it's missing) is checked at the _end_ of
> first execution. You can leave the body empty or use a *break* to
> get out of the loop, but that has nothing to do with the definition
> of the for loop.

What? That's completely wrong. The test in a for loop in C in checked at
the TOP of the loop, before the first execution of the body.

The execution of the following two loops is identical:

FOR:

    for (i = 0; i < 10; ++i)
        if (foo(i))
            break;

WHILE:

    i = 0;

    while (i < 10)
    {
        if (foo(i))
            break;

        ++i;
    }

One interesting way of demonstrating a subtle difference between C's for
and while loops is to change 'break' to 'continue' in both of the above
examples. With 'continue', the for loop will execute no more than ten
times (because ++i is always executed after each pass), whereas the
while loop, with 'continue', would execute _at_least_ ten times, and
possibly forever (because the ++i is executed only when foo returns 0;
if it always returns non-zero, the while loop will never exit).

I though your recursion examples were unnecessarily complex. A simple
factorial or Fibonacci sequence function would have demonstrated
recursion quite adequately with a fraction of the code.

Craig

Attachment: pgps1d3Qyi58_.pgp
Description: PGP signature


Reply to: