Sample C++ MidTerm 2


The correct answers are highlighted in red.

Part I - Multiple Choice

  1. A function calling statement must supply arguments that

    1. match the function header in number
    2. match the function header in number and order
    3. match the function header in number, order, and data type
    4. match the function header in number, order, data type, and names
    5. match the function header in number, names, and data type

  2. Which of the following appear in a function header?

    1. the function name, return type, and argument types
    2. the function name, return type, argument types and argument names
    3. the function name, return type, and argument names
    4. the function name and the supplied arguments

  3. How does a function report its answer back to its calling (or boss) function?

    1. by altering or storing the result into one of the variables passed as an argument
    2. by altering or storing the result directly into the caller�s variable
    3. by cout � ing the result to the screen
    4. by asking the user via an input function
    5. by executing a return statement with the answer

  4. A function prototype does not have to __________.

    1. include argument names
    2. end with a semi-colon
    3. agree with the function header
    4. match with all calls of the function

  5. What will be displayed by the following code?

  6. int main()
      {
      int num = 3;
      
      fn(num);
      cout << num;
      
      return 0;
      }
      
      
    int fn( int n )
      {
      n++;
      }
    1. The code will not display anything
    2. 3
    3. 4
    4. 5
    5. There is not enough information provided to determine what will be displayed.

  7. When the body of a function begins to execute what is true of its arguments?

    1. they must be declared as local variables in the function
    2. they must be initialized by the function before they are used
    3. they already have values provided by the calling function and are ready to be used
    4. the arguments must be #defined

  8. A variable called score is declared in main(). main() calls a function UpdateScore to update the score. UpdateScore also has a variable called score. When a value is added to score in UpdateScore, the value of score in main() is also changed.

    1. true
    2. false

  9. Prototype statements are placed before int main().

    1. true
    2. false

  10. The function header and the calling statement must contain the name and the data type of the arguments.

    1. true
    2. false

  11. The statement int main() means that main is a function that takes no arguments, and returns an integer.

    1. true
    2. false

  12. What is the subscript of the last element in the array Table if it is defined as follows?

  13. float Table[30];
    1. 30
    2. 31
    3. 29
    4. 0
    5. none of the above

  14. Which of the following statements (a-d) about Table is true?

  15. float Table[] = { 0.9, 0.8, 0.7, 0.6 };
    1. The definition for Table will cause an error because there is no value specified inside of the square brackets
    2. Table[1] contains the value 0.9
    3. There are actually 5 values stored in Table - the four listed and a null terminator as the fifth element
    4. The definition for Table will cause an error because an array cannot be initialized when it is created
    5. All of the statement (a-d) are false

  16. Which of the following "chunks" of C++ code will print the contents of an array called ar that has been defined to hold 25 integer values and has been initialized with 25 integer values?

  17. int i;
    1. cout << ar[];
    2. for( i = 0; i == 25; i++ )
        cout << ar[i] << " ";
    3. for( i = 0; i < 25; i++ )
        cout << ar[i] << " ";
    4. for( i = 0; i < 25; i++ );
        cout << ar[i] << " ";

  18. The following is a valid array definition.

  19. int ar[];
    1. true
    2. false

  20. What will be displayed by the following code?

  21. int main()
      {
      int num[5] = { 2, 4, 6, 8, 10 };
      int i;
      
      fn(num);
      
      for( i = 0; i < 5; i++ )
        cout << num[i] << ' ';
      
      return 0;
      }
      
      
    int fn( int n[] )
      {
      n[3] = n[3] + 1;
      }
    1. The code will not display anything
    2. 2 4 6 8 10
    3. 2 4 7 8 10
    4. 2 4 6 9 10
    5. There is not enough information provided to determine what will be displayed.

Part II - Short Answer

  1. We call the pieces of information that are passed to a function, which it then uses to do its task a/an argument.

  2. A function may return 0 or 1 result(s). It may take 0 to many arguments.

  3. List two differences between a function prototype and a function header:

  4. Function prototypes are located before int main().

  5. If a function does not return anything, then the return type on the function prototype and function header is void.

  6. Consider the following program:

  7. int main()             int abc(int m)           float xyz(float v, int k)
      {                      {                        {
      int a = 3, b;          int i, j = 1;            int i;
      float x = 2.0, y;                               float w = 1.0;
    
      b = abc(a);            for(i=1; i<=m; i++)      for(i=1; i<=k; i++, w *= v);
      y = xyz(x, a);            j = j * i;
      return 0;
      }                      return j;                return (w);
                             }                        }
    

    When the program is completed, the value of b is 6 and the value of y is 8.

  8. Complete the following sentence: If you declare an array to hold N values, legal subscripts run from 0 to N - 1.

  9. Complete the following sentence: the unsubscripted name of an array is the address of the array.

Part III - Coding

  1. Write a function that takes a real number of ounces (representing the weight of a letter) and returns an integer number of cents which represents the cost of mailing the letter. The rules for calculating the cost are as follows:

  2. int ouncesToCents( float ounces )
    {
    if( ounces <= 1 )
      return 33;
    
    else if( ounces <= 1.5 )
      return 40;
    
    else if( ounces <= 2 )
      return 50;
    
    else
      return (int) (30 * ounces);
    }
    
  3. Write a function (call it getAns()) that prompts the user to enter a single letter from "a" to "d". It will return that letter to the calling function. It will not return anything but "a" through "d". If the user enters anything else, it will display an error message and ask the user to re-enter until they enter a value between "a" through "d".

  4. string getAns()
    {
    string answer;
    
    cout << "Enter a letter from a to d: ";
    cin >> answer;
    
    while( answer != "a" && answer != "b" &&
           answer != "c" && answer != "d" )
      {
      cout << "Invalid answer. Try again: ";
      cin >> answer;
      }
    
    return answer;
    }
    
  5. Write a single statement that will both call getAns() and display the value returned.

  6. cout << getAns();
  7. Write a function called GetIntegerInRange() that gets an integer value from the user that is between 0 and an upperbound. It takes 1 argument:

  8. It returns an integer: the value that is between 0 and the upperbound.

    The function should prompt the user to enter a value between 0 and the passed in high value. As long as the user enters an an invalid value (i.e. smaller then 0 or greater then the high value), display an error message and have the user try again. Once the user has entered a valid value, it should be returned.

    Example: assuming the user passes in the value 120. The output should closely resemble:

    Enter a number (0 to quit) between 0 and 120:

    NOTE: You may assume that the passed in high value is greater than 0.

    int getIntegerInRange( int upperBound )
    {
    int userVal;
    
    cout << "Enter a number (0 to quit) between 0 and " << upperBound << ": ";
    cin >> userVal;
    
    while( userVal < 0 || userVal > upperBound )
      {
      cout << "Invalid value. Try again: ";
      cin >> userVal;
      }
    
    return userVal;
    }
    
  9. Write a COMPLETE program that uses GetIntegerInRange() to accept temperatures from the user in the range of 0 to 120. The value of 0 serves as an exit signal.

  10. After all the temperatures have been entered, the program should display the following with brief labels:

    You may assume that at least one temperature above 32 is entered and that one temperature below 32 is entered.

    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    
    int getIntegerInRange( int );
    
    int main()
    {
    int temp, above32cnt = 0, below32cnt = 0, above32sum = 0, below32sum = 0;
    float above32Avg, below32Avg;
    
    temp = getIntegerInRange( 120 );
    
    while( temp != 0 )
      {
      if( temp > 32 )
        {
        above32sum += temp;
        above32cnt++;
        }
      else    //note: this will include temperatures equal to 32
        {
        below32sum += temp;
        below2cnt++;
        }
    
      temp = getIntegerInRange( 120 );
      }
    
    above32avg = (float) above32sum / above32cnt;
    below32avg = (float) below32sum / below32cnt;
    
    cout << "The average of the temperatures above 32 is " << above32avg << endl
         << "The number of temperatures above 32 is " << above32cnt << endl << endl
         << "The average of the temperatures below 32 is " << below32avg << endl
         << "The number of temperatures below 32 is " << below32cnt << endl;
    
    return 0;
    }
    
  11. Assume an array called AR contains 45 integers. Write a loop to print out the values of every other integer starting from subscript 0.

  12. int sub;
    
    for( sub = 0; sub < 45; sub += 2 )
      {
      cout << AR[sub] << endl;
      }
    
  13. Assume an array called AR contains 10 integers. Write code to swap the very first and the very last values in the array.

  14. int temp = AR[0];
    AR[0] = AR[9];
    AR[9] = temp;
    
  15. Declare an array to hold 500 integers. In the declaration statement, initialize the array so the very first value is 2, the second is 4, and all the rest are 0.

  16. int AR[500] = { 2, 4 };
  17. Write a function to cube the first N elements in an array of doubles. The function should be passed the array and the number of elements to be cubed. It returns nothing.

  18. void cubeAr( double ar[], int N )
    {
    int sub;
    
    for( sub = 0; sub < N; sub ++ )
      {
      ar[sub] = ar[sub] * ar[sub] * ar[sub];
      }
    }
    
  19. Write a function to return the sum of the first N elements in an array of doubles. The function can assume N >= 0. The function should be passed the array and the number of elements to be added together.

  20. double sumAr( double ar[], int N )
    {
    int sub;
    double sum = 0;
    
    for( sub = 0; sub < N; sub ++ )
      {
      sum += ar[sub];
      }
    
    return sum;
    }