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 methods for calculating the distance between two points in a 2D or 3D space. It is derived from the Pythagorean theorem and is used widely in mathematics, physics, computer science, and various real-world applications like machine learning and robotics.

This program demonstrates how to calculate the Euclidean distance between two points in a 2D space using the C programming language.


Formula

The Euclidean distance between two points, (x1, y1) and (x2, y2), in a 2D plane is calculated using the formula:

distance = sqrt((x2 - x1)² + (y2 - y1)²)

Here, sqrt represents the square root function. The formula calculates the length of the straight line that connects the two points.

Steps to calculate:

  • Find the differences between the x-coordinates and y-coordinates: x2 - x1 and y2 - y1.
  • Square both differences.
  • Add the squared values.
  • Take the square root of the sum to get the distance.

Code

The following is the C program to compute the Euclidean distance:

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

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

    // Input coordinates of the first point
    printf("Enter x1 and y1: ");
    scanf("%f %f", &x1, &y1);

    // Input coordinates of the second point
    printf("Enter x2 and y2: ");
    scanf("%f %f", &x2, &y2);

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

    // Output the result
    printf("Euclidean Distance = %.2f\\n", distance);

    return 0;
}
        

Output

Here is an example of how the program runs:

Enter x1 and y1: 1 2
Enter x2 and y2: 4 6
Euclidean Distance = 5.00
        

In this example, the points are (1, 2) and (4, 6). The calculated distance between these points is 5.00.


Explanation

The program works as follows:

  • Input: The user is prompted to enter the coordinates of two points. These values are read using the scanf function.
  • Calculation:
    • The differences between the x-coordinates and y-coordinates are calculated.
    • These differences are squared using the pow function.
    • The sum of the squared values is computed.
    • The square root of the sum is calculated using the sqrt function to get the Euclidean distance.
  • Output: The calculated distance is displayed with two decimal places using the printf function.

The use of functions like pow and sqrt from the math.h library makes the program efficient and concise. Additionally, the program ensures flexibility by allowing the user to input any valid floating-point coordinates.