Algorithm to Find the Slope of a Line Segment
- Input: Coordinates of the endpoints ((x1, y1)) and ((x2, y2)).
- Check if the line segment is vertical:
- If ( x1 = x2 ), the line is vertical, and the slope is undefined.
- Calculate the slope:
- ( \text{slope} = \frac{y2 – y1}{x2 – x1} )
- Determine the nature of the slope:
- If ( \text{slope} > 0 ), the slope is positive.
- If ( \text{slope} < 0 ), the slope is negative.
- If ( \text{slope} = 0 ), the slope is zero.
- Output: Whether the slope is positive, negative, zero, or undefined.
C Program to Find the Slope of a Line Segment
#include <stdio.h>
// Function to determine and print the nature of the slope
void findSlope(int x1, int y1, int x2, int y2) {
// Check if the line segment is vertical
if (x1 == x2) {
printf("The line is vertical; the slope is undefined.\n");
return;
}
// Calculate the slope
double slope = (double)(y2 - y1) / (x2 - x1);
// Determine the nature of the slope
if (slope > 0) {
printf("The slope is positive.\n");
} else if (slope < 0) {
printf("The slope is negative.\n");
} else {
printf("The slope is zero.\n");
}
}
int main() {
int x1, y1, x2, y2;
// Input coordinates of the endpoints
printf("Enter coordinates of the first point (x1 y1): ");
scanf("%d %d", &x1, &y1);
printf("Enter coordinates of the second point (x2 y2): ");
scanf("%d %d", &x2, &y2);
// Call the function to find and print the slope
findSlope(x1, y1, x2, y2);
return 0;
}
Explanation
- Function Definition (
findSlope
):
- The function
findSlope
takes four integers as input: x1
, y1
, x2
, and y2
.
- It checks if the line segment is vertical (i.e., if ( x1 == x2 )). If so, it prints that the slope is undefined and returns.
- Otherwise, it calculates the slope using the formula ( \text{slope} = \frac{y2 – y1}{x2 – x1} ).
- Based on the value of the slope, it determines if the slope is positive, negative, or zero and prints the result.
- Main Function (
main
):
- It prompts the user to enter the coordinates of the two endpoints.
- It then calls the
findSlope
function to determine and print the nature of the slope.