8.5. Structures as parameters

You can pass structures as parameters in the usual way. For example,

void print_point (point p) {
  cout << '(' << p.x << ", " << p.y << ')' << '\n';
}

print_point takes a point as an argument and outputs it in the standard format. If you call print_point (blank), it will output (3, 4).

The active code below uses the print_point function. Run the code to see the output!

Example structures_parameters_AC_1
 1#include <iostream>
 2using namespace std;
 3
 4struct point {
 5    double x, y;
 6};
 7
 8void print_point (point p) {
 9    cout << '(' << p.x << ", " << p.y << ')' << '\n';
10}
11
12int main() {
13    point blank = { 3.0, 4.0 };
14    print_point (blank);
15}

As a second example, we can rewrite the distance function from Section [distance] so that it takes two points as parameters instead of four doubles.

double distance (point p1, point p2) {
  double dx = p2.x - p1.x;
  double dy = p2.y - p1.y;
  return sqrt (dx*dx + dy*dy);
}

Q1

The active code below uses the updated version of the distance function. Feel free to modify the code!

Example structures_parameters_AC_2
 1#include <iostream>
 2#include <cmath>
 3using namespace std;
 4
 5struct point {
 6    double x, y;
 7};
 8
 9double distance (point p1, point p2) {
10    double dx = p2.x - p1.x;
11    double dy = p2.y - p1.y;
12    return sqrt (dx*dx + dy*dy);
13}
14
15int main() {
16    point origin = { 0.0, 0.0 };
17    point point = { 3.0, 4.0 };
18    cout << "The distance from the point to the origin is " << distance (origin, point) << '\n';
19}

Q2

What will print?

struct coordinate {
  int x, y;
};

void print_opposite_coordinate (coordinate p) {
  cout << '(' << -p.y << ", " << -p.x << ')' << '\n';
}

int main() {
  coordinate coord = { 2, 7 };
  print_opposite_coordinate (coord);
}

Q3

Construct a function that takes in three point structures and prints the average of the x coordinates and the average of the y coordinates as a coordinate. Find the x average before the y average.

  1. cout << '(' << "avg_x" << ',' << "avg_y" << ')'; #distractor
  2. cout << '(' << avg_x << ',' << avg_y << ')';
  3. double avg_x = (p1.x + p2.x + p3.x)/3;
  4. double avg_y = (p1.y + p2.y + p3.y)/3;
  5. double avg_y = (y.p1 + y.p2 + y.p3)/3; #distractor
  6. void print_average_point(point p1, point p2, point p3) {
  7. }