Moving
By the end of this lesson you can fill several cells, and you know why it matters where the pointer stands.
Walk along the tape
The tape has five cells again, now with two more buttons, Left and Right. Make cell 0 hold 2 and cell 2 hold 3, and leave the other cells at 0:
Notice that + and − changed only the cell with the outline, and that Left and Right changed no number: they moved the outline. To put 3 in cell 2 you first had to walk there, one cell at a time.
In a program, the two new buttons are the commands >, one cell to the right, and <, one cell to the left. They move the pointer. There is no command for "go to cell 2".
One, two, three
Now you write the line. Make cell 0 hold 1, cell 1 hold 2 and cell 2 hold 3. The tape under the box shows what your program leaves, and the line under the figure says what is still wrong:
Hint
After the plus for cell 0, move right before you add again.
Read the answer aloud: +>++>+++ is one here, step right, two here, step right, three here. Notice that most of a brainfuck program has this beat: walk, change, walk, change.
One step too many
This program was meant to leave 3 in cell 0 and 2 in cell 1. It does not. Drag the slider back to the start and step through it, watching where the pointer goes, then repair the line in the box:
Hint
Step through the program and watch where the last two plus signs land.
Notice that one > too many sent the 2 to cell 2. The machine did not complain: every line made of these four commands is a correct program. It just did something other than you meant.
Most mistakes in brainfuck are this one: the pointer is not where you think it is. The cure is the one you just used. Step through the program and watch the pointer.
The edge
The pointer stands on cell 0, and the program is a single <. Press Step once and read the line under the tape:
Notice that the program stopped: there is nothing to the left of cell 0. Here the machine says so. Some brainfuck machines quietly do something odd instead; either way it is a mistake in the program.
To the right there is room. The tape in these figures has six cells to keep it small; in the Challenges it has 30,000. How long the tape is, and what happens at its ends, differs from one brainfuck machine to the next; the Reference lists them.
Check yourself
A free exercise
Write 1, 0, 1, 0, 1 into the first five cells, and make the program end with the pointer back on cell 0. Nothing is checked here:
What you can do now
You can walk along the tape and put numbers in several cells. These are the commands you know:
| Command | What 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. |