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

Re: Difference between for and while loop



Thus spake raja kumar (meerajakumar@hotmail.com):

> 
> 
> 
> Sir,
> 
> 
>     could u tell me the all the differences between FOR and WHILE loops
> please..

C confuses the two. In many languages (e.g. the pascal family) for is
used for definite (i.e. a certain number of times) loops and while for
indefinite (i.e. until some condition becomes true/false) loops.

In C you can do *anything* with a for loop that you can do with a
while, which is not true in Pascal.

E.g.

	while (condition)

is equivalent to:

	for (;condition;)

The normal use of for in other langugaes would be achieved in C with
something like 

	for (i = 1; i <= 100; i++)

corresponding to pascal's

	for i := 1 to 100

Also, in pascal you may not make any assignment inside the for loop
body to the loop control variable (i in the above).

So something like C's (don't ask why youi'd want to do this)

       for (i = 1; i <= 100; i++){
       /* stuff */
       if (condition)
          i++;
       /* more stuff */
       }

is not possible in pascal.

Bottom line: in C you can dispense with while or you can dispense with
for. In pascal (and friends) you can do without for but you cannot do
without while.

Incidentally, much as I love recursion, there are some algorithms
which are far more comprehensibly expressed using iteration.
-- 
|Deryk Barker, Computer Science Dept. | Music does not have to be understood|
|Camosun College, Victoria, BC, Canada| It has to be listened to.           |
|email: dbarker@camosun.bc.ca         |                                     |
|phone: +1 250 370 4452               |         Hermann Scherchen.          |



Reply to: