Introduction to C Programming
Iteration through Loops

Outline: Loops are a form of iteration (recursion being the other form). Proper use of recursion depends on viewing the problem in a certain way to extract the recursion. Loop-based iteration is no different. They all come down to the same process.

while Loops

The while loop is the universal loop - all loops can be constructed using while loops. All other loops are created for specific circumstances.
        while( condition ) 
           BB; 
        int i = 0;
        while( i < 5 ) 
	{
            printf( "i = %d\n", i);
	    i++;
	}
        printf( "After loop, i = %d\n", i );
How it works:

The condition is checked prior to executing the body every time. It will only exit once the condition evaluates to false. Make sure you don't forget to have something change so that it eventually terminates the loop.


When to use this construct: This is appropriate for any loop - unless your loop follows the special circumstances for the loops below. In general, this is for loops for which the exit condition is not simply a counter that increments (as you see above). Instead, it's perfect for loops such as menus asking for user input.

do-while

If you know you want to run the body of a loop at least once, then a do-while loop is appropriate.
	do{
            BB;
	} while( condition )
	int stop = 0;
	do {
		stop = Menu();
	} while (!stop);
How it works:

The BB will run once no matter what, then the condition will be evaluated. Once that BB is run once, it is equivalent to the while loop.


When to use this construct: When you want the body to run at least once.

For

The for loop was created based on a common mistake when implementing loops - forgetting the update step. That is, forgetting to increment your counter or some such action. If you forget the action that gets you closer to loop termination, then your loop will not terminate.

The for loop is designed so that

	for (init; condition; update)
	{
		BB;
	}
	int i;
        for( i = 0; i < 5; i++ )
            printf( "i = %d\n", i );
        printf( "After loop\n");
How it works:

The init code runs before the loop. Then it evaluates the condition. Next, it runs the loop body. It finishes with the update step, looping back to the condition again. The most common mistake in terms of understanding is forgetting that the condition is evaluated prior to the first loop iteration.


When to use this construct:

When your loop control is very simple and can be expressed easily inside the for loop syntax.

The comma operator

            int i, j = 10, sum;
            for( i = 0, sum = 0; i < 5; i++, j-- )
                sum += i * j;

break and continue