C: Distance between two points

Use a struct to hold a point.

What to build

A struct, and a function that takes two of them.

Requirements

  • Define a type Point with int fields x and y.
  • Write int dist2(Point a, Point b), returning the squared distance.
  • Read two points and print the result.

Input

One line with four whole numbers: x1 y1 x2 y2.

Output

One number.

Constraints

Each number is from -1000 to 1000.

Example

Input:

0 0 3 4

Output:

25

Why it works

With a struct, each point travels as one value, so the function needs two parameters instead of four.

Examples

Example 1 · Input
0 0 3 4
Expected output
25
Example 2 · Input
1 1 1 1
Expected output
0

Hints

Hint 1

Define a struct with x and y, using typedef.

Hint 2

Write dist2 taking two Point values.

Hint 3

Work with the squared distance, so that no square root is needed.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

typedef struct {
    int x, y;
} Point;

int dist2(Point a, Point b) {
    int dx = a.x - b.x;
    int dy = a.y - b.y;
    return dx * dx + dy * dy;
}

int main(void) {
    Point a, b;
    scanf("%d %d %d %d", &a.x, &a.y, &b.x, &b.y);
    printf("%d\n", dist2(a, b));
    return 0;
}

Lesson: Structures →