C Program To Calculate Distance Between Two Points

Given two points A(x1, y1) and B(x2, y2), find the distance between them.

Formula To Calculate Distance Between Two Points using Pythagorean theorem

distance = sqrt( (x2 – x1) * (x2 – x1) + (y2 – y1) * (y2 – y1) );

Note: sqrt() is a builtin method present in math.h header file.

Related Read:
Basic Arithmetic Operations In C

Expected Output for the Input

User Input:
Enter point 1 (x1, y1)
1
1
Enter point 2 (x2, y2)
9
9

Output:
Distance between (1.00, 1.00) and (9.00, 9.00) is 11.31

Video Tutorial: C Program To Calculate Distance Between Two Points


[youtube https://www.youtube.com/watch?v=e4R-VhXp_k4]

YouTube Link: https://www.youtube.com/watch?v=e4R-VhXp_k4 [Watch the Video In Full Screen.]

Source Code: C Program To Calculate Distance Between Two Points

#include<stdio.h>
#include<math.h>

int main()
{
    float x1, y1, x2, y2, distance;

    printf("Enter point 1 (x1, y1)\n");
    scanf("%f%f", &x1, &y1);

    printf("Enter point 2 (x2, y2)\n");
    scanf("%f%f", &x2, &y2);

    distance = sqrt( (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1) );

    printf("Distance between (%0.2f, %0.2f) and (%0.2f, %0.2f) is %0.2f\n", x1, y1, x2, y2, distance);

    return 0;
}

Output 1:
Enter point 1 (x1, y1)
0
0
Enter point 2 (x2, y2)
5
0
Distance between (0.00, 0.00) and (5.00, 0.00) is 5.00

Output 2:
Enter point 1 (x1, y1)
2
3
Enter point 2 (x2, y2)
10
8
Distance between (2.00, 3.00) and (10.00, 8.00) is 9.43

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert