Module 5. Loops Exercises

1.  Complete the C++ code below.  It should input an ID number and
Exam 1 score for every student in CS 180.  Use a while loop to input
and sum the scores.  After all actual ID numbers and scores are input
to your program, a really large ID number (at least as large as the
named constant ID_MAX) is input along with an irrelevant score.
Compute the average Exam 1 score.  You need not output anything.
Assume that there is at least one student in CS 180.  Declare any
other variables you need.

  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


  cin >> id_number >> score;

2.  The C++ code below uses float type variables x, y, z, and square.
It computes the square root of the variable square by repeatedly
moving x and y closer together so that x*x <= square and y*y >= square
until they are so close that either one could be used as the square
root.  Complete the code below by making the compound statement {...}
into a do/while loop that continues until the difference y-x is
smaller than 0.001.  You may use the literal constant 0.001 in your

  x = 0.0;
  y = 100.0;

     z = (x + y) / 2.0;
     if (z*z > square)
       y = z;
       x = z;

3.  Complete the C++ code below.  The variable days_in_month contains
a count of how many days are in this month.  Write a for loop to input
a temperature (temp) for every day in this month.  When the loop ends
the variable warm_days should be the count of the number of days in
this month in which the temperature was greater than the constant
FREEZING.  You need not output anything.  Assume that FREEZING has a

  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;

4.  In the while loop below explain what happens if xxxxxxx is the
break statement.  Then explain what happens if xxxxxxx is the continue

  while (gravity >= air_pressure)
     gravity -= force;
     if (helium > mercury) 
     gravity *= deflection;