UMBC CS 201, Fall 07
UMBC CMSC 201
Fall '07

CSEE | 201 | 201 F'07 | lectures | news | help

Loop Conversion

Any for loop can be converted into an equivalent while loop.

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++;
}

So, which should I use?

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

Any for loop?

Unfortunately, any 'for' loop can be written as a 'while' loop. That doesn't mean you should use them interchangeably (see sermon above)

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>
}


CSEE | 201 | 201 F'07 | lectures | news | help

Thursday, 23-Aug-2007 12:00:52 EDT