Introduction to Programming

For Loop

Lesson 8: Loops

What is a For Loop?

A For loop is used when you know exactly how many times you want to repeat something. Unlike a While loop that depends on a condition, a For loop counts through a range of numbers automatically.

In PictoBlox, the Repeat (n) block acts as a For loop. It repeats its contents exactly n times, automatically keeping count for you.
PictoBlox Repeat block with a number input slot and space for blocks inside the loop body

For Loop vs While Loop

For Loop vs While Loop

FeatureFor Loop (Repeat n)While Loop (Repeat Until)
Number of repetitionsFixed and known in advanceUnknown — depends on a condition
Controlled byA counterA condition
Risk of infinite loopNo — stops after n timesYes — if condition never becomes true
Best used forDrawing shapes, repeating animationsWaiting for user input, game loops

Example: Drawing Multiple Squares

Let's use a For loop to draw 5 squares on the Stage, each rotated slightly from the last to create a pattern.

  • Open PictoBlox and add the Pen Extension.
  • Add a 'When flag clicked' block, then 'Erase All' and 'Go to x:0 y:0'.
  • Add a 'Repeat 5' loop.
  • Inside the outer loop, add a 'Repeat 4' loop with 'Move 100 steps' and 'Turn 90 degrees' to draw a square.
  • After the inner loop, add a 'Turn 30 degrees' block to rotate before drawing the next square.
  • Add 'Pen Down' before and 'Pen Up' after.
Block coding script showing a repeat 5 outer loop containing a repeat 4 inner loop for drawing a square, followed by turn 30 degrees
PictoBlox stage showing a star-like pattern made of 5 overlapping squares each rotated 30 degrees
Loops can be nested inside each other! An outer loop can contain an inner loop, and the inner loop will complete all its repetitions for each single repetition of the outer loop.

Subscribe to our newsletter.

Get updates to news and events.