Recursion Explanation and Demos

Simply put, recursion is a function that calls itself.

Refresh your memory of factorials. Define factorials recursively (math, then code).

Practice problems from CodingJS Recursion-1 section. Be sure to do at least the following:

Sierpinski Triangle

Make a Sierpinski triangle drawing program in p5.

../_images/sierpinski-triangle.gif

Key ideas:

  • use an object to hold point data (x and y coordinates)

  • have a function that calculates the midpoint between two coordinates, and returns the resulting coordinate

  • create a sierpinski(points, degree) recursive function. Use the degree as both the exit clause, as well as the index value to select a fill color from a list of colors

Fractal Circles

Check out the demo here.

Fractal Tree

If students are interested in another demo, build something like this Coding Train fractal tree demo.

Practice Quiz

Try the practice quiz to make sure you understand this topic.

Extensions

Maze generator demo (already have a version built in my demos folder…). Warning – This is a much more involved/challenging demo.

Next Section - Bubble Sort