Programming Course for Beginners - ZedLX

The Easiest Online Computer Programming Course, for Free

How to Generate the Sierpinski Triangle [3/10]

3. A Function for Drawing

The most common way to generate the Sierpinski triangle is by using functions. To create a function that generates the Sierpinski triangle, the code from the previous page only needs to be slightly reorganized to make a function.

The function SierpinskiTriangle created in such a manner won't yet draw the Sierpinski triangle, but it is an important step towards writing the correct function.
[Run the program by clicking the 'Run' button]

To truly generate the Sierpinski Triangle requires a recursive function. Writing recursive functions can be challenging, so it is a good idea to take some intermediate steps in the process of writing a recursive function.
[Run the program]

It is important to rename all the points within the SierpinskiTriangle function. The letters A, B, and C have now replaced indices 1, 2, and 3 inside the function.

The final adjustment is to perform a call of the SierpinskiTriangle function at the point in the source code where the blue triangle was previously displayed. This new call to the SierpinskiTriangle function now includes an unused argument of value 4, called the level. This argument will be essential for the next enhancement of the program.

Loading...