Index « Previous Next »

Question

Write a program to compute the distance of line whose staring and ending points A(x1, y1) and B(x2, y2) are input by user. Your program should also find the mid point of line.

Source Code

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

struct point
{
    float x;
    float y;
};

struct line
{
    struct point start;
    struct point end;
};

struct point midPoint(struct line);
float findDistance(struct line);

int main()
{
    struct point p;
    struct line myLine;
    float distance;

    printf("Enter x coordinate of starting point: ");
    scanf("%f", &myLine.start.x);
    printf("Enter y coordinate of starting point: ");
    scanf("%f", &myLine.start.y);
    printf("Enter x coordinate of ending point: ");
    scanf("%f", &myLine.end.x);
    printf("Enter y coordinate of ending point: ");
    scanf("%f", &myLine.end.y);

    p = midPoint(myLine);
    printf("\nThe midPoint of (%.2f,%.2f) & (%.2f,%.2f) is (%.2f,%.2f)\n",
        myLine.start.x, myLine.start.y, myLine.end.x, myLine.end.y, p.x,
        p.y);


    distance = findDistance(myLine);
    printf("The distance between (%.2f,%.2f) & (%.2f,%.2f) is %.2f\n",
        myLine.start.x, myLine.start.y, myLine.end.x, myLine.end.y, distance);

    return 0;
} 

struct point midPoint(struct line myLine)
{
    struct point temp;
    temp.x = (myLine.start.x + myLine.end.x) / 2.0;
    temp.y = (myLine.start.y + myLine.end.y) / 2.0;
    return temp;
} 

float findDistance(struct line myLine)
{
    float distance;
    distance = sqrt((myLine.start.x - myLine.end.x) * (myLine.start.x -
        myLine.end.x) + (myLine.start.y - myLine.end.y) * (myLine.start.y -
        myLine.end.y));

    return distance;
}

Output

Enter x coordinate of starting point: 10
Enter y coordinate of starting point: 15
Enter x coordinate of ending point: 20
Enter y coordinate of ending point: 30

The midPoint of (10.00,15.00) & (20.00,30.00) is (15.00,22.50)
The distance between (10.00,15.00) & (20.00,30.00) is 18.03