The machine
By the end of this lesson you can put any number in a cell, using two of the eight commands of brainfuck.
A box with a number
Here are four boxes in a row, all holding 0. Press the buttons until the box numbered 0 holds 5:
Notice that every press changed the first box by exactly 1, and that the other three stayed at 0. The outline marks the box you are working on.
The row of boxes is called the tape, a box is a cell, and the outlined one is where the pointer stands. Cells are counted from 0, so the first one is cell 0. The two buttons are commands, written + and −. This tape has four cells to keep it small; a real one has thousands.
A program is a list of presses
Now nobody presses. The seven presses are written out above the boxes as one line, and the marked one comes next. Press Step until the line ends, then drag the slider back and forth to go through it again:
Notice that the line held five + and two −, and that the first cell ended at 3. Nobody pressed a button: the machine read the line from left to right, one command at a time.
A list of commands written down like this is a program.
Write a number
Now you write the line. Make cell 0 hold 7, by typing in the box or with the keys under it. Anything that is not one of the eight commands is skipped, so you may add spaces or words. The tape shows where your program ends:
Hint
A number is that many plus signs.
Below zero
The cell holds 0, and the program is a single −. Press Step once and watch the first box:
Not −1, but 255. Notice that the box jumped from the lowest number to the highest. A cell is like the mileage counter of an old car: after the highest number comes 0 again, and before 0 comes the highest number. We say the cell wraps round.
The cells in this course hold 0 to 255. That is called an 8 bit cell. Other brainfuck machines have larger cells; the Reference lists them.
Check yourself
A free exercise
Make cell 0 hold 250. Typing 250 plus signs would work, but six commands are enough if you remember what the last figure did. Nothing is checked here:
What you can do now
You can put any number from 0 to 255 in a cell with + and −, and read a program one command at a time. These are the commands you know:
| Command | What it does |
|---|---|
+ − | Add 1 to the cell under the pointer, or take 1 off. |
Type the minus with the ordinary hyphen key. The pages draw it as − so that it is easier to see; both work in every box.