- How to use the Pythagorean theorem with two point structs
- How to reach into both points with the dot operator to get dx and dy
- Why you need
#include <math.h>forsqrt - Why the link step may need
-lmon Linux - Why the distance is never negative β and how the formula handles that for you
Pythagoras on the plane
To find the distance between two points, draw a right triangle between them. The horizontal side is how far apart they are in x, the vertical side is how far apart they are in y, and the distance is the hypotenuse. That's the Pythagorean theorem: distanceΒ² = dxΒ² + dyΒ², so distance = β(dxΒ² + dyΒ²).
With structs, this reads naturally. If you have struct point a and struct point b, then dx = b.x - a.x and dy = b.y - a.y. Square them, add them, take the square root. That's the whole program. The struct gives you a clean way to hold both points together, and the dot operator gives you the x and y you need.
A couple of small things to watch. First, the distance is always non-negative, and the formula gives that automatically because you square the differences before adding them β the sign of dx or dy doesn't matter. Second, sqrt lives in math.h, and on Linux you may need to add -lm to the compile command to pull in the math library. On macOS and Windows, that's usually automatic. Third, the result is a double, because sqrt returns double β even if the inputs are floats, the return value is a double, and that's fine.
π‘ In one line: sqrt((b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)). That's the whole distance formula.
The formula, step by step
Breaking the formula into four small steps makes it easier to check and debug:
- Work out
dx = b.x - a.x. - Work out
dy = b.y - a.y. - Square each one and add:
dx*dx + dy*dy. - Take the square root:
sqrt(dx*dx + dy*dy).
You can write it in one line if you like, but the four-step form is easier to follow when you're reading the code later. And it's easier to debug if the answer comes out wrong β you can print dx and dy and check them against what you expect.
| Point A | Point B | dx | dy | Distance |
|---|---|---|---|---|
| (0, 0) | (3, 4) | 3 | 4 | 5.00 |
| (0, 0) | (1, 1) | 1 | 1 | 1.41 |
| (2.5, 3.1) | (-1.0, 4.5) | -3.5 | 1.4 | 3.77 |
| (2, 2) | (2, 2) | 0 | 0 | 0.00 |
| (-3, -4) | (0, 0) | 3 | 4 | 5.00 |
The first row is the famous 3-4-5 triangle β that's a good one for checking your work because you know the answer before you run the program. The last row shows that the sign of dx and dy doesn't matter: squaring makes them positive anyway. The fourth row is the case where the two points are the same β the distance is 0.
Complete C Program
Program: distance between two points
#include <stdio.h>
#include <math.h>
struct point {
float x;
float y;
};
int main(void) {
struct point a = {2.5f, 3.1f};
struct point b = {-1.0f, 4.5f};
float dx = b.x - a.x;
float dy = b.y - a.y;
double distance = sqrt(dx * dx + dy * dy);
printf("Point A : (%.2f, %.2f)\n", a.x, a.y);
printf("Point B : (%.2f, %.2f)\n", b.x, b.y);
printf("Distance : %.2f\n", distance);
return 0;
}
And here's a version that reads both points from the user. It's a bit longer, but it's what you'd actually write if you wanted to test more than one pair of points:
Variant: read both points from the user
#include <stdio.h>
#include <math.h>
struct point {
float x;
float y;
};
int main(void) {
struct point a, b;
printf("Enter x and y of point A: ");
scanf("%f %f", &a.x, &a.y);
printf("Enter x and y of point B: ");
scanf("%f %f", &b.x, &b.y);
float dx = b.x - a.x;
float dy = b.y - a.y;
double distance = sqrt(dx * dx + dy * dy);
printf("A = (%.2f, %.2f)\n", a.x, a.y);
printf("B = (%.2f, %.2f)\n", b.x, b.y);
printf("Distance = %.2f\n", distance);
return 0;
}
The two versions compute the distance in exactly the same way. The only difference is where the points come from β hardcoded in the first version, read from the user in the second. That's the usual pattern: start with fixed values so you can check the formula, then switch to user input once you trust it.
One note on compiling: on Linux, you may need to add -lm when you build, like gcc distance.c -o distance -lm. Without it, the linker complains that sqrt is undefined, because sqrt lives in the math library, which isn't linked by default. On macOS and Windows with most compilers, you don't need the flag β but if you see a link error about sqrt, that's the fix.
Program Output
Point A : (2.50, 3.10)
Point B : (-1.00, 4.50)
Distance : 3.77
And for the user-input version, with the 3-4-5 test:
Enter x and y of point A: 0 0
Enter x and y of point B: 3 4
A = (0.00, 0.00)
B = (3.00, 4.00)
Distance = 5.00
Try the 3-4-5 case first β that's the easiest one to check by hand because 3Β² + 4Β² = 5Β². If your program gives 5.00, the formula is right. Then try points at the same spot β the distance should be 0.00. Try a horizontal pair like (0, 0) and (7, 0) β that should give 7.00. Try a vertical pair like (0, 0) and (0, 5) β that should give 5.00.
Step-by-Step Explanation
Let's walk through the calculation for A = (2.5, 3.1) and B = (-1.0, 4.5).
1. The two points
struct point a = {2.5f, 3.1f}; and struct point b = {-1.0f, 4.5f}; declare two points with the coordinates we want. The f after each number says "float", not "double". Both are perfectly fine as struct point values with the fields already filled in.
2. The differences
float dx = b.x - a.x; gives -1.0 - 2.5 = -3.5. float dy = b.y - a.y; gives 4.5 - 3.1 = 1.4. These are the two legs of the right triangle. Their signs don't matter for the distance β we're about to square them, which removes the sign.
3. The formula
sqrt(dx * dx + dy * dy) computes sqrt((-3.5)Β² + (1.4)Β²) = sqrt(12.25 + 1.96) = sqrt(14.21) β 3.769. Printed with %.2f, that's 3.77. If you wanted more digits, you'd use %.4f and see 3.7695. For most geometry problems, two decimal places are enough.
4. The math.h include
#include <math.h> at the top pulls in the declaration of sqrt. Without it, the compiler assumes sqrt returns an int and takes int arguments β which would silently truncate your coordinates and give wildly wrong answers. In modern C (C99 and later), using sqrt without the include is a warning or an error. So always include math.h.
5. Why double, not float, for distance
sqrt returns a double, not a float, because it's designed for higher precision. You could store the result in a float (the compiler would convert it down), but there's no reason to β a double holds more digits, and the extra 4 bytes don't matter here. Keeping the result as double also means you don't have to worry about a small rounding error creeping in.
6. The -lm flag
On Linux, the C math library is a separate file that isn't linked by default. If you compile with gcc distance.c -o distance, you may see an error like undefined reference to 'sqrt'. The fix is gcc distance.c -o distance -lm β the -lm tells the linker to include the math library. macOS and Windows handle this automatically with most toolchains, so you may not see the error there. But it's a common gotcha on Linux, so worth knowing.
7. Why this assignment matters
This is the first assignment where the struct is actually used for a computation, not just for storage. Up to now, we've been filling structs and printing them. Here, we reach into two structs at once, do arithmetic on their members, and get a meaningful result. That's the real purpose of structs β they let you write functions like distance(a, b) that work on complete records. Every geometry, graphics, or simulation program you'll see in C does exactly this.
π― Remember this: dx = b.x - a.x, dy = b.y - a.y, distance = sqrt(dx*dx + dy*dy). Include <math.h>. On Linux, link with -lm. Test with the 3-4-5 triangle: (0,0) to (3,4) should give 5.00.
Frequently Asked Questions
1. Why do I get "undefined reference to 'sqrt'" when I compile?
You're on Linux and forgot the -lm flag. The math library is separate from the standard C library, and the linker needs to be told about it. Compile with gcc distance.c -o distance -lm and the error goes away. On macOS and Windows, this is usually automatic and you won't see the error.
2. Why is the distance always positive?
Because we square dx and dy before adding them. Squares are always non-negative, so the sum inside the square root is non-negative, and sqrt of a non-negative number is non-negative. The sign of dx or dy doesn't matter β the formula handles it for you.
3. Can I use hypot instead of writing the formula?
Yes β hypot(dx, dy) computes sqrt(dx*dx + dy*dy) directly, and it's a bit safer because it avoids overflow when dx or dy are very large. It's also in math.h. For this assignment, writing the formula is fine and clearer. But hypot is worth knowing if you ever work with very large coordinates.
4. Why does my answer come out as an integer?
Probably because you're printing with %d instead of %.2f. The distance is a double with a fractional part; using %d makes printf read the wrong bits and print garbage. Use %f or %.2f for the distance. Same rule as with any other floating-point value.
5. What happens if both points are the same?
The distance is 0. dx and dy are both 0, so sqrt(0 + 0) = sqrt(0) = 0. That's correct β a point is zero distance from itself. This is a good test case to check your formula: (2, 2) and (2, 2) should give 0.00. If it doesn't, something's wrong.
6. How would I compute the distance between many pairs of points?
Wrap the whole calculation in a loop over two arrays of points. For example, for (int i = 0; i < n; i++) { distance = ...; } where the points come from pts1[i] and pts2[i]. The formula doesn't change β only where the points come from. If you want all pairwise distances, you'd need a nested loop, but that's a bigger problem than this assignment.
π‘ Tip: After this, try computing the midpoint between the two points: ((a.x + b.x) / 2, (a.y + b.y) / 2). Same struct, same field access, just different arithmetic. Then try checking whether three points are collinear β that uses a determinant formula, but the struct handling is the same. Every geometry problem you can think of starts with these little operations on points.