Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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. The triangle has formed by three points.

Input:
x1,y1,x2,y2,x3,y3,xp,yp separated by a single space

Sample Solution:

C Code:

#include <stdio.h>
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;
  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]);
  printf("\nInput the point to check it is inside the triangle or not:\n");
  scanf("%lf %lf", & xp, & yp);

  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]);
  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;
}

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 Flowchart: Check if a point (x, y) is within a triangle or not.

C programming Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C program to find the prime numbers which are less than or equal to a given integer.
Next: Write a C program to test whether two lines are parallel or not. The four points are P(x1, y1), Q(x2, y2), R(x3, y3) and S(x4, y4), check PQ and RS are parallel are not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



C Programming: Tips of the Day

Static variable inside of a function in C

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

Ref : https://bit.ly/3fOq7XP