Write a C program to find intersection of two lines.
Answers
#include <stdio.h>
void main ()
{
float slope1, intercept_c1, slope2, intercept_c2;
float x1, y1, x2, y2;
float intersection ptX, intersection ptY;
x1=1;
y1=2;
x2=5;
y2=7;
slope1=(y2-y1)/(x2-x1);
printf("Slope of line1:%f\n",slope1);
intercept_c1=y1 - slope1*x1;
printf("Intercept of line1:%f\n",intercept_c1);
x1=3;
y1=3;
x2=4;
y2=5;
slope2=(y2-y1)/(x2-x1);
printf ("Slope of line2:%f\n",slope2);
intercept_c2=y1 - slope2*x1;
printf("Intercept of line2:%f\n",intercept_c2);
printf("Equation of line1: Y = %.2fX %c %.2f\n", slope1, (intercept_c1 < 0) ? ' ‘: '+', intercept_c1);
printf("Equation of line2: Y = %.2fX %c %.2f\n", slope2, (intercept_c2 < 0) ? ' ‘: '+', intercept_c2);
if((slope1 - slope2) == 0)
printf("No Intersection between the lines\n");
else
{
Intersection ptX = (intercept_c2 - intercept_c1) / (slope1 - slope2);
intersection ptY = slope1 * intersection ptX + intercept_c1;
printf("Intersecting Point: = %.2f, %.2f\n", intersection ptX, intersection ptY);
}
}
Explanation:
The above program finds the intersection of two lines for the given end points of those lines.
Step 1: Find the slope for first line, using formula slope = (y2 - y1) / (x2 - x1) and also calculate the intercept using formula intercept = y1- slope * x1.
Step 2: Find the slope and intercept for second line using the formula mentioned in step 1.
Step 3: Using the slope and the intercept, intersecting point of the two lines can be calculated as follows:
If the difference between the slope of two lines are ZERO, then there is no intersection.
Else
intersection_ptX = (intercept_c2 - intercept_c1) / (slope1 - slope2);
intersection_ptY = slope1 * intersection_ptX + intercept_c1;