/* This program reads in the x and y coordinates of NUM_POINTS points from a file points.dat. If then computes the length of the connect-the-dot path from point 0 to point 1 to ... point NUM_POINTS - 1. */ #include #include #include const int NUM_POINTS = 10; double line_seg_length (double, double, double, double); double path_length(double[], double[]); void main(){ ifstream infile("points.dat"); double x[NUM_POINTS], y[NUM_POINTS]; for (int i = 0; i< NUM_POINTS; i++) infile >> x[i] >> y[i]; cout << "The length of the connect-the-dots path starting at\npoint 0" << " and ending at point " << NUM_POINTS - 1 << " is " << path_length(x,y) << ".\n"; } double line_seg_length (double x1, double y1, double x2, double y2){ return sqrt(pow(x2-x1,2) + pow(y2-y1,2)); } /* Remember there are NUM_POINTS points, but only NUM_POINTS - 1 line segments to compute the length of. This is reflected in the loop below (see how the alternate version commented out below it differs). */ double path_length (double x[], double y[]){ double length = 0; for (int i=0; i < NUM_POINTS - 1; i++) length += line_seg_length(x[i], y[i], x[i+1], y[i+1]); /* the previous loop is equivalent to ... for (int i=1; i < NUM_POINTS; i++) length += line_seg_length(x[i-1], y[i-1], x[i], y[i]); */ return length; }