LearnBrainfuck basics

Loops

By the end of this lesson you can make the machine repeat a piece of program, and empty a cell whatever it holds.

Round and round

This program puts 3 in cell 0, and then comes a pair of square brackets around a minus. Press Step until it has ended, and read the question the line under the tape asks at each bracket:

Empty a cell

Cell 0 holds 200. Empty it with a program of at most 3 commands:

A loop that moves something

Now a loop with more inside it: it takes 1 from cell 0 and adds 3 to cell 1. Press Play, or step through it, and watch both cells until the program has ended:

A loop that never ends

Here the loop has nothing inside it. Drag the slider all the way to the right, and read the line under the tape. The figure stops after 500 steps, so that nothing freezes:

A loop that never starts

This time the cell holds 0 when the loop begins, and one more command follows the loop. Press Step until the end and watch what the first bracket does:

Check yourself

A free exercise

Write a loop that goes round 5 times and adds 2 to cell 1 each round, so that cell 1 ends at 10. Nothing is checked here:

What you can do now

You can repeat with [ and ] until a cell is zero, empty a cell with [−], and spot a loop that cannot end. These are the commands you know:

The commands of Lessons 1 to 4.
CommandWhat it does
+ −Add 1 to the cell under the pointer, or take 1 off.
> <Move the pointer one cell to the right or to the left.
.Print the cell as one character.
[ ]Repeat everything between them until the cell under the pointer is zero.

Brackets must match: every [ needs its own ] further on. Loops may stand inside loops. A program whose brackets do not match is the only kind of brainfuck program that is refused before it runs.

The loop of step 3 is a multiplication, and with it a big number takes only a few commands. Lesson 5 builds them.