C program to calculate distance between two points

Given two points with coordinates, we need to calculate the distance between them. In a two-dimensional plane, if we have points A and B with coordinates (x1, y1) and (x2, y2) respectively, we can find the distance using the Euclidean distance formula.

Syntax

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

Distance Formula

The distance between two points is calculated using the formula −

A(x1,y1) B(x2,y2) distance (x2-x1) (y2-y1) X Y

Algorithm

  • Input the coordinates as x1, y1, x2, and y2
  • Apply the distance formula: sqrt((x2-x1)² + (y2-y1)²)
  • Display the calculated distance

Example

Here's a complete C program to calculate the distance between two points −

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

// Function to calculate distance between two points
void calculateDistance(float x1, float y1, float x2, float y2) {
    float distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
    printf("Distance between points (%.1f, %.1f) and (%.1f, %.1f) is: %.6f<br>", 
           x1, y1, x2, y2, distance);
}

int main() {
    float x1 = 4.0, y1 = 9.0;
    float x2 = 5.0, y2 = 10.0;
    
    calculateDistance(x1, y1, x2, y2);
    
    return 0;
}
Distance between points (4.0, 9.0) and (5.0, 10.0) is: 1.414214

How It Works

The program uses the sqrt() function from math.h library and pow() function to calculate the square root and power respectively. The distance formula is implemented as sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)).

Note: To compile this program, you may need to link the math library using -lm flag in some systems: gcc program.c -lm

Conclusion

The distance between two points can be easily calculated using the Euclidean distance formula. This fundamental geometric calculation is widely used in computer graphics, game development, and scientific applications.

Updated on: 2026-03-15T12:15:15+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements