Moving and copying
By the end of this lesson you can move a value to another cell, add two values, and copy one.
Pour it over
A value that you read or built sits in one cell, and sooner or later you need it somewhere else. Cell 0 holds 5, and the program is a loop of six commands. Press Play, or drag the slider through the steps, and watch both cells:
Notice that every round took one from cell 0 and gave one to cell 1, until cell 0 was empty. It is like pouring water from one glass into another, a drop at a time.
This is called moving a value. Look at cell 0: the value is not there any more. In brainfuck, reading a value uses it up.
Two cells further
The box holds the loop of the first figure. Change it so that the value of cell 0 lands in cell 2 instead of cell 1. It must work for any value, so it is tried with 7 and with 3:
Hint
Inside the loop the pointer walks to the target and back.
Hint
Two steps right, add, two steps left.
[−>>+<<] The walk inside the loop has to end where it began, on the counter: as many < as >. If they do not match, the bracket asks its question about the wrong cell. That is the mistake of Lesson 2, a pointer that is not where you think it is, now inside a loop.
Keep the original
Cell 0 holds 4, and the program has two loops. Press Play, or Step through it, and watch all three cells:
Notice that cell 0 was emptied, as before, but filled up again, and that cell 1 now holds the same number. The first loop poured cell 0 into cells 1 and 2 at once. The second loop poured cell 2 back into cell 0. That makes a copy in two moves.
Cell 2 was only borrowed. A cell used like this is called a scratch cell: it has to be empty before, and it is empty again after.
Adding
Cell 0 holds 3 and cell 1 holds 4. Write a program that leaves their sum in cell 1. It must work for other numbers too, so it is also tried with 10 and 1:
Hint
What happens if you pour a cell into a cell that is not empty?
[−>+<] again, the loop of the first figure. Pouring into a cell that already holds something adds to it. Adding is moving.
Taking away is moving with a minus: [−>−<] takes cell 0 off cell 1.
Check yourself
A free exercise
Cell 0 holds 6. Leave twice that, 12, in cell 1. Then try three times. Nothing is checked here:
What you can do now
You can move a value with [−>+<], add by moving into a cell that is not empty, and copy with a scratch cell. No new command came in this lesson: all three are the loop of Lesson 4. Patterns has a page for each, with variations: move, copy and add and subtract.