Repeating Things

We repeat things using loops. There are multiple kinds of loops, but one of the most useful is the for-loop. We use this when we want to do something a certain number of times. It looks like this:

for(int i = 0; i < max; i++) {

Whatever goes in the brackets gets repeated max number of times.

We can use this do draw a circles inside one another like this:

Repeating Circles

Repeating Circles

We can create this using the code below:

int width = 500;
int height = 500;

void setup() {
   size(500, 500);
   background(236, 0 , 128);

void draw() {
  stroke(140, 9, 214);
  int inc = 50;
  int radius = width - inc;
  int n = radius/inc;
  int x = width/2;
  int y = width/2;

 for(int i = 0; i < n; i++) {
    if (i%2 == 0) {
      fill(255, 126, 0);
     else {

     ellipse(x, y, radius, radius);
     radius = radius - inc;

Let’s look at what’s happening here. We’re drawing the outermost circle first, this is because things we draw later are drawn over the top of things we drew before. So we start with the outermost circle and draw the rest of them inside it, getting progressively smaller.

We have a lot of numbers that we’re using again and again, but they all depend on the size of the applet (which is declared at the top – width and height) and the increment (inc) which is the space between each circle, so we can calculate them from that. Writing math in Processing is much the same as when you do your math homework – except you don’t need to work out the answer yourself!

The initial radius is the width less that space. The number of times we’ll repeat the loop (n) is the number of times we can reduce the radius by inc and still have a circle to draw. x and y are the centre point of the applet.

For each iteration of the loop, we calculate the color (as we did before), draw the circle, and reduce the radius for the next iteration.

One Response to Repeating Things

  1. Pingback: Processing » Archive » Pacman

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>