C Program to Find the Distance Between Two Points

Howdy readers, today you will learn how to write a C program to find the distance between two points.

The distance β€˜d’ between two points (x1, y1) and (x2, y2) can be calculated using the following formula:

  • d = √[x2 – x1]2 + [y2 – y1]2

This is known as the distance formula.

This tutorial prompts the user to enter the coordinates of two points, and then calculate the distance between them using the distance formula.

So, without any delay, let’s begin this tutorial.

C Program to Find the Distance Between Two Points

C Program

// C Program to Find the Distance Between Two Points
#include <stdio.h>
#include <math.h>

int main(){
    float x1, y1, x2, y2, dist;
    
    // Taking input
    printf("Enter the coordinates of the first point: ");
    scanf("%f %f", &x1, &y1);
    printf("Enter the coordinates of the second point: ");
    scanf("%f %f", &x2, &y2);
    
    // Calculating distance
    dist = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
    
    // Display distance
    printf("The distance between the two given points is: %f", dist);
    
    return 0;
}

Output

Enter the coordinates of the first point: 9 5
Enter the coordinates of the second point: 13 27
The distance between the two given points is: 22.360680
C Program to Find the Distance Between Two Points

Explanation

    float x1, y1, x2, y2, dist;

In this program, we have declared five float data type variables named x1, y1, x2, y2 and dist.

    printf("Enter the coordinates of the first point: ");
    scanf("%f %f", &x1, &y1);
    printf("Enter the coordinates of the second point: ");
    scanf("%f %f", &x2, &y2);

Now, the user is asked to enter the coordinates of the first and the second point. The coordinates of the first point get stored in the x1 and y1 variables.

Whereas, the coordinates of the second point get stored in the x2 and y2 variables.

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

Now, we take the help of distance formula to calculate the distance between two points.

The sqrt() function is used to compute the square root of a number. It is defined in math.h header file.

The distance computed above using the distance formula gets stored in the dist variable.

    printf("Distance between two given points is: %f", dist);

At last, the distance computed between the two given points gets printed on the screen using the printf() function.

Conclusion

Today you learned how to write a C program to find the distance between two points.

If you have any queries related to the tutorial, comment down your questions in the comment section.

Thanks for reading.

Happy Coding!!

Also Read:

Leave a Comment