← All lessons/Arrays· Lesson 25 of 32

Patterns from an array

Store a set of x positions in an array and loop over them to lay out a neat row of shapes.

About 8 min

Data drives the drawing

An array is a great place to keep a set of positions. Put your x-coordinates in a list, loop over them, and let each one place a shape. Change the list and the whole layout changes — no extra code:

Five dots placed by an array of x positions.

Try it

Add another number to xs and run again — a new dot appears all by itself, because the loop follows the array's length.

Your turn

Make an array xs of four x positions, such as [100, 180, 260, 340]. Loop over it and draw one rect at each position — for example rect(xs[i], 180, 40, 40). That's four rectangles in a row.

Hints