Recursive patterns – the Sierpinski Carpet

The Sierpinski Carpet is a fractal pattern first described by Waclaw Sierpinski in 1916. The Sierpinski carpet is self-similar pattern with 8 non-overlapping copies of itself. It starts with a solid white (255) square (in this case a 513×513). This is divided into nine smaller squares. The interior square is filled with black (0). This is the carpet at depth=1. Now subdivide each of the eight remaining squares into 9 squares and fill the centre square of each to obtain a carpet at depth=2. Continue doing this until a depth is reached. Below is an example.

Sierpinski Carpets of different depths: 1 to 4 (top 1,2; bottom 3,4)

What does the Processing code look like? The algorithm makes use of the Processing function rect() to mark a rectangle, and fill(0) to fill the rectangle with black (naturally any course could be specified).

int dim;
int limit, depth;

void setup() {
   size(513, 513);
   dim = 513;
   limit = dim;
   depth = 3;

void draw() {
   for (int i=1; i<=depth; i=i+1) {
      limit = limit / 3;

void sierpinskiCarpet(int x, int y, int size){
   if (size < limit)
   size = size / 3;
   for (int i=0; i<9; i=i+1)
      if (i == 4){
         rect(x+size, y+size, size, size);
         sierpinskiCarpet(x+(i%3)*size, y+(i/3)*size, size);




2 thoughts on “Recursive patterns – the Sierpinski Carpet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.