e02 : Midterm exam - II

num ready? description exam date
e02 true Midterm exam - II Thu 02/28 03:30AM

Exam logistics

Thursday, 2/28 in the regular lecture classroom at the usual lecture time

You may bring only one 8.5” x 11” piece of paper with notes on both sides.


Open Review Session

The Open Review Session will be in HFH 1104 from 6-9PM on Monday, Feb 25th. Tutors will go over practice problems. Feel free to stop by at any time during that interval to ask for help with any of the topics or practice problems.

Have fun practicing what you’ve learned so far!

Remember: programming is not a spectator’s sport – you have to actively write code in order to get better at writing, reading, and debugging it.


Midterm 2 Topics


Practice Problems

For these problems, we recommend that you run through this code “on paper”, try to figure out what the output should be, then run the code and compare the answers. Understand why the computer produced the answer you saw, and look closer at why your answer might not match what the computer provided.

Question 1: Pointer Basics

Write the output for each scenario and create pointer diagrams for each. (You can check PythonTutor for C++ to see how each case is stored in memory). a)

int p1;
p1 = 3;
cout << 3 << endl;
cout << p1 << endl;

b)

int *p2;
p2 = &p1;
cout << *p2 << endl;
cout << p2 << endl;

c)

int p3;
int *p4;
p3 = 6;
//cout << *p4 << endl; //what happens here? why would you _want_ this commented? 
p4 = p2;
p2 = &p3;
cout << *p2 << endl;
cout << *p4 << endl;

Question 2: All Roads Point to….Rome?

Write the output of the following:

int main(){
  char rome = 'r';
  char venice = 'v';
  char genoa = 'g';
  char *romeptr = &rome;
  char *veniceptr = &venice;
  char *genoaptr = &genoa;
  cout << *romeptr << endl;
  cout << *veniceptr << endl;
  cout << *genoaptr << endl;
  veniceptr = genoaptr;
  cout << *veniceptr << endl;
  *romeptr = 'g';
  genoaptr = romeptr;
  cout << *romeptr << endl;
  cout << *genoaptr << endl;
  cout << *veniceptr << endl;
  return 0;
}

Question 3: Get to the Point!

Write the output of the following:

int main() {
  char letter1 = 'a';
  char letter2 = 'b';
  char letter3 = 'c';
  char *point1 = &letter1;
  char *point2 = &letter2;
  char *point3 = &letter3;
  cout << *point1 << endl;
  cout << *point2 << endl;
  cout << *point3 << endl;
  point2 = point1;
  cout << *point2 << endl;

  letter1 = 'c';
  point3 = point1;
  cout << letter1 << endl;
  cout << *point2 << endl;
  cout << *point3 << endl;
  return 0;
}

Question 4: Reference Parameters

Write the output of the following:

void increment1(int x, int y){
    x++;
    y++;
    cout << x << endl;
    cout << y << endl;
    return;
}
void increment2(int &x, int &y){
    x++;
    y++;
    cout << x << endl;
    cout << y << endl;
}
int main(){
    int a = 6;
    int b = 10;
    increment1(a,b);
    cout << a << " " << b << endl;
    increment2(a,b);
    cout << a << " " << b << endl;
}

Question 5: A Malfunctioning Function

What is wrong with the function below?

// The function is supposed to swap the values of the passed arguments. 
swap(int x, int y){
    x = y;
    y = x;
    cout << x << endl;
    cout << y << endl;
}
int main(){
    int a = 12;
    int b = -4;
    swap(a,b);
    cout << a << " " << b << endl;
}

What is the output of this program? Why?

What do we need to do to correct it?

Question 6: Pointer Ping-Pong

Consider the following code:

int num1 = 3;               //line 1
int num2 = 1;               //line 2
int *ptr1 = &num1, *ptr2=0; //line 3
*ptr1 = num2;               //line 4
ptr2 = ptr1;                //line 5
*ptr2 = *ptr1 + num2;       //line 6

a. Draw a pointer diagram to show the state of memory after the first three lines of the above code are executed. Assume num1 is at memory address 0x0001 and num2 is at memory address 0x0002.

b. Copy your pointer diagram from part(a). Now modify it to show the effect of executing lines 4 through 6.

Question 7: Line by line, character by character (ifstream)

Write a function numLines whose parameters are a filename and a character, that prints out the number of lines in the file that start with the character passed in. If we have a file “sample1.txt” with contents:

Apple 
pen
align
Store
Alias
student A

Calling numLines("sample1.txt", 'A') should print 2 in the terminal. You can assume that the <fstream> library has been included.

Question 8: Pointers / References (and which variables change after function call)

Consider this trickyFunction and a short program that calls it:

