Assignment 6

Lab assignment 6 is available on the moodle for your practice. Please note that this is an ungraded assignment. You can submit the answers directly on the moodle for the first two questions. For the 3rd question, you can use your preferred IDE to write the code and then copy paste that on the moodle.

We encourage you to do these ungraded assignments by yourself until the end, as this will help you to improve your coding skills.

  1. Reference parameters: What is the output of the following code?
    void mystery(int &b, int c, int &a)
    {
      a++;
      b--;
      c += a;
    }
    
    int main()
    {
      int a = 5;
      int b = 2;
      int c = 8;
      mystery(c, a, b);
      cout << a << " " << b << " " << c << endl;
      return 0;
    }
    
    Explain.
  2. Return values: What is the output of the following code?
    int mystery(int b, int c)
    {
      return c + 2 * b;
    }
    
    int main()
    {
      int a = 4;
      int b = 2;
      int c = 5;
      a = mystery(c, b);
      c = mystery(b, a);
      cout << a << " " << b << " " << c << endl;
      return 0;
    }
    
    Explain.
  3. Square root by Newton's method: In order to compute the square root of a number a, we can start with some approximate value x and refine it as follows:
    y = (x + a/x)/2
    
    For example, if a=4 and our initial estimate is x=3, then:
    y = (3 + 4/3)/2 = 2.1666
    
    We can repeat the process again with y' as our new estimate. Continuing the above example, we get:
    y' = (2.1666 + 4/2.1666)/2 = 2.0064
    
    Now, repeat again with y' as our new estimate until there is no change in the value computed.

    Implement a function float square_root(float a, int k) that takes in a floating point number a, an integer k corresponding to the number of times to repeat the estimation procedure and returns the square root. If k <= 0, then the function is expected to run until there is no change in the estimated value. Use the initial estimate of 1.0 for all cases.

    Examples: