Programming Course for Beginners - ZedLX

The Easiest Online Computer Programming Course, for Free

How to Generate the Sierpinski Triangle [4/10]

4. Writing a Recursive Function

The hardest step of writing a recursive Sierpinski triangle function is, of course, the recursion. The recursion can be very mind-boggling, so it is usually the best to stick to some good old rules.

A rule, and a very important insight, is that every recursive function must have an atomic case, triggered by the stopping condition. Otherwise, the recursion would continue indefinitely.

The Atomic Case of Recursion

The actual stopping condition can be something practical, of our choice. In the provided source code, the atomic case is triggered when level falls down to 0, which is the stopping condition.

So, what is the atomic case for generating the Sierpinski triangle? Obviously, it is a single triangle. Therefore, a single triangle should be drawn when the stopping condition is reached. The provided source code draws that single triangle in the pink color.

It is also important to remember to exit the function in the atomic case, as that is the main point of the atomic case. The return statement exits the function. In recursive functions, it exits from only one level of recursion, not from the entire call tree.

The entire source code of the atomic case is provided at the beginning of the SierpinskiTriangle function.

Adding the Recursive Case

Writing just the atomic case is not sufficient to make a function recursive. The second required change, compared to the previous page, is that recursive calls have to be performed inside the recursive function. In the source code, the correct recursive calls are now stated, which results in an image that already looks a lot like the Sierpinski triangle.
[Run the program]

The recursive case of the SierpinskiTriangle function is everything not belonging to the atomic case. Obviously, any recursive case must contain recursive calls.

When writing the three recursive calls that draw the inscribed Sierpinski triangles, the level needs to be provided as an argument instead of the color. In order to prevent the recursion from running indefinitely, all recursive calls must end in an atomic case in a finite number of steps. To guarantee finiteness, the level gets reduced by 1 on each level of recursion. Therefore, the level will eventually fall down to zero (from the initial value of 4), which will then trigger the stopping condition.

Compared to the previous page, the drawings of the three inscribed ordinary triangles have simply been replaced by drawings of the three inscribed Sierpinski triangles. With such a simple change, the program already works well. The recursion always works in surprising and magical ways.
[Run the program]

Loading...