LearnFrenzy
Sign in Take a free test

Structures, Unions, Enums · Structure Programs · Question 2

Distance between two points using a structure in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Represent a point as a structure and write a function that returns the distance between two points.

Solution
main.c
#include <math.h>
#include <stdio.h>

struct point {
    double x, y;
};

double distance(struct point a, struct point b) {
    return hypot(b.x - a.x, b.y - a.y);     /* sqrt(dx*dx + dy*dy), without overflow */
}

int main(void) {
    struct point p = {1, 2}, q = {4, 6};
    printf("distance = %.2f\n", distance(p, q));
    return 0;
}

Output Verified by compiling and running

distance = 5.00

dx = 3 and dy = 4, so the distance is 5. hypot() from <math.h> computes √(dx² + dy²) without overflowing for large values. On Linux, link with -lm.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links