8.13. Multiple Choice ExercisesΒΆ

Q1

Which of the following are compound values?

struct student {
  string first_name, last_name;
  int year;
  double gpa;
};

struct professor {
  string first_name, last_name;
  string department;
  int class;
};

int main() {
  student x = { "John", "Doe", 2, 3.46 };
  student y = { "Jane", "Doe", 3, 3.68 };
  professor z = { "Richard", "Roe", "Computer Science", 101 };
  string college = "University of College";
  int student_pop = 3400;
  double avg_gpa = 3.2;
}

Q2

What is wrong with the following struct definition?

struct chicken {
  string name;
  int num_legs;
  int eggs;
  bool eggs;
}

Q3

How do we assign the value of 4 to the instance variable num_legs of the dog object?

 struct dog {
   string name;
   int num_legs;
   bool is_panting;
 };

int main() {
  dog fido = { "Fido", 0, true };
}

Q4

What is the output of the code below?

struct cube {
  int edge_length;
  int volume;
  int mass;
};

int main() {
  cube c;
  c.edge_length = 4;
  c.volume = 64;
  c.mass = 128;
  cout << c.edge_length << ", " << c.volume << ", " << c.mass << ", ";
  int density = c.mass / c.volume;
  cout << density;
}

Q5

What is the output of the code below?

struct cube {
  int edge_length;
  int volume;
  int mass;
};

int calculate_density (cube c) {
  return c.mass / c.volume;
}

int main() {
  cube c = { 2, 8, 4 };
  int density = calculate_density (c);
  cout << density;
}

Q6

What is the value of s.coffee_cup_full when the code is done running?

struct student {
  string name;
  bool is_sleepy;
  bool coffee_cup_full;
};

void pour_coffee (student s) {
  s.coffee_cup_full = true;
}

int main() {
  student s = { "Thor Odinson", true, false };
  if (s.is_sleepy) {
    pour_coffee (s);
  }
}

Q7

What is the value of r.battery_level_percentage when the code is done running?

struct robot {
  string name;
  int battery_level_percentage;
  bool is_fully_charged;
};

void charge_robot (robot& r) {
  if (r.battery_level_percentage + 50 > 100) {
    r.battery_level_percentage = 100;
    r.is_fully_charged = true;
  }
  else {
    r.battery_level_percentage = r.battery_level_percentage + 50;
  }
}

int main() {
  robot r = { "Rob", 60, false };
  charge_robot (r);
}

Q8

What is the output of the code below?

void foo (int& x, int y) {
  x = x + 4;
  y = 2 * x + 3 * y;
}

void bar (int x, int y) {
  y = 2 * x;
  x = x - 1;
  foo (x, x);
}

void func (int &x, int& y) {
  x = x + 3;
  bar (y, x);
}

int main() {
  int x = 4;
  int y = 7;
  func (y, x);
  cout << x << ", " << y;
}

Q9

If the user inputted the string "R2-D2", what is the output of the code below?

int main() {
  string name;
  cin >> name;
  cout << "Hello, " << name << '!';
}

Q10

If the user inputted the string "C-3PO", what is the output of the code below?

int main() {
  char name;
  cin >> name;
  cout << "Hello, " << name << '!';
}