UMBC CMSC 201 Spring '02 | CSEE | 201 | 201 S'02 | lectures | news | help |
For example, the for loop
for (i = 0; i < 10; i++) { printf("The value of i is %d\n", i); }
is equivalent to the while loop
i = 0; while (i < 10) { printf("The value of i is %d\n", i); i++; }
Glad you asked -- this is the one time when I can get on my soapbox....
Use a for loop when the number of repetitions is controlled by a counter as in the example programs provided today. Your code "knows" exactly how may times the loop will be executed because it's predetermined.
Use a while loop when the number of repetitions is controlled by a condition (like the user entering 0). There is no way for your code to "know" if the loop will be executed 1 time or 1000000 times. The number or repetitions is indeterminate, based on a a condition over which your code has no control.
End of Lecture
Let <LCV> stands for "loop control variable":
for (<initialize LCV>; <continuation_test>; <update LCV>) { <body of loop> }
is equivalent to
<initialize LCV> while (<continuation_test>) { <body of loop> <update LCV> }