Physics 5—Midterm Exam—Spring ’04    Name________________________________

 

  1. It is known that the harmonic series  is divergent; that is, it grows without bound.  However, it diverges very slowly—summing 10000 terms only amounts to about 9.78751.  Write C++ code for a program accepts a user-supplied value for M and then computes and displays the minimum value of  N so that .    Use a while structure for looping.

  2. Write C++ code for a program to produce a random integer between 1 and 100 and allow the user to guess what it is.  If it is too low or too high, inform the user and prompt them to guess a number in the narrowed interval of remaining possibilities.  The screen for game play might look something like this:

Enter a guess for the number between 1 and 100

62

Your guess is too low.

Enter a guess for the number between 62 and 100

86

 

Your guess is too low.

Enter a guess for the number between 86 and 100

95

 

Your guess is too low.

Enter a guess for the number between 95 and 100

98

 

Your guess is too low.

Enter a guess for the number between 98 and 100

99

Congratulations! The target was, in fact, 99.

 

  1. Each of the following code snippets contains an error.  Identify the error as either a syntax error or a logic error and suggest a fix for the error

a.        


#include <iostream>


int main()

{

      int x = 10;

      while(x != 1) x /= 5;

      cout << x;

      return 0;

}

b.        The following code is meant to assure that the input is in the range between 1 and 100.  How does it do?

#include <iostream.h>
 
void main()
   cout << “\nEnter a number between 1 and 100:” endl  
   do

           cin >> guess;

   while(guess>0 && guess<UpperBound)
   cout << “Your guess was “ << setw(5) guess;  
return 0;


  1. Write a program to carry out the activity in the flow chart below.  What is the result when the input is 42?