C program to calculate distance between three points in 3D

In C programming, calculating the distance between two points in 3D space is a common geometric problem. The distance between two points in three-dimensional space can be calculated using the Euclidean distance formula.

Syntax

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

Where (x1, y1, z1) and (x2, y2, z2) are the coordinates of the two points in 3D space.

Formula

The mathematical formula for calculating distance between two points in 3D space is −

Distance = ?[(x2-x1)² + (y2-y1)² + (z2-z1)²]

X Y Z P1(x1,y1,z1) P2(x2,y2,z2) Distance

Example

Here's a complete C program to calculate the distance between two points in 3D space −

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

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

int main() {
    float x1 = 4.0, y1 = 9.0, z1 = -3.0;
    float x2 = 5.0, y2 = 10.0, z2 = 9.0;
    
    printf("Calculating 3D distance between two points:<br>");
    calculateDistance(x1, y1, z1, x2, y2, z2);
    
    return 0;
}
Calculating 3D distance between two points:
Distance between points (4.0, 9.0, -3.0) and (5.0, 10.0, 9.0) is: 12.083046

Key Points

  • The sqrt() function requires including the math.h header file
  • The pow() function is used to calculate the square of differences
  • The formula works for any two points in 3D coordinate system
  • Use appropriate data types (float or double) for precise calculations

Conclusion

Calculating 3D distance in C involves applying the Euclidean distance formula using the sqrt() and pow() functions from the math library. This fundamental geometric calculation is essential in many applications including computer graphics, physics simulations, and spatial analysis.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements