C Program to Calculate Distance Between Two Points

The program uses the distance formula to calculate the distance between two points in C.

To find the distance between two coordinates, we have a formula named distance formula. In this article, we will be using this where we perform subtraction first (X2 from X1 & Y2 from Y1 ) and then calculate their squares.

After getting squared values, we do add operation and find their square roots to get the distance between between the points.

Distance formula: distance formula

C Program to Calculate Distance Between Two Points

Program:

#include<stdio.h>
#include<math.h>
int main(){
    int x1, y1, x2, y2;
    double  dis,diff1,diff2;
       printf("**********************------------------------*************************\n\n ");
 printf("Please Enter  the value of initial coordinates (x,y)\n");
 scanf("%d",&x1);
  scanf("%d",&y1);
 printf("\nPlease Enter  the value of initial coordinates (x1,y1) \n");
 scanf("%d",&x2);
 scanf("%d",&y2);
 diff1=x1-x2;
 diff2=y1-y2;
 diff1=pow(diff1,2);
 diff2=pow(diff2,2);
 dis=sqrt(diff1+diff2);
 printf("\n Distance of the line = %.2f\n",dis);
 return 0;
    }

Output:

*********************------------------------*************************

 Please Enter  the value of initial coordinates (x,y)
4
6

Please Enter  the value of initial coordinates (x1,y1) 
2
3

 Distance of the line = 3.61

Explanation :

  1. Get values two coordinates as an input from the user
  2. calculate difference between x2 and x1 & y2 and y1
  3. Now, perform square operations on both x and y coordinates
  4. Further, add both x and y squared values and find square root of the result
  5. Lastly, printed the distance on output screen

Leave a Reply