Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C program to calculate distance between two points
Given with the two points coordinates and the task is to find the distance between two points and display the result.
In a two dimension plane there are two points let’s say A and B with the respective coordinates as (x1, y1) and (x2, y2) and to calculate the distance between them there is a direct formula which is given below
$$\sqrt{\lgroup x2-x1\rgroup^{2}+\lgroup y2-y1\rgroup^{2}}$$
Given below is the diagram representing two points and their differences
$$\frac{(x_2-x_1)}{(x_1,y_1)\:\:\:\:\:\:(y_2-y_1)\:\:\:\:\:\:(x_2,y_2)}$$
Approach used below is as follows −
- Input the coordinates as x1, x2, y1 and y2
- Apply the formula to compute the difference between two points
- Print the distance
Algorithm
Start Step 1-> declare function to calculate distance between two point void three_dis(float x1, float y1, float x2, float y2) set float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0) print dis step 2-> In main() Set float x1 = 4 Set float y1 = 9 Set float x2 = 5 Set float y2 = 10 Call two_dis(x1, y1, x2, y2) Stop
Example
#include <stdio.h>
#include<math.h>
//function to find distance bewteen 2 points
void two_dis(float x1, float y1, float x2, float y2) {
float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0);
printf("Distance between 2 points are : %f", dis);
return;
}
int main() {
float x1 = 4;
float y1 = 9;
float x2 = 5;
float y2 = 10;
two_dis(x1, y1, x2, y2);
return 0;
}
Output
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
Distance between 2 points are : 1.414214
Advertisements