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 form a function.

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

The real function that generates the Sierpinski triangle must be a recursive function. Recursive functions are not easy to write, so it is a good idea to use some intermediate steps in the process of writing a recursive function.
[Run the program]

Notice that it is required to actually rename all the points inside the SierpinskiTriangle function. All the vertices and mid-points now use slightly different names compared to the previous page, where indices 1, 2 and 3 have now been replaced by the letters A, B and C.

The last change is to perform a call of the SierpinskiTriangle function. The call is made at the place in the source code where previously the blue triangle was displayed. The new call to the SierpinskiTriangle function features an unused argument of value 4, called the level, which will be required in the next improvement of this program.

Loading...