Challenging C programming practice problem. A line segment can be described by t
ID: 3885588 • Letter: C
Question
Challenging C programming practice problem.
A line segment can be described by two end-points. Read two line segments as (x_1, y_1) (x_2, y_2) (x_3, y_3) and (x_4, y_4). You will write a program (1) to draw two lines (2) to draw a small circle at the cross-point if they if they cross to each other as shown below: Refer the wikipedia at https: // en.wikipedia.org/wiki/Line-line intersection for mathematical background. The article gives a formula to find the intersection point of two infinitely long lines defined by the points. This lab asks to find a cross-point of two line segments between the points. Remember that you must test your program with various test cases to show all exceptional cases. Challenge: Read an input file in which each line contains 8 numbers indicating a pair of line segments. Find a cross-point for each pair and draw them in different color, line style and/or thickness. In that way, multiple pairs line segments and circles can be distinguished even they are drawn in a single paper.Explanation / Answer
#include <graphics.h>
#include <stdio.h>
#include <math.h>
#include <dos.h>
void main( )
{
float x,y,x1,y1,x2,y2,dx,dy,step;
float intersection_X, intersection_Y;
int i,gd=DETECT,gm;
initgraph(&gd,&gm," ");
printf("Enter the value of x1 and y1 : ");
scanf("%f%f",&x1,&y1);
printf("Enter the value of x2 and y2: ");
scanf("%f%f",&x2,&y2);
dx=abs(x2-x1);
dy=abs(y2-y1);
if(dx>=dy)
step=dx;
else
step=dy;
dx=dx/step;
dy=dy/step;
x=x1;
y=y1;
float m1 = dy / dx;
// y = mx + c
// intercept c = y - mx
float c1 = y1 - m1 * x1; // which is same as y2 - slope * x2
i=1;
while(i<=step)
{
putpixel(x,y,5);
x=x+dx;
y=y+dy;
i=i+1;
delay(100);
}
printf("Enter the value of x3 and y3 : ");
scanf("%f%f",&x1,&y1);
printf("Enter the value of x4 and y4: ");
scanf("%f%f",&x2,&y2);
dx=abs(x4-x3);
dy=abs(y4-y3);
if(dx>=dy)
step=dx;
else
step=dy;
dx=dx/step;
dy=dy/step;
x=x1;
y=y1;
float m2 = dy / dx;
// y = mx + c
// intercept c = y - mx
float c2 = y1 - m1 * x1; // which is same as y2 - slope * x2
i=1;
while(i<=step)
{
putpixel(x,y,5);
x=x+dx;
y=y+dy;
i=i+1;
delay(100);
}
if( (m1 - m2) == 0)
printf("No Intersection between the lines ");
else
{
intersection_X = (c2 - c1) / (m1 - m2); //to find intersection between the lines
intersection_Y = m1 * intersection_X + c1;
printf("Intersecting Point: = %.2f, %.2f ", intersection_X, intersection_Y);
circle(intersection_X, intersection_Y, 50); //for drawing circle
}
closegraph();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.