Algorithm to find the slope of a line segment.

IT & Software

| 133 views

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.

Here’s a simple algorithm to find the slope of a line segment given its endpoints (x1,y1)(x1,y1) and (x2,y2)(x2,y2). The slope mm is calculated using the formula:

m=(y2−y1)/ (x2−x1)

Algorithm Steps:


 1. Input the coordinates x1x1, y1y1, x2x2, and y2y2.


 2. Check if x1x1 is equal to x2x2:
        If true, the slope is undefined (vertical line).
        If false, calculate the slope using the formula.


 3. Determine the nature of the slope:
        If m>0,  output "Positive slope Positive".
        If m>0,  output "Positive slope Negative".

         If m==0, output "Zero slope".

C Program


Here’s how you can implement the above algorithm in C:

#include 
int main() {
    float x1, y1, x2, y2, slope;
    // Input coordinates
    printf("Enter coordinates (x1, y1, x2, y2): ");
    scanf("%f %f %f %f", &x1, &y1, &x2, &y2);
    // Check for vertical line
    if (x1 == x2) {
        printf("The slope is undefined (vertical line).\n");
    } else {
        // Calculate the slope
        slope = (y2 - y1) / (x2 - x1);
        // Determine the nature of the slope
        if (slope > 0) {
            printf("Positive slope\n");
        } else if (slope < 0>           
             printf("Negative slope\n");
        } else {
            printf("Zero slope\n");
        }
    }
    return 0;
}


Explanation of the C Program:


    The program prompts the user to enter the coordinates of the two endpoints.
    It checks if the line is vertical by comparing x1x1 and x2x2.
    If the line is not vertical, it calculates the slope and checks its value to determine if it's positive, negative, or zero, then outputs the result accordingly.

You can compile and run this code using any standard C compiler.

📢 Join Our WhatsApp Channel

Get Daily GK, Current Affairs, Amazing Facts & Quiz Updates.

🚀 Join Now
Share this Post
About Author

Quizer Team

Comments

No comments yet — be the first to comment! 💬
Leave a Comment

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

Daily Challenge

📅 Daily Quiz Challenge

Attempt today's quiz and improve your competitive exam preparation with fresh questions daily.

Start Quiz →
Mega Contest

🏆 Monthly Mega Quiz

Participate in monthly quiz contests and test your overall knowledge with top performers.

Explore Quiz →

🔥 Join Our WhatsApp Channel

Daily GK, Facts & Quiz Updates