Point in Polygon in C
Posted: , Last Updated:
package point_in_polygon.c;
/**
* Used to perform the Raycasting Algorithm to find out whether a point is in a given polygon.
*/
public class PointInPolygon {
/**
* Performs the evenoddrule Algorithm to find out whether a point is in a given polygon.
* This runs in O(n) where n is the number of edges of the polygon.
*
* @param polygon an array representation of the polygon where polygon[i][0] is the x Value of the ith point and polygon[i][1] is the y Value.
* @param point an array representation of the point where point[0] is its x Value and point[1] is its y Value
* @return whether the point is in the polygon (not on the edge, just turn < into <= and > into >= for that)
*/
public static boolean pointInPolygon(int[][] polygon, int[] point) {
//A point is in a polygon if a line from the point to infinity crosses the polygon an odd number of times
boolean odd = false;
// int totalCrosses = 0; // this is just used for debugging
//For each edge (In this case for each point of the polygon and the previous one)
for (int i = 0, j = polygon.length  1; i < polygon.length; i++) { // Starting with the edge from the last to the first node
//If a line from the point into infinity crosses this edge
if (((polygon[i][1] > point[1]) != (polygon[j][1] > point[1])) // One point needs to be above, one below our y coordinate
// ...and the edge doesn't cross our Y corrdinate before our x coordinate (but between our x coordinate and infinity)
&& (point[0] < (polygon[j][0]  polygon[i][0]) * (point[1]  polygon[i][1]) / (polygon[j][1]  polygon[i][1]) + polygon[i][0])) {
// Invert odd
// System.out.println("Point crosses edge " + (j + 1));
// totalCrosses++;
odd = !odd;
}
//else {System.out.println("Point does not cross edge " + (j + 1));}
j = i;
}
// System.out.println("Total number of crossings: " + totalCrosses);
//If the number of crossings was odd, the point is in the polygon
return odd;
}
}
About the algorithm and language used in this code snippet:
Point in Polygon Algorithm
The Point in Polygon (PIP) problem is the problem of determining whether a point is any arbitrary polygon. This might sound trivial for a simple polygon like a square or a triangle, but gets more complex with more complex polygons like the one in the example below. In this post, the evenodd algorithm, also called crossing number algorithm or Jordan’s algorithm (since it can be proven using the Jordan curve theorem), will be introduced.
Description of the Algorithm
The basic principle behind the Evenodd aka. Jordan aka. Cross Number Algorithm is to count the number of times a line from the point in question (in any, arbitrary direction) crosses any edge of the polygon. This line will always be outside of the polygon at it’s “end” in infinity, so if it is inside the polygon at the start (the point in question), it will have to leave the polygon at some point, crossing some edge. It can reenter the polygon (see the example below), but it always has to leave again, making the total number of crossings uneven if the point is in the polygon. The opposite is also true; if the number of crossings is even, the point is always outside of the polygon. This is the above mentioned Jordan’s curve theorem.
The algorithm checks every edge of the polygon in a loop to determine if the line from the point to infinity crosses it. In the example below, this line is drawn from the point to infinity to the right, but it can be any direction.
The steps are:
 For each edge in the polygon:
 If the edge crosses the imaginary line from the point to infinity, increase a counter.
 At then end, if the counter is uneven, return true. Else, return false.
A simple boolean variable that is inverted every time a crossing is found is also possible.
Example of the Algorithm
Consider the following polygon with 8 edges and two points for which we want to determine whether they are in the polygon:
The steps the algorithm performs on this polygon to determine whether the first (green) point is in the polygon are, starting from the first edge:
 Green Point crosses edge 8
 Green Point does not cross edge 1
 Green Point crosses edge 2
 Green Point does not cross edge 3
 Green Point crosses edge 4
 Green Point crosses edge 5
 Green Point does not cross edge 6
 Green Point does not cross edge 7
 Total number of crossings: 4
 Even number of edge crossings, therefore the point is not in the polygon
The steps the algorithm performs on this polygon to determine whether the second (red) point is in the polygon are, starting from the first edge:
 Red Point does not cross edge 8
 Red Point does not cross edge 1
 Red Point does not cross edge 2
 Red Point does not cross edge 3
 Red Point does not cross edge 4
 Red Point crosses edge 5
 Red Point does not cross edge 6
 Red Point does not cross edge 7
 Total number of crossings: 1
 Uneven number of edge crossings, therefore the point is in the polygon
Runtime Complexity of the Algorithm
The runtime complexity of the Jordan Algorithm aka. Crossing Number Algorithm aka. EvenOdd Algorithm to solve the pointinpolygon problem for a single point is linear with respect to the number of edges. This is evident by looking at the code, which contains a single loop over the edges, with no recursion or further function calls or loops.
Formally the runtime is O(V), V:=number of edges in the polygon.
Space Complexity of the Algorithm
The space complexity is also linear w.r.t. the number of edges, since only fixedsize variables need to be stored in addition to the polygon. Additionally, the algorithm can be implemented online, meaning there is no need to look at past edges during the loop, so they can be evicted from memory (or comparable performance improvement measures).
C
C is a compiled language used for many purposes, although it can be primarily found in systems where importance is important. This is because C offers a lot of lowlevel support for optimization, at the cost of not having some of the convenient abstractions that other languages offer. C is therefore primarily found in situations where available computation power is low such as embedded systems, or situations where required computation power is high, such as simulation or deep learning.
Getting to “Hello World” in C
The most important things first  here’s how you can run your first line of code in C.
 If you’re on Linux or Mac, download and install the latest version of GCC, a C compiler, from gcc.gnu.org. You can also download an earlier version if your use case requires it.
 If you’re on Windows, you can also install GCC, even though it might cause problems. You also have other options outlined e.g. here.

