Module 5. Loops Exercise Answers

1.
  const int ID_MAX = 999999;  // every student ID number is smaller
                                            // than 999999
  int id_number;  // student ID number
  float score;    // student score on Exam 1
  float average;  // average of all student Exam 1 scores
  int counter;    // counter to determine number of students
  float sum;      // sum of all student Exam 1 scores

  sum = 0.0;
  cin >> id_number >> score;
  counter = 0;
  while (id_number < ID_MAX)
    {
     sum += score;
     counter++;
     cin >> id_number >> score;
    }
  average = sum / counter;

2.
  x = 0.0;
  y = 100.0;

  do
    {
     z = (x + y) / 2.0;
     if (z*z > square)
       y = z;
     else
       x = z;
    }
  while ( (y-x) >= 0.001);

3.
  int day;            // counter for days in this month
  int days_in_month;  // number of days in this month
  int warm_days;      // number of warm days in this month 
  float temp;         // temperature for each day

  warm_days = 0;
  for (day = 1; day <= days_in_month; day++)
    {
     cin >> temp;
     if (temp > FREEZING) 
       warm_days++;
    }

4.  The break statement immediately terminates the loop.  The continue
statement skips the remainder of that loop iteration (that is, the
statement gravity *= deflection;), but can go through the loop again
if gravity is greater than or equal to air_pressure.