Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 13-8: Recursion

void setup() {
  size(200,200);
  smooth();
}

void draw() {
  background(255);
  stroke(0);
  noFill();
  drawCircle(width/2,height/2,100);
}

void drawCircle(float x, float y, float radius) {
  ellipse(x, y, radius, radius);
  if(radius > 2) {
    // drawCircle() calls itself twice, creating a branching effect. 
    // For every circle, a smaller circle is drawn to the left and right.
    drawCircle(x + radius/2, y, radius/2);
    drawCircle(x - radius/2, y, radius/2); 
  }
}
  • Samuel

    class Bubble
    {
    float diam;
    float x;
    float y;

    Bubble()
    {
    diam = random(80);
    // x = random(width + 2000);
    x = random(width + 1500);
    y = 100;
    }

    void draw() // Not the global draw!
    {
    fill(132, 22, 88, 6);
    ellipse(x, y, diam, diam);
    }
    }

    //~ ArrayDeque bubbles;
    ArrayList bubbles;

    void setup() {
    size(200, 100);
    background(255);
    smooth();

    //~ bubbles = new ArrayDeque();
    bubbles = new ArrayList();
    }

    void draw() {
    background(255);
    bubbles.add(new Bubble());
    Iterator it = bubbles.iterator();
    while (it.hasNext())
    {
    Bubble b = (Bubble) it.next();
    b.draw();
    }
    if (bubbles.size() > 20)
    {
    bubbles.remove(0);
    }
    }

    *thanks to PhiLho for this one*

  • Orrick Hampton

    Can you assume the radius is cut in half in the recursive function only after 3 circles are drawn. When I tried to check it out with println I got a flow that was hard to follow although it seems the assumption would give the same answer.

  • http://www.learningprocessing.com Daniel Shiffman

    You could, but in order to determine how many circles were drawn you’d have to introduce a new variable to keep track of the number of iterations. Check out this example on processing.org which has a variable called “level” that will do the trick for you.

    http://processing.org/learning/basics/recursion.html

  • Ndstephens

    Shouldn’t “radius” be named “diameter”?  Since we’re using the default ellipseMode(CENTER) then the value of “100″ is setting the first circles diameter.  We then cut the diameter in half with each recursion to get the specified look above.  If we cut the circle’s actual radius in half, then the final image would look different.  I realize it doesn’t matter in a sense b/c it’s just a variable name.  The image will look the same no matter what the variable is called.  But for naming purposes it just doesn’t make sense and threw me off while i was reading the book and looking at the image.

  • B

    Hi can any one please tell me how to plot random points inside a circle..