Turtlegraphics with Java
HomeAufgabenDruckenJava-Online

Recursion

Recursion is a problem solving method in which a problem reduced to the same, but a bit simpler problem. In Java a method is recursive if its declaration class the same method. To be sure that the recursive program does not end in an infinite loop, it is necessary to set breaking conditions.

   
// Quadratmuster1.java
import ch.aplu.turtle.*;

public class  Quadratmuster1 extends Turtle
{
  public Quadratmuster1()
  {
    hideTurtle();
    figure(0064);
  }

  void figure(double x, double y, double s)
  {
    if (< 1)
    {
      return;
    }
    else
    {
      setPos(- s/2, y - s/2);
      quadrat(s);
      figure(+ s, y + s, s/2);
    }
  }

  void quadrat(double s)
  {
    for(int i = 0; i < 4; i++)
    {
      forward(s);
      right(90);
    }
  }

  public static void main(String[] args)
  {
    new Quadratmuster1();
  }
}
 


With some small addition other patterns can be drawn...

// Quadratmuster2.java
import ch.aplu.turtle.*;

public class  Quadratmuster2 extends Turtle
{
  public Quadratmuster2()
  {
    hideTurtle();
    speed(-1);
    figure(0064);
  }

  void figure(double x, double y, int s)
  {
    if (< 1)
    {
      return;
    }
    setPos(- s/2, y - s/2);
    quadrat(s);
    figure(+ s, y + s, s/2);
    figure(- s, y + s, s/2);
  }

  void quadrat(int s)
  {
    for(int i = 0; i < 4; i++)
    {
      forward(s);
      right(90);
    }
  }

  public static void main(String[] args)
  {
    new Quadratmuster2();
  }
}
 


Example Koch graph:

 
// Koch.java

import ch.aplu.turtle.*;

public class Koch extends Turtle
{
  public Koch()
  {
    double length = 200;
    int generations = 4;
    hideTurtle();
    setPos( -180, 0);
    right(90);
    koch(length, generations);
  }

  private void koch(double s, int n)
  {
    if (n == 0)
    {
      forward(s);
      return;
    }
    koch(s / 3, n - 1);
    left(45);
    koch(s / 3, n - 1);
    right(90);
    koch(s / 3, n - 1);
    left(45);
    koch(s / 3, n - 1);
  }

  public static void main(String[] args)
  {
    new Koch();
  }
}
 


More examples:

Tree.java

Sierpi.java

Peano.java

Menger.java

Dragon.java