The for Statement and Repetition Structures, Continued

Tom Kelliher, CS17

Apr. 26, 1996

The for Statement

Fine Points

Loop Structures

Counter-Controlled Loops

See previous examples

Sentinel-Controlled Loops

Entering a list of ages and using a negative age to indicate ``end of input'':

cout << "Enter an age: "
cin >> inputAge;

while (inputAge >= 0)
{
   // Do something with the age.

   cout << "Enter an age: "
   cin >> inputAge;
}

Note the redundancy. Better expressed through a posttest structure:

do
{
   cout << "Enter an age: "
   cin >> inputAge;

   // Do something with the age.
} while (inputAge >= 0);

Suppose the first age is itself negative? (Unlikely in this case.) The ``best'' solution:

while (1)
{
   cout << "Enter an age: "
   cin >> inputAge;

   if (inputAge < 0)
      break;

   // Do something with the age.
}
Midtest repetition?

Continue Statement

Not used very often.

Example: rejecting invalid inputs.

#include <iostream.h>
#include <iomanip.h>

double computeAverage(int number);

int main()
{
   int n;

   do
   {
      cout << "Enter the number of scores: ";
      cin >> n;
   } while (n < 1);

   cout << "\nThe average score is " << setprecision(1)
        << setiosflags(ios::fixed) << computeAverage(n) << ".\n";
   cout << "\nThe bill is in the mail.\n";

   return 0;
}

double computeAverage(int number)   // Why return double?
{
   int sum = 0;
   int score;
   int i;

   // Note comma operator in loop initializer.
   // The form of this differs from a similar example in the text.

   for (sum = 0, i = 0; i < number; ++i)
   {
      cout << "Enter score " << i << ": ";
      cin >> score;

      if (score < 0)
      {
         cout << "Score must be non-negative!  Score discarded.\n";

         // Why is this decrement necessary?
         --i;
         continue;  // Skip to next iteration.
      }

      sum += score;
   }

   return sum / number;   // Will this return a double?
}

Nested Loops

What is printed by:

int i, j;

for (i = 0; i < 3; ++i)
   for (j = 0; j < 4; ++j)
      cout << j << endl;

What is printed by:

int i, j;

for (i = 0; i < 3; ++i)
   for (j = 0; j < 4; ++j)
      cout << setw(8) << i << setw(8) << j << endl;

An Advanced Example

Arrays and sorting.

An array of 5 ints:

int i;        // Loop counter.
int temp;     // Temporary storage.
int sorted;   // Flag variable.
int data[5];  // Array of 5 ints.

for (i = 0; i < 5; i++)
{
   cout << "? ";
   cin >> data[i];
}
Sorting the five numbers:
sorted = 0;   // Set to 0 so that we get into the loop.

while (!sorted)
{
   sorted = 1;

   for (i = 0; i < 4; ++i)
      if (data[i] > data[i + 1]
      {
         sorted = 0;
         temp = data[i];
         data[i] = data[i + 1];
         data[i + 1] = temp;
      }
}

Exercises

  1. Problems 2 and 3, pg. 420.
  2. Problems 12 and 15, pg. 422.


Thomas P. Kelliher
Thu Apr 25 12:08:41 EDT 1996
Tom Kelliher