Learning recursion through visual patterns (i)

The problem with trying to understand recursion is often the examples used. Fibonacci, and factorial are interesting mathematical expressions, which can even be expressed recursively. But most people don’t consciously think in a recursive manner (maybe subconsciously, but who really knows?). One simple way of viewing recursion is through visual patterns.

The easiest of these is the “square within a square within a square…”

This is generated in Processing. Here is the basic Processing environment set-up:

float dx, dy;

void setup() {
   size(400, 400);

void draw() {
   dx = width/2.0;
   dy = height/2.0;

Here is the recursive procedure:

void recSquare(float side) {
   if (side > 1) {
      rect(dx, dy, side, side);

In the recursive function recSquare(),  if the size of the side of the square is greater than 1, it draws a square, and then calls itself recursively with a square size 5 pixels less.



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 )

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.