Structure Assignment 9 β€” Find the Distance Between Two Points Using a Structure
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Distance Between Two Points Using a Structure

πŸ“‘ On this page:
  • Pythagoras on the plane
  • The formula, step by step
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
πŸ“š In this program, you will learn:
  • 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> for sqrt
  • Why the link step may need -lm on 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.

A right triangle drawn between two points A and B on a coordinate plane. The horizontal side is labelled dx, the vertical side is labelled dy, and the hypotenuse is labelled distance.

The formula, step by step

Breaking the formula into four small steps makes it easier to check and debug:

  1. Work out dx = b.x - a.x.
  2. Work out dy = b.y - a.y.
  3. Square each one and add: dx*dx + dy*dy.
  4. 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)345.00
(0, 0)(1, 1)111.41
(2.5, 3.1)(-1.0, 4.5)-3.51.43.77
(2, 2)(2, 2)000.00
(-3, -4)(0, 0)345.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.

πŸ“– Related Tutorials

  • 7. Create a Structure to Represent a Point in 2D Space
  • 8. Initialize and Display the Coordinates of a Point Using a Structure
  • 10. Create a Structure to Represent a Rectangle
  • Structures and Functions
  • Accessing Structure Members
  • Array of Structures
  • Introduction to Structures in C
  • All 25 Structure Assignments

Previous Topic: -->> 8. Initialize and Display the Coordinates of a Point Using a Structure   ||   Next Topic: -->> 10. Create a Structure to Represent a Rectangle


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.