C Program to Calculate Slope and Midpoint of a given Line Segment

Before going to the program first let us see what is Slope and Midpoint of a Line and how to calculate it?

Slope of a Line:

                   The Slope of a Line is a number that describes both the direction and the steepness of the line.

Midpoint of a Line:

                   The Midpoint of a Line is the middle point of a line segment. It is equidistant from both endpoints.

To calculate we should know the formulas.

So the formulas are:

slop

Program code to Calculate Slope and Midpoint of a Line in C:

#include<stdio.h>
#include<conio.h>

void main()
{
    float x1,x2,y1,y2,slope,midX,midY;
    clrscr();
    
    printf(" Enter the X Coordinate of Endpoint 1: ");
    scanf("%f",&x1);
    printf(" Enter the Y Coordinate of Endpoint 1: ");
    scanf("%f",&y1);
    
    printf(" Enter the X Coordinate of Endpoint 2: ");
    scanf("%f",&x2);
    printf(" Enter the Y Coordinate of Endpoint 2: ");
    scanf("%f",&y2);
    
    printf(" The Endpoints of a Line are : (%.2f,%.2f) and (%.2f,%.2f)",x1,y1,x2,y2);
    
    slope=(y2-y1)/(x2-x1);
    
    midX=(x1+x2)/2;
    midY=(y1+y2)/2;
    
    printf(" Slope : %.2f",slope);
    printf(" Midpoint : (%.2f,%.2f)",midX,midY);
    getch();
}

Explanation:

  • First the computer reads the X and Y Coordinate of the Endpoint 1 from the user and stores it in the “x1” and “y1” variables respectively using the following lines:
printf(" Enter the X Coordinate of Endpoint 1: ");
scanf("%f",&x1);
printf(" Enter the Y Coordinate of Endpoint 1: ");
scanf("%f",&y1);

 Note: %f is used to read the floating-point value.

  • Then the computer reads the X and Y Coordinate of the Endpoint 2 from the user and stores it in the “x2” and “y2” variables respectively using the following lines:
printf(" Enter the X Coordinate of Endpoint 2: ");
scanf("%f",&x2);
printf(" Enter the Y Coordinate of Endpoint 2: ");
scanf("%f",&y2);
  • Then using the formulas the Slope and Midpoint of a Line is calculated and stored in the “slope” and “midX”, “midY” variables respectively using the following lines:
slope=(y2-y1)/(x2-x1);

midX=(x1+x2)/2;
midY=(y1+y2)/2;
  • Finally the Slope and Midpoint of a Line is printed on the screen using the following lines:
printf(" Slope : %.2f",slope);
printf(" Midpoint : (%.2f,%.2f)",midX,midY);

Note: %.2f is used to print the floating-point value with only 2 decimal places.

Output:

midpoint

TO DOWNLOAD THE PROGRAM CODE : CLICK HERE

 

Leave a Reply

Your email address will not be published. Required fields are marked *