One simple graphical example of recursion is the Sierpinski triangle, which can easily be drawn by hand, which will help in determining how to write the algorithm.
On a piece of paper:
We can draw Sierpinski triangles on the computer using any graphical library. Using Processing, and perhaps even the PTurtle module, we can write a program with a recursive function that creates Sierpinski triangles.
As you consider how to go about doing this, think about what the function will need to have for parameters. What will be the base case for our function? What will the recursive call look like, and what parameters will need to be modified when we make the recursive call?
One strategy for determining when the algorithm should stop is to think of the "degree" of the triangle (fractal). It begins with a degree of some value--say 3--and then each time we recurse, we reduce the degree of the triangle by 1. Once the degree reaches 0, we'll have arrived at the base case.
Create a Processing project SierpinskiTriangle
that draws Sierpinski triangles.
Sierpinski triangles have a certain appeal of their own, but they become even more interesting when the triangles are given different colors.
Begin by filling your triangle with a color, either black or white, based on the odd- or even-degree of the triangle.
if (degree % 2 == 0)
fill(0); // black
else
fill(255); // white
Once you've done that, consider expanding the range of colors that you use for the fill by creating a color map of colors that can be used in coloring your triangle.
In your instance variables create an Array of colors:
color[] map = {color(255,128,0), color(128,255,0), color(0, 128, 128)};
In your recursive function, identify the fill for each triangle based on the degree and the color map:
fill(map[degree % map.length]);