Homework #2

practice problems for midterm - due Thursday Jan. 18
  1. for(int x=0, y=0; x < 14; x+=2) {
        y += x;
    }
    
    cout << "x: " << x << "; y: " << y << endl;
    
    1. What does the above code print?
    2. Rewrite this code as a while loop.
    3. Rewrite this code using x++ as the increment operator, and an if statement in the body.
  2. std::vector vec;
    std::string s;
    int x, y = 0;
    
    What do the above variables contain?

  3. Explain the difference between defining, declaring and initializing a variable.

  4. Which of the following are legal variable definitions? (Legal meaning will compile.)
    vector v1(5,"twenty");
    vector v2 = {0,1,2};
    int *iarr = new int[20];
    vector v3(iarr);
    vector v4(v3);
    

  5. What is the appropriate use of a header file?
  6. std::vector vec(20);
    std::vector::const_iterator viter = vec.begin();
    
    double dbl = 2.0;
    while(viter != vec.end()) {
        *viter = (dbl *= dbl);
        viter++;
    }
    
    There's an issue in the above code, and it won't compile. What is it? Fix it, and then provide the contents of vec after the error has been fixed.

  7. int x = 15, y = 20;
    int &z = x;
    int *px = &x, *py = &y, *pz = &z;
    *pz = z + *py;
    z -= 10;
    py = pz;
    *pz = x;
    
    What is in the variables x, y and z after the above code runs?

  8. int &mystery(int &a, int b) {
      int c = b;
      b = a;
      a = c;
      return c;
    }
    
    int main() {
      int x = 2, y = 5;
      int z = mystery(x,y);
      return 0;
    }
    
    What are the contents of x, y and z after the above code?

    NOTE: We talked about this question in class (01/17), and I said it was a problem that I'd returned c. This is true: it is going to be a problem, it's bad horrible practice to return a reference to a local variable, BUT it isn't a compiler error, it only results in a warning. z will point to where c was in memory. However, that space can't have been changed by the end of the program. Use that to help you figure it out =)