CSCI 159 Quiz 2 (F24N01/02) Monday lab Sample Solutions


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

// computes and returns pi to the power of p
float powerPi(int p);

  1. What is the return type of the function?
    Sample Solution
    float
    

  2. What is the return type of the parameter?
    Sample Solution
    int
    

  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 7 as the parameter and storing the returned value into a variable named 'answer'.
    Sample Solution
    answer = powerPi(7);
    


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 " << a << endl;
      if (b < 0) {
         cout << "b is negative" << endl;
      } else {
         cout << "b is not negative" << 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 is 7
    b is not negative
    

  2. As precisely as possible, what will be its output if a and b are both -1?
    Sample Solution
     - doesn't produce any output at all (no else case so no action if a==b)
    


Question 3 [3 marks]
As precisely as possible, show the output from the following program assuming the user types in 4 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(1, x);
}

void q3(int i, int n)
{
   if (i > n) {
      std::cout << "done!" << std::endl;
   } else {
      int v = i * 5;
      std::cout << v << std::endl;
      q3(i+1, n);
   }
}
Sample Solution
5
10
15
20
done!
- the initial call is q3(1,4), then the recursive calls are
  q3(2,4), q3(3,4), q3(4,4), q3(5,4)