Section 1.2
Changing Pointer Position
It would be pretty boring if we could only manipulate data within one cell. Brainfuck operates on a pseudo-infinite tape, meaning that we can switch from one pointer over to the other. Intuitively, >
shifts the pointer one cell to the right and <
shifts the pointer one cell to the left.
The code +>+>+>
applied to a blank initialized tape…
A blank initialized tape.
...[0][0][0][0][0][0][0]...
^
…yields the following tape after execution.
A manipulated tape.
...[0][0][0][1][1][1][0]...
^
Say we wanted to store the ASCII codes for the digits 0 through 9 so we can sweep through and print them conveniently. Recall that the ASCII code for the digit 0 is 48.
Storing ASCII codes for the digits 0 through 9 in contiguous cells.
++++++++++
++++++++++
++++++++++
++++++++++
++++++++
>
++++++++++
++++++++++
++++++++++
++++++++++
+++++++++
>
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
>
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
+
>
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++
>
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
+++
>
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++
>
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
+++++
>
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++
>
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
+++++++
State of the tape after execution.
...[48][49][50][51][52][53][54][55][56][57][0][0][0]...
^
Say we wanted to print out all the numbers in ascending order, then descending order, then ascending order again (and descending order again for good measure). Rather than needing to increment and decrement repeatedly, all the ASCII codes are stored in our tape. We only need to move the pointer around appropriately and print.
- Move the pointer left 9 times until it points to the cell containing 48 (the ASCII code for the digit 0).
- Print the current cell value and move the pointer right. Repeat 9 times until the pointer points to the cell containing 57 (the ASCII code for the digit 9).
- Print the current cell value and move the pointer left. Repeat 9 times until the pointer points to the cell containing 48.
- Print the current cell value and move the pointer left. Repeat 9 times until the pointer points to the cell containing 57.
- Print the current cell value and move the pointer left. Repeat 9 times until the pointer points to the cell containing 48.
We can translate this into Brainfuck code:
<<<<<<<<<
.>.>.>.>.>.>.>.>.>
.<.<.<.<.<.<.<.<.<
.>.>.>.>.>.>.>.>.>
.<.<.<.<.<.<.<.<.<
Running this complete code yields the following output.
012345678987654321012345678987654321