void trickyFunction(int* a, int* b, int& c, int d) {
    *a = *a + 1;
    b = b + 1;
    c = c + 1;
    d = d + 1;
}

int main() {
    int w = 10, x = 10, y = 10, z = 10;
    trickyFunction(&w, &x, y, z);
    cout << w << ,  << x << ,  <<  y  <<,  <<  z <<endl;
    return 0;
}

Question 9: Robotic Number Conversions

A Cyborg-Robot is taking a test. After taking the test, the Robot receives the score of ‘0xAC3’. Unfortunately, for our robot friend, they can only read in binary. What is ‘0xAC3’ in binary?

Suppose the Cyborg-Robot uses quantum computing, meaning that they use ternary values (base 3). Our Cyborg-Robot now sees that they got ‘10121’ in their base 3 system. What is ‘10121’ base 3 in decimal?

Question 10: Structs and Pointers

A pet will be represented by the following struct:

struct Pet{
    string name;    // name of pet
    string species; // ex: dog, cat, etc.
    double weight;  // weight of pet
};

Implement the two functions below.

nameOfHeavierPet() will take two pointers to Pet objects as input and print the name of the pet that weighs more. If either of the pointers are null, print "invalid Pet" and exit. If both pets weigh the same, print "same weight".

void nameOfHeavierPet(Pet *p1, Pet *p2);

numCats() will take in an array of Pet and the array size. Count the number of Pet objects where species = “cat”. Return the count.

int numCats(Pet pets[], int length);

For example, let’s pretend we have an array pets like so:

Pet pets[] = { {"Buddy", "dog", 34.5}, {"Snowball", "cat", 10.2}, {"Oreo", "cat", 8.7} };
cout << numCats(pets, 3); // should print 2

Question 11: Array iteration with for-loops

Write the implementation of a function ‘getSmallestOdd’ that takes two arguments: an integer array and the length of that array. Your function should find and return the lowest odd number in the array. If there are no odd numbers in the array then return -1. You may assume the array does not contain negative numbers. Remember to account for an empty array.

Question 12: Arrays in memory

Consider the code given below. Assume that the array nums is created at the location 0x8000, which means the address of nums[0] is 0x8000. Also assume that an integer takes up 4 bytes, so the memory location of the next element would be 4 bytes greater than the starting address.

void arrStuff (int x[], int len)
{
    cout << x << ,  << *x << ,  << x+1<< ,  << *(x+1) << endl;
    *x = *x+1;
}

int main(){
  const int VAL=2;
  int nums[ ] = {40,10,-60,25};
  arrStuff(nums, 4);
  for(int i=0; i< VAL; i++){
    cout<<nums[i]<< ;
  }
  return 0;
}

a) Draw a pointer diagram that shows all the variables in memory when the function arrStuff is called and only the first line has been executed. Your pointer diagram should show the nums array, the arguments of arrStuff() and any relationships between them.

b) What is printed to standard output when the program is executed? You may represent each value that is printed in hex or decimal notation as convenient. You must include the output produced by the cout statements in arrStuff() and main()

Question 13: Structs and functions

Consider the following struct definitions:

struct Point{ 
    double x;
    double y;
};
struct Box{ 
    Point ul; // upper left corner of the Box double width; //width of the Box 
    double height; //height of the Box 
}; 

The following function is designed to initialize the member variables of a Box object.

void initBox(Box* p, double x, double y, double width, double height);

Consider the following code:

Box b1;
Box &b2 = b1;
Box* b3 = new Box;

Using the function definition from above, state whether each of the following lines of code results in a compilation error or not. Write RE (for run-time error), CE (for compile-time error) or NE (for No Error).

(a) initBox(b1, 10.0, 20.0, 2, 4); 
(b) initBox(*b1, 10.0, 20.0, 2, 4); 
(c) initBox(&b1, 10.0, 20.0, 2, 4); 
(d) initBox(b2, 10.0, 20.0, 2, 4); 
(e) initBox(&b2, 10.0, 20.0, 2, 4); 
(f) initBox(b3, 10.0, 20.0, 2, 4); 
(g) initBox(&b3, 10.0, 20.0, 2, 4);

Question N: Reading from a file

filestream.cpp
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    ifstream ins;
    string nextline;
    string filename = "students.txt";

    ins.open(filename);
    if (ins.fail())
    {
        cerr << "Unable to open the file " << filename << endl;
        return -1;
    }

    while (!ins.eof()) {
        ins >> nextline;
        cout << nextline << endl;
    }
    ins.close();

    return 0;
}

The input file students.txt contains:

   Arthur
   Jaqui
   Surya

What is the output of running the above program? (Try running it yourself.)


Make sure to look at the example problems that we did on the quizzes as well as the code that was shown in lectures. Please be sure to review the code from lecture, which can be found in the lecture notes (different from lecture slides).