Looping Control Structures


Selection control structures are fine for executing a block of code once for a given condition.

Looping control structures are used to execute a block of code multiple times until a condition is met. It is extremely important that the condition is met at some point in the loop, or you get what is known as an endless loop - one that never stops without killing the program.

Three basic loop structures are:

  1. for : a pre-test loop
  2. while : a pre-test loop
  3. do while: a post-test loop

All loops have three basic parts:

  1. A looping variable
  2. A condition against which to test the value of the looping variable
  3. An increment/decrement assignment for the looping variable

A pre-test loop is one in which the condition is tested before the code block is executed. This means that the code block may never be executed.

A post-test loop is one in which the condition is tested after the code block is executed. This means that the code block will always execute at least once.

The steps that take place in a pre-test loop are:

  1. Initialize the looping variable
  2. Test the looping variable
  3. If the test is false, exit the loop
  4. If the test is true execute the code
  5. increment/decrement the looping variable
  6. return to step 2

The steps that take place in a post-test loop are: 

  1. Initialize the looping variable
  2. Execute the code
  3. Test the looping variable
  4. If the test is false, exit the loop
  5. If the test is true increment/decrement the looping variable
  6. return to step 2

The for Loop

Identify the three basic parts in the loops below initialize, test, increment/decrement

	for ( int i=0; i<10; i++ );

	for ( int i=0; <n; i++ ) x += i; // this loop will calculate the triangle value of n

	for ( int i=1; i=<n; i++ ) { // why start the loop at 1?
		x += i;  // triangle value of n
		y *= i;  // factorial value of n
	}
The while Loop

Identify the three basic parts in the loops below initialize, test, increment/decrement

	int i = 0;
	while ( i<10 ) i++;

	int i = 0;
	while ( i<n ) i++;

	int i = 1; // why start the loop at 1?
	while ( i=<n ) {
		x += i;  // triangle value of n
		y *= i;  // factorial value of n
		i++;
	}
The do while Loop

Identify the three basic parts in the loops below initialize, test, increment/decrement

	int i = 0;
	do {
		x += i; // this loop will calculate the triangle value of n
		i++;
	} while ( i<n );