Name: ______Key_________

Quiz 4 (Week 5)

CS-150, Fall ‘02, Dr. C. S. Tritt

Each question is worth the same amount.

 

  1. What output would be produced by the following fragment of C++ code (assume any necessary header files have been included and variables declared and defined)?

 

   double elev = 800.;

   double drop = 250.;

   while (elev >= 0)

   {

      cout << "Falling through: " << elev << " m.\n";

      elev = elev - drop;

      if (elev < 400.) drop = 150.;

   }

   cout << "Bang!\n";

 

   return 0;

Answer -

Falling through: 800 m.

Falling through: 550 m.

Falling through: 300 m.

Falling through: 150 m.

Falling through: 0 m.

Bang

 

Math errors –5, getting looping wrong –15, input/output errors –5, first and last lines only –20 (common mistake – ask about logic) and missing first line (… 800 m.) –5.

 

  1. Write a fragment of C++ code that reads two integers entered by the user and repeatedly subtracts the second from the first and displays the result until the result is negative. For example, if the user entered 7 and 3 the program would display 4 1 (the exact appearance of the output is not critical).

Answer --

   int i1, i2;

   cout << "Enter two integers: ";

   cin >> i1 >> i2;

   i1 = i1 - i2; // Omitting this displays the first value.

   while (i1 >= 0)

   {

      cout << i1 << " ";

      i1 = i1 - i2;

   }

   cout << endl;

 

Going around 1 too many times –10, minor input/output errors –5, infinite loop –25, displaying first entered value okay, hard coding 7 & 3 –10, using poor variable names (one & two) okay, omitting output of differences –20, use of for loop okay, input inside of loop – 20 and not recognizable C++ – 40.