Write a C program to calculate the distance between the two points.

Previous
Next

Note: x1, y1, x2, y2 are all double values.

Approach-1:

  • In this approach, we read values of x1, x2, x3, x4 and calculated the distance between those points.
  • Remember the points must be of double type as mentioned in the problem statement.
#include <stdio.h>
#include <math.h>
int main() 
{
	double x1, y1, x2, y2, d;
	printf("Input x1: ");
	scanf("%lf", &x1);
	printf("Input y1: ");
	scanf("%lf", &y1);
 	printf("Input x2: ");
	scanf("%lf", &x2);
	printf("Input y2: ");
	scanf("%lf", &y2);
	d = ((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1));
	printf("Distance between the points: %.4lf\n", sqrt(d));
	return 0;
}

Approach-2:

  • In this approach, we define the custom function along with the main() function.
  • We read the values of two points in main() function and pass to custom function called distance().
  • We display the distance in the called function itself after calculation.
#include<stdio.h>
#include<math.h>
void distance(double, double, double, double);
int main() 
{
double x1 = 4;
double y1 = 9;
double x2 = 5;
double y2 = 10;
distance(x1, y1, x2, y2);
return 0;
}
void distance(double x1, double y1, double x2, double y2) 
{
double d = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
printf("Distance between 2 points are : %lf\n", d);
return;
}
Previous
Next

Courses Enquiry Form