Looping in two dimensions

A simple diamond pattern loops in two dimensions

This simple diamond pattern loops by repeating the shape in two dimensions.

How are repeating patterns like the one above created? You guessed it, they are a kind of loop!

In this case they repeat the pattern not only in one direction but in two dimensions. What does that mean?

When we create a one dimensional pattern from a row of shapes, we loop across the x access by using a counter that set the x position of the shape.
Here is the code for a one dimensional loop. Can you spot the counter which loops across the x axis? It should look familiar, if not, take a look at this tutorial.

   for(int x=0; x<=width; x=x+radius){
        ellipse(i,j, radius, radius); 
This pattern loops by repeating the ellipse along the x axis.

This pattern loops by repeating the ellipse along the x axis.

To create a two dimensional pattern we loop down the y axis by using another  counter ( which draws a whole row of shapes and sets the position of the y axis. Here’s the end product:

This pattern loops by repeating the row of ellipses down the y axis.

This pattern loops by repeating the row of ellipses down the y axis.

And here’s the code. See whether you can find both the x counter and the y counter in this example:

   for(int x=0; x<=width; x=x+radius){
     for(int y =0; y<=height; y=y+radius){
        ellipse(i,j, radius, radius); 

Play around with this more complex example in a sketchpad. Can you change the diamond pattern to repeat a different shape? Can you change from two dimensions to one dimension and back? Can you change the spacing of the pattern? Be careful, the counter variables are named i and j instead of x and y.

// The message to be displayed
color white =color(255);
color yellow =color(255,255,0);
color blue =color(0,0,255);
color red =color( 95,0,0);
color green= color(0,134,0);
color darkgreen=color(0,57,0);
color purple= color(229,41,255,100);
color skyblue=color(41,250,255);
color black = color(0);
color bg = black;
int diamondSize = 20;
void setup(){

void draw(){
setFullPattern(black, diamondSize);
//save a screenshot of the image
if (mousePressed) {
if (mouseButton == RIGHT) {

void setFullPattern(color patternColor, int offset){
for(int i=0; i<=width; i=i+offset){
for(int j =0; j<=height; j=j+offset){
vertex(i, j);
vertex(i, j-offset/2);
vertex(i+offset/2, j);
vertex(i, j+offset/2);
vertex(i-offset/2, j);
vertex(i, j-offset/2);

2 thoughts on “Looping in two dimensions

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s