C++ Program to Find Euclidean Distance

C++ Program to Find Euclidean Distance

C++ Program to Find Euclidean Distance


Introduction

The Euclidean distance is one of the most commonly used metrics in mathematics and computer science to measure the "straight-line" distance between two points in Euclidean space. It is widely used in various fields, including geometry, machine learning, and computer graphics.

This C++ program computes the Euclidean distance between two points in a 2D plane. By understanding and implementing this program, you can grasp the fundamentals of distance calculation and geometric computations in programming.


Formula

The Euclidean distance between two points P1(x1, y1) and P2(x2, y2) is given by the formula:

  • Distance = √((x2 - x1)2 + (y2 - y1)2)

This formula is derived from the Pythagorean theorem, which calculates the hypotenuse of a right triangle. The difference between the x-coordinates and y-coordinates represents the lengths of the two perpendicular sides.


Code

#include <iostream>
#include <cmath>

using namespace std;

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

    // Input the coordinates of the first point
    cout << "Enter the x-coordinate of the first point: ";
    cin >> x1;
    cout << "Enter the y-coordinate of the first point: ";
    cin >> y1;

    // Input the coordinates of the second point
    cout << "Enter the x-coordinate of the second point: ";
    cin >> x2;
    cout << "Enter the y-coordinate of the second point: ";
    cin >> y2;

    // Calculate the Euclidean distance
    distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));

    // Display the result
    cout << "The Euclidean distance between the two points is: " << distance << endl;

    return 0;
}
    

Output

When you run the program, it prompts you to enter the coordinates of two points. It then calculates and displays the Euclidean distance between them.

Example:

Enter the x-coordinate of the first point: 3
Enter the y-coordinate of the first point: 4
Enter the x-coordinate of the second point: 7
Enter the y-coordinate of the second point: 1
The Euclidean distance between the two points is: 5
    

Explanation

The program begins by taking the coordinates of two points as input from the user. These coordinates represent the x and y values of the two points in a 2D plane. It calculates the Euclidean distance using the formula:

  • distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));

Here, the differences x2 - x1 and y2 - y1 are squared using the pow function to compute their squares. These squared values are then summed, and the square root of the result is taken using the sqrt function to calculate the final distance.

For instance, given the points (3, 4) and (7, 1), the program computes:

  • x2 - x1 = 7 - 3 = 4
  • y2 - y1 = 1 - 4 = -3
  • distance = √(42 + (-3)2) = √(16 + 9) = √25 = 5

The calculated result is then displayed to the user.