Objective: generate fractals using recursion.
Recall the two famous fractals from computer science last year!
The Sierpinski Carpet, and Triangle.
![]() |
![]() |
/** * Complete the Applet below which draws the Sierpinski Carpet */ import java.awt.*; import java.applet.*; public class Boxes extends Applet { Graphics g; public void drawBox(int x, int y, int s) { if (s <= 1) { return; } // base case else { /** * draw "big" square at position x,y * with length = s, width = s */ g.drawRect(x,y,s,s); /** * now draw 8 smaller squares in the big square * each with size s/3 */ s = s / 3; // <<< Complete the code to draw 8 "small" squares drawBox( <<< COMPLETE THE CODE>>> ); drawBox( <<< COMPLETE THE CODE>>> ); drawBox( <<< COMPLETE THE CODE>>> ); drawBox( <<< COMPLETE THE CODE>>> ); drawBox( <<< COMPLETE THE CODE>>> ); drawBox( <<< COMPLETE THE CODE>>> ); drawBox( <<< COMPLETE THE CODE>>> ); drawBox( <<< COMPLETE THE CODE>>> ); } } public void paint(Graphics gr) { g = gr; setVisible(true); g.setColor(Color.red); drawBox(0, 0, 500); } }
/** * Complete the Applet below which draws the Sierpinski Triangle */ import java.awt.*; import java.applet.*; public class Triangle extends Applet { Graphics g; public void drawTri(int x, int y, int s) { if (s <= 5) { return; } else { /** * draw "big" triangle then make recursive * call to draw three "small" traingles */ int[] a = {x,x+s/2,x+s}; int[] b = {y+s,y,y+s}; g.drawPolygon(a,b,3); /** * complete the code to draw the * three "small" triangles */ // <<< COMPLETE THE CODE } } public void paint(Graphics gr) { g = gr; setVisible(true); g.setColor(Color.red); drawTri(0, 0, 500); } }