# Code Ninja Tutorial - Loops and Patterns

Repeat loops are fundamental in Code Ninja for creating patterns and shapes efficiently. They allow you to run a set of commands multiple times.

## Understanding Repeat Loops

### Basic Repeat Loop

• Syntax: `repeat X { commands }`, where X is the number of times to repeat.
• Example: `repeat 4 { fd 100 rt 90 }` draws a square.
• Adjusting the count and commands inside `repeat` lets you create various shapes.

Nested loops are loops within loops. They’re powerful for creating intricate designs. They are as simple as placing one complete repeat loop inside another. The inner loop completes its repetitions before the outer loop continues. This can be used to create a grid or complex geometric patterns.

## Exercise: Drawing a Spiral

Let’s use nested repeat loops to growing squares in a spiral pattern. This code draws a square, then rotates the pointer by a small amount, and increases the length of the line square edges.

``````var length 20
repeat 20 {
repeat 4 {
fd \$length
rt 90
}
rt 15
}
``````

💡 Top Tip Notice the indenting on different blocks of code. Each time a loop is started I press the Tab key on the keyboard. This pushes the code to further right, and helps me to see where the loops begin and end making the code a lot easier to read.

• Use the spiral code to draw your own spiral.
• Experiment with different values for `length` and the rotation angles. You could also try using a constant line length and see what happens there.

## Creating a Complex Geometric Pattern

As an advanced challenge, try creating your own complex pattern using nested loops. Consider how changing the number of repetitions, angles, and line lengths can result in unique designs. Maybe you could try adding multiple repeat loops in a loop, or nesting the loop inside a loop inside a loop! You could also add some random colours or line widths to make it more interesting.

Keep in mind that the number of repetitions can take a long time to run if it’s too high. Start with small numbers and increase them gradually to see the effect on your pattern.

## Wrap-Up

With the knowledge of repeat and nested loops, you’ve unlocked a new level of creativity in Code Ninja. The ability to repeat actions efficiently opens up a world of intricate designs and patterns.