C Exercises: Check if a point (x, y) is within a triangle or not
Check if a point lies within a triangle
Write a C program to check if a point (x, y) is within a triangle or not. Three points make up a triangle.
Input:
x1,y1,x2,y2,x3,y3,xp,yp separated by a single space
Sample Solution:
C Code:
#include <stdio.h>
// Function to calculate the outer product of two vectors
double check_outer_product(double X1, double Y1, double X2, double Y2) {
return X1 * Y2 - X2 * Y2;
}
int main() {
double x[3], y[3], xp, yp, cop1, cop2, cop3;
// Prompting the user to input three points to form a triangle
printf("Input three points to form a triangle:\n");
scanf("%lf %lf %lf %lf %lf %lf", &x[0], &y[0], &x[1], &y[1], &x[2], &y[2]);
// Prompting the user to input a point to check if it's inside the triangle
printf("\nInput the point to check if it is inside the triangle or not:\n");
scanf("%lf %lf", &xp, &yp);
// Calculating the outer products using the function
cop1 = check_outer_product(x[1] - x[0], y[1] - y[0], xp - x[0], yp - y[0]);
cop2 = check_outer_product(x[2] - x[1], y[2] - y[1], xp - x[1], yp - y[1]);
cop3 = check_outer_product(x[0] - x[2], y[0] - y[2], xp - x[2], yp - y[2]);
// Checking if the point is inside or outside the triangle based on outer products
if (((cop1 > 0.0) && (cop2 > 0.0) && (cop3 > 0.0)) ||
((cop1 < 0.0) && (cop2 < 0.0) && (cop3 < 0.0))) {
printf("The point is inside the triangle!");
} else {
printf("The point is outside the triangle!");
}
return 0; // End of the program
}
Sample Output:
Input three points to form a triangle: x1 y1 z1 Input the point to check it is inside the triangle or not: The point is outside the triangle!
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to determine if a point is inside a triangle using the area method.
- Write a C program to check point inclusion in a triangle by comparing barycentric coordinates.
- Write a C program to use cross-product calculations to verify if a point lies within the bounds of a triangle.
- Write a C program to implement a function that calculates areas and determines if a point is inside a triangle.
Go to:
PREV : Find all prime numbers ≤n\leq n≤n.
NEXT : Determine if two lines are parallel.
C programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.