Turtle Graphics with Java

Bern University of Teacher Education  
HomeStart Online-EditorPrintAndroid-TurtlegraphicsJava-Online

while-structure (Iteration)

To draw a square with the Turtle in the first example Tu1, the programer had to repeat the two lines
joe.forward (100);
joe.right (90);

four times.
A more elegant solution is the Java program structure of the Iteration (Repetition). One or more condotions are set and the following actions are executed as long as the conditions are meet.

Run this example (Tu2.java)

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

class Tu2
  Turtle joe = new Turtle();

    int i = 0;            //Starting value
    while (i < 4)         //Condition
      joe.forward(100);   //Actions
      i++;                //Increasing starting value

  public static void main(String[] args)
    new Tu2();


Test this example in the Online-Editor


Explaining the program code:
is equal to i = i + 1. The value of i is increased by 1 after each repetition.