Open a terminal, make sure the
gcc
command is working (or the according command for whichever compiler you’re using), and that the command your’re going to be using is referring to the version you just installed by runninggcc version
. If you’re getting a “command not found” error (or similar), try restarting your command line, and, if that doesn’t help, your computer. If the issue persists, here are some helpful forum questions for each platform: 
As soon as that’s working, copy the following snippet into a file named HelloWorld.c:
#include<stdio.h> int main() { printf("Hello World\n"); return 0; }
 Change directory by typing
cd path/to/HelloWorld
, then rungcc HelloWorld.c
to compile the file (which creates the bytecode), then run./a.out
. This should print “Hello World” to your Terminal.
That’s it! People who know multiple programming languages will notice that the entry barrier in C is a little lower than Java even though it is lowerlevel, while the entry barrier to Python is lower even though it is higherlevel. My personal observation is that lowlevel and highlevel languages tend to have low barriers of entry, whereas midlevel languages have higher barriers.
Fundamentals in C
To understand algorithms and technologies implemented in C, one first needs to understand what basic programming concepts look like in this particular language. Each of the following snippets should be compiled and run using the commands mentioned above.
Variables and Arithmetic
Variables in C are statically typed, meaning the content of a variable needs to be specified when writing the code.
The datatype for whole numbers, for example is int
.
Numbers with decimal places are typed float
or double
depending on the required precision.
The type for text ist String
.
#include<stdio.h>
int main() {
int number = 5;
double decimalNumber = 3.25;
double result = number * decimalNumber;
char callout [] = "The number is ";
// In this instance, the values are concatenated rather than added because one of them is a String.
printf("%s", callout);
printf("%f", result);
printf("\n");
return 0;
}
Arrays
Arrays in C are real arrays (as opposed to e.g. Python where they’re implemented as lists). The implications of that are that the size needs to be set when they are created and cannot be changed, but also that they are more efficient in C than they are in Python. Also, contrary to Java, C does not check array bounds. If you access an index that doesn’t exist, the program will read whatever is in the memory at that location (which will probably be gibberish).
int integers[5];
integers[3] = 12; // Assigning values to positions in the array
printf("%d\n", integers[0]); // will be 0
printf("%d\n", integers[3]); // will be 12
printf("%d\n", integers[6]); // will print something random that happened to be at that location in memory
return 0;
Conditions
Just like most programming languages, C can do ifelse
statements. Additionally, C can also do switchcase
statements.
int value = 5;
if(value == 5){
printf("%s\n", "Value is 5");
} else if(value < 5){
printf("%s\n", "Value is less than 5");
} else {
printf("%s\n", "Value is something else");
}
switch (value){
case 1:
printf("%s\n", "Value is 1");
break; // Don't go further down the cases
case 2:
printf("%s\n", "Value is 2");
break; // Don't go further down the cases
case 3:
printf("%s\n", "Value is 3");
break; // Don't go further down the cases
case 4:
printf("%s\n", "Value is 4");
break; // Don't go further down the cases
case 5:
printf("%s\n", "Value is 5");
break; // Don't go further down the cases
default:
printf("%s\n", "Value is something else");
}
The above C code will print “Value is 5” twice.
Loops
C supports for
, while
as well as do while
loops. break
and continue
statements are also supported.
The below example illustrates the differences:
int value = 2;
for (int i = 0; i < value; i++) {
printf("%d\n", i);
}
while (value > 0) {
printf("%d\n", value);
value;
}
do {
printf("%d\n", value);
value;
} while (value > 0);
This will print the following to the terminal:
0
1
2
1
0
Note the last 0
: it is printed because in the dowhile
loop, compared to the while
loop. the code block is executed at least once before the condition is checked.
Functions
Functions in C can be declared similar to Java, but require less boilerplate since they don’t need to be part of classes or objects. Here is a minimal example of a function:
#include<stdio.h>
int addNumbers(int numberOne, int numberTwo) {
return numberOne + numberTwo;
}
int main() {
printf("%d\n", addNumbers(3, 4));
}
Syntax
C requires the use of curly brackets ({}
) to surround code blocks in conditions, loops, functions etc.;
It also requires semicolons at then end of statements.
While this can lead to some annoying syntax errors, it also means the use of whitespace for preferred formatting (e.g. indentation of code pieces) does not affect the code.
Note how the Syntax of C is very similar to Java.
The Syntax of Java, and many other languages that came after and/or were derived from C copy many aspects of its Syntax.
Advanced Knowledge of C
C was first released in 1972, is statically typed and was ported to many platforms with various implementations (one of which is GCC which was presented in this article). For more information, C has a great Wikipedia) article.