C program to find the Euclidean distance between two points
Last Updated :
28 Feb, 2024
Given four integers x1, y1, x2 and y2, which represents two coordinates (x1, y1) and (x2, y2) of a two-dimensional graph. The task is to find the Euclidean distance between these two points.
Euclidean distance between two points is the length of a straight line drawn between those two given points.
Examples:Â
Input: x1, y1 = (3, 4)
      x2, y2 = (7, 7)
Output: 5
Input: x1, y1 = (3, 4)
      x2, y2 = (4, 3)
Output: 1.41421
Approach: Since the Euclidean distance is nothing but the straight line distance between two given points, therefore the distance formula derived from the Pythagorean theorem can be used. The formula for distance between two points (x1, y1) and (x2, y2) is [Tex]\sqrt{(x2-x1)^{2} + (y2-y1)^{2}}[/Tex]
We can get the above formula by simply applying the Pythagoras theoremÂ
 Below is the implementation of the above approach
C
#include <math.h>
#include <stdio.h>
float distance( int x1, int y1, int x2, int y2)
{
return sqrt ( pow (x2 - x1, 2)
+ pow (y2 - y1, 2) * 1.0);
}
int main()
{
printf ( "%.2f" , distance(3, 4, 4, 3));
return 0;
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...