Program 01: Euclidean Distance Calculation
Problem Statement:: A robot needs to find how far it must travel between two points on a 2D plane. Develop a C program to calculate the straight-line distance between the given coordinates.
Problem Description:
Input: Four floating-point numbers representing coordinates (x1, y1) and (x2, y2).
Output: The straight-line (Euclidean) distance formatted to two decimal places.
Constraints: Coordinates can be any valid floating-point numbers; the output must be non-negative.
Method: Utilize the Euclidean distance formula:
$d = \sqrt{(x_2-x_1)^2 + (y_2-y_1)^2}$.
Pgm Logic:
Start.
Input the coordinates of the first point (x1, y1).
Input the coordinates of the second point (x2, y2).
Compute the distance using the formula: sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)).
Display the calculated distance.
Stop.
Program Code:
// Purpose: To calculate the straight-line distance between two points on a 2D plane.
#include <stdio.h>
#include <math.h>
void main()
{
float x1, y1, x2, y2, distance;
printf("Enter x1 and y1 (coordinates of the first point): ");
scanf("%f %f", &x1, &y1);
printf("Enter x2 and y2 (coordinates of the second point): ");
scanf("%f %f", &x2, &y2);
distance = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
printf("The straight-line distance between the two points is: %.2f\n", distance);
}
Output:
Enter x1 and y1 (coordinates of the first point): 0 0
Enter x2 and y2 (coordinates of the second point): 3 4
The straight-line distance between the two points is: 5.00
RESULT: Thus the program has been executed and the output was verified.
Remarks: This program was compiled and run in the Code::Blocks IDE. It requires the <math.h> header for the sqrt function.
Program Explanation: The program reads two pairs of coordinates from the user. It then applies the Pythagorean theorem-based distance formula to find the gap between the points and displays the result with two-decimal precision.
For all 2026 published C Lab Program posts Index page: click here:
For all 2026 published articles list:click here:
…till the next post, bye-bye & take care
No comments:
Post a Comment