CSCI 159 Quiz 2 (F24N01/02) Wednesday lab Sample solutions


Question 1 [4 marks]
Consider the function prototype below then answer parts 1-3.

// computes and returns the square root of f
double rootOf(float f);

  1. What is the return type of the function?
    Sample solution
    double
    

  2. What is the return type of the parameter?
    Sample solution
    float
    

  3. Assuming it was part of a correct main routine (and larger program), write a single line of code that makes a call to the function, passing 3.5 as the parameter and storing the returned value into a variable named 'answer'.
    Sample solution
    answer = rootOf(3.5);
    


Question 2 [3 marks]
For the code segment below (assuming it's part of a larger correct program) answer questions 1 and 2.

   // beginning of code segment
   if (a < b) {
      cout << "a is smaller" << endl;
      if (b == 10) {
         cout << "a is less than 10" << endl;
      }
   } else {
      cout << "a may be bigger" << endl;
   }
   // end of code segment

  1. As precisely as possible, what will be its output if a is 7 and b is 3?
    Sample solution
    a may be bigger
    

  2. As precisely as possible, what will be its output if a and b are both -1?
    Sample solution
    a may be bigger
    - since the a==b would fall under the 'else' case
      for the top test
    


Question 3 [3 marks]
As precisely as possible, show the output from the following program assuming the user types in 20 when they run it.
#include <iostream>

void q3(int i, int n);

int main()
{
   int x;
   std::cout << "Enter an integer: ";
   std::cin >> x;
   q3(5, x);
}

void q3(int i, int n)
{
   if (n <= 0) {
      std::cout << "done!" << std::endl;
   } else {
      int v = n - i;
      std::cout << v << std::endl;
      q3(i, v);
   }
}
Sample solution
15
10
5
0
done!
- the initial calls is q3(5,20), then the recursive calls are
  q3(5,15), q3(5,10), q3(5,5), q3(5,0)