C Program to Find the Distance Between Two Points

Program description:- Write a C program to find the distance between two given points.

The distance formula is derived from the Pythagorean theorem. To find the distance between two points (x1, y1) and (x2, y2), all that you need to do is use the coordinates of these ordered pairs and apply the formula.

Distance Formula

Assume we have two points M and N, with coordinates (x1, y1) and (x2, y2) respectively. Their distance can be represented as MN and it can be calculated as given below formula,

The first point (M):- (x1, y1)
Second point (N):- (x2, y2)
Distance (MN):- √((x2-x1)2 + (y2-y1)2)

Example:-
M = (4, 8)
N = (12, 14)
Then distance between M and N is, MN = √((12-4)2 + (14-8)2) = √(64 + 36) = √(100) = 10

#include<stdio.h>
#include<math.h>
int main()
{
   int x1, y1, x2, y2, x, y, distance;

   // take first point's coordinates
   printf("Enter coordinates of first point: ");
   scanf("%d %d",&x1, &y1);

   // take second point's coordinates
   printf("Enter coordinates of second point: ");
   scanf("%d %d",&x2, &y2);

   x = (x2-x1);
   y = (y2-y1);

   distance = sqrt(x*x + y*y);

   // display result
   printf("Distance = %d", distance);

   return 0;
}

The Output for different test cases are:-

Enter coordinates of first point: 0 0
Enter coordinates of second point: 6 8
Distance = 10

Enter coordinates of first point: 4 6
Enter coordinates of second point: 28 13
Distance = 25

Enter coordinates of first point: 4 8
Enter coordinates of second point: 12 14
Distance = 10

In this C program to find the distance between two points, to find the square root of a number we use a predefined function sqrt() which is defined in math.h library header file.

In this program, the x1 and x2 variables store the value of the x-axis of both points. Similarly, the y1 and y2 variables store the value of the y-axis of both points.

The difference of x-axis of both points is stored in the variable x and the difference of y-axis of both points is stored in the variable y.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Similar Basic C programming examples

Leave a Comment

Your email address will not be published. Required fields are marked *