Join Whatsapp Channel for Ignou latest updates JOIN NOW

Write an algorithm to find the slope of a line segment whose end point coordinates are (x1, y1) and (x2, y2). The algorithm gives output whether the slope is positive, negative or zero. Transform your algorithm into C program. Note : Slope of line segment = (y2 – y1)/ (x2 – x1)

Algorithm to Find the Slope of a Line Segment

  1. Input: Coordinates of the endpoints ((x1, y1)) and ((x2, y2)).
  2. Check if the line segment is vertical:
  • If ( x1 = x2 ), the line is vertical, and the slope is undefined.
  1. Calculate the slope:
  • ( \text{slope} = \frac{y2 – y1}{x2 – x1} )
  1. 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.
  1. 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

  1. 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.
  1. 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.
error: Content is protected !!