> For the complete documentation index, see [llms.txt](https://easy-draw.joemazzone.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://easy-draw.joemazzone.net/java-curriculum/unit-3-iteration-and-drawings.md).

# Unit 3: Iteration and Drawings

In this unit students use **loops** to draw patterns, grids, and animations. Loops turn a few lines of code into hundreds of shapes, and the results show right away whether the loop is correct.

{% hint style="info" %}
**Teacher notes**

* **Time:** 11 class periods: 6 lessons (1 class each) and 5 classes for the unit project
* **AP Computer Science A:** Iteration (`while` loops, `for` loops, nested loops, developing algorithms, tracing loops) and an introduction to arrays.
* **Before this unit:** students have finished [Unit 2: If Statements and Drawings](/java-curriculum/unit-2-if-statements-and-drawings.md).
* **Tracing tip:** have students predict where the first three shapes will be *before* running a loop. The drawing checks their trace.
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Write `for` loops and `while` loops that draw repeated shapes.
2. Use the loop variable in expressions to change position, size, and color.
3. Write nested loops to draw rows and grids.
4. Combine loops and conditionals to draw patterns.
5. Trace a loop and predict how many times it runs and what it draws.
6. Store shapes in an array and loop over the array to change them.

## Lesson 3.1: for Loops

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        for (int i = 0; i < 10; i++) {
            EasyDraw.Circle dot = new EasyDraw.Circle(30 + i * 60, 300, 25);
            dot.setColor("blue");
        }

        EasyDraw.end();
    }
}
```

Trace it as a table: when `i` is 0, x is 30. When `i` is 1, x is 90. When does the loop stop?

The loop variable can change size and color too. Big circles are drawn first so the smaller ones end up on top.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        for (int i = 0; i < 10; i++) {
            EasyDraw.Circle ring = new EasyDraw.Circle(300, 300, 250 - i * 25);
            ring.setColor(i * 25, 0, 255 - i * 25);
        }

        EasyDraw.end();
    }
}
```

**Practice:**

1. Draw a staircase of 8 squares.
2. Draw 36 lines from the center of the canvas, each rotated 10 degrees more than the last. (Hint: draw the same line each time and call `rotate(i * 10)`.)
3. What changes if the loop is `for (int i = 9; i >= 0; i--)`? Predict, then run it.

## Lesson 3.2: while Loops

A `while` loop repeats as long as its condition is `true`. It is useful when we do not know ahead of time how many times to repeat.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        double size = 280;
        int count = 0;
        while (size > 5) {
            EasyDraw.Rectangle square = new EasyDraw.Rectangle(300 - size, 300 - size, size * 2, size * 2);
            if (count % 2 == 0) {
                square.setColor("black");
            } else {
                square.setColor("white");
            }
            size = size * 0.8;
            count++;
        }

        EasyDraw.Text label = new EasyDraw.Text(300, 585, count + " squares");
        label.setColor("red");

        EasyDraw.end();
    }
}
```

**Discussion:** How many squares will be drawn? What happens if we change `0.8` to `1.2`? (An infinite loop! Show students how to stop the program with Ctrl+C.)

## Lesson 3.3: Nested Loops

A loop inside a loop draws rows and columns.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        for (int row = 0; row < 8; row++) {
            for (int col = 0; col < 8; col++) {
                EasyDraw.Rectangle tile = new EasyDraw.Rectangle(col * 75, row * 75, 75, 75);
                if ((row + col) % 2 == 0) {
                    tile.setColor("black");
                } else {
                    tile.setColor("red");
                }
            }
        }

        EasyDraw.end();
    }
}
```

**Discussion:** How many times does the inner loop's body run in total?

**Practice:**

1. Draw a triangle of circles: 1 in the first row, 2 in the second, and so on up to 8. (Hint: the inner loop's condition uses `row`.)
2. Draw a grid of 100 squares that fade from white in the top-left to black in the bottom-right.

## Lesson 3.4: Algorithms with Loops

Loops can count, find the biggest, or add things up while they draw.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        int tallest = 0;
        int tallestIndex = 0;

        for (int i = 0; i < 12; i++) {
            int height = (int) (Math.random() * 400) + 50;
            EasyDraw.Rectangle building = new EasyDraw.Rectangle(i * 50, 600 - height, 48, height);
            building.setColor("dimgray");

            if (height > tallest) {
                tallest = height;
                tallestIndex = i;
            }
        }

        EasyDraw.Circle marker = new EasyDraw.Circle(tallestIndex * 50 + 24, 600 - tallest - 20, 10);
        marker.setColor("red");

        EasyDraw.end();
    }
}
```

**Practice:**

1. Show the average building height in a `Text` object.
2. Color every building taller than 300 pixels `"steelblue"`.

## Lesson 3.5: Arrays of Shapes

An array can store many shapes so a loop can change all of them later.

```java
public class Main {
    static EasyDraw.Circle[] balls = new EasyDraw.Circle[10];

    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        for (int i = 0; i < balls.length; i++) {
            balls[i] = new EasyDraw.Circle(30 + i * 60, 300, 25);
        }

        EasyDraw.canvasEventSetup("<Button-1>", event -> {
            for (EasyDraw.Circle ball : balls) {
                ball.setColor((int) (Math.random() * 256), (int) (Math.random() * 256), (int) (Math.random() * 256));
            }
        });

        EasyDraw.end();
    }
}
```

## Lesson 3.6: Animation

A loop with `Thread.sleep()` moves a shape a little at a time. `main` needs `throws InterruptedException` to use `Thread.sleep()`.

```java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        EasyDraw.loadCanvas();

        EasyDraw.Circle ball = new EasyDraw.Circle(50, 300, 30);
        ball.setColor("red");
        double speed = 10;

        for (int step = 0; step < 200; step++) {
            double x = ball.getCenterX() + speed;
            if (x > 570 || x < 30) {
                speed = -speed;
            }
            ball.setCenter(x, 300);
            Thread.sleep(20);
        }

        EasyDraw.end();
    }
}
```

**Practice:** Make the ball bounce off all four walls by giving it an x speed and a y speed.

## Unit Project: Pattern Generator

Students write a program that draws an original pattern, scene, or animation using loops. Ideas: a quilt, a city at night with lit windows, a field of flowers, a spiral, an animated screensaver.

**Requirements:**

* At least one `for` loop, one `while` loop, and one nested loop.
* At least one conditional inside a loop.
* At least one algorithm that counts, totals, or finds a minimum or maximum while drawing.
* Uses `Math.random()` so each run is different.
* At least 100 shapes from no more than 60 lines of code inside `main`.
* A written trace table for one of the loops (first 4 times through).

| Category     | 4 - Exceeds                                         | 3 - Meets                                 | 2 - Approaching                   | 1 - Beginning |
| ------------ | --------------------------------------------------- | ----------------------------------------- | --------------------------------- | ------------- |
| Loops        | All loop types used in a complex, purposeful design | `for`, `while`, and nested loops all used | Only one or two kinds of loops    | No loops      |
| Algorithms   | Several algorithms affect the drawing               | One counting/total/min/max algorithm      | Algorithm attempted but incorrect | No algorithm  |
| Trace        | Complete and correct, with a predicted drawing      | Complete and correct                      | Partly correct                    | Missing       |
| Code quality | No "magic numbers," clear names and comments        | Clear names and comments                  | Few comments                      | Hard to read  |
| Design       | Original, polished, and different each run          | Complete and different each run           | Same every run                    | Incomplete    |
