﻿ C : Check if a point (x, y) is within a triangle or not

# C Exercises: Check if a point (x, y) is within a triangle or not

## C Basic Declarations and Expressions: Exercise-137 with Solution

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, y, 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, &y, &x, &y, &x, &y);

// 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 - x, y - y, xp - x, yp - y);
cop2 = check_outer_product(x - x, y - y, xp - x, yp - y);
cop3 = check_outer_product(x - x, y - y, xp - x, yp - y);

// 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: C programming Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