Fractals
CS 106B: Programming Abstractions
Fall 2025, Stanford University Computer Science Department
Lecturer: Chris Gregg, Head CA: Yasmine Alonso
- Code for today:
Observations about recursion
- The base case represents the simplest possible instance of the problem you are solving.
- Example: How many people are behind you, including you? Answer? 1, it’s just me!
- Example: What is x^n? Answer: x^0 = 1
- Solve the Towers of Hanoi Answer: 1 ring is easy!
- The recursive case represents how you can break down the problem into smaller instances of the same problem.
- Example: How many people are behind you, including you? Answer? 1 + the number behind me
- Example: What is x^n? Answer: x * x^(n-1)
- Solve the Towers of Hanoi Answer: N-1 disks to aux, 1 disk to target, N-1 disks to target
Fractals
A fractal is a recurring graphical pattern. Smaller instances of the same shape or pattern occur within the pattern itself.
Fractal Examples in Nature
- Many natural phenomena generate fractal patterns:
- earthquake fault lines
- animal color patterns
- clouds
- mountain ranges
- snowflakes
- crystals
- coastlines
- DNA
The Cantor Fractal
- We can create many fractals programmatically, and because fractals are self-similar, we can do so recursively!
- The first fractal we will code is called the “Cantor” fractal, named after the late-19th century German mathematician Georg Cantor.
- The Cantor fractal is a set of lines (indeed, a “Cantor Set” of lines) where there is one main line, and below that there are two other lines, each 1/3rd of the width of the original line, one on theleft, and one on the right (with a 1/3 separation of white space between them)
- Below each of the other lines is an identical situation: two 1/3rd lines.
- This repeats until the lines are no longer visible.
The Cantor Fractal
In text, a 4-level Cantor fractal would look like this:
---------------------------
--------- ---------
--- --- --- ---
- - - - - - - -
- Parts of a cantor set image … are Cantor set images!
The Cantor Fractal
- The Cantor fractal above has six levels.
- Every individual line segment is its own 1-level Cantor fractal
How to draw a level 1 Cantor fractal
How to draw a level n Cantor fractal
- Draw a line from start to finish.
- Underneath, on the left third, draw a Cantor of size
n - 1. - Underneath, on the right third, draw a Cantor of size
n - 1.
Graphics in C++ with the Stanford library: GPoint
Let’s code!
Snowflake Fractal
Let’s break this down to a smaller part
Depth 1 Snowflake: A line
Depth 2 Snowflake: The line has a triangle break
Depth 3 Snowflake: In progress
Depth 3 Snowflake: In progress
Depth 3 Snowflake: Finished
Let’s Code a Snowflake!