To Check Whether the Given Point P is inside a Triangle or Not

Submitted by:Jhon Jhon

Date added:13 May, 2015

Category:C

C code example to check whether the given point P is inside a Triangle or Not

Tags: point p , triangle

Code Snippet:

#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#include<math.h>

int main()
{
int x[]={0,0,0,0};
int y[]={0,0,0,0};

int i=0;

int VarX=0, VarY=0;
int Size=sizeof(x)/sizeof(int);
clrscr();
printf("Size of x: %d\n",Size);

for (i=0;i<3;i++)
{
printf("Enter X[%d]:",i);
scanf("%d",&x[i]);
printf("Enter Y[%d]:",i);
scanf("%d",&y[i]);
}

printf(" \n Enetr the Co-ordinates of the Fourth Point \n");
printf("\n Enter X[3] : ");
scanf("%d" , &x[3]);
printf(" \n Enter Y[3] : " );
scanf("%d", &y[3]);

for (i=0;i<4;i++)

{
printf("X[%d] Y[%d] = [%d] [%d] \n",i,i,x[i],y[i]);
}

i=0;

if ( ( (x[i]<=x[3] ) && ( x[i+1]>=x[3])) || ( (x[i+1]<=x[3]) && (x[i]>=x[3])) )

{
VarX=1;}

else if( ( (x[i+1]<=x[3]) && (x[i+2]>=x[3])) || ((x[i+2]<=x[3]) && (x[i+1]>=x[3])) )
{ VarX=1; }
else if ( ((x[i+2]<=x[3] && x[0]>=x[3])) || ((x[0]<=x[3] && x[i+2]>=x[3])))

{ VarX=1; }

printf(" \n The Value of VarX is :%d ",VarX);
i=0;
if ( ((y[i]<=y[3]) && (y[i+1]>=y[3])) || ((y[i+1]<=y[3]) && (y[i]>=y[3])) )
{ VarY=1;}
else if( ((y[i+1]<=y[3]) && (y[i+2]>=y[3])) || ((y[i+2]<=y[3]) && (y[i+1]>=y[3])) )
{ VarY=1; }
else if ( ((y[i+2]<=y[3]) && (y[0]>=y[3])) || ((y[0]<=y[3]) && (y[i+2]>=y[3])) )
{
VarY=1;
}

printf("\n The Value of VarY is %d " , VarY);

if (VarX && VarY )
{ printf(" The Point X[4] Y[4] is in side the Triangle .....\n");}
else { printf( "\n The Point is not Inside Triangle ....\n");}

getch();

return(0);
}
 
 

Comments