8.5. Structures as parameters

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

void printPoint (Point p) {
  cout << "(" << p.x << ", " << p.y << ")" << endl;
}

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

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

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

As a second example, we can rewrite the distance function from Section 5.2 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);
}

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

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.

You have attempted 1 of 5 activities on this page