A BrainFuck Tutorial from Rich's Bit

Warning: to enjoy this page you will probably need to be either a mathmo, a compsci, a wierdo, criminally insane or all of the above (I can't think of anyone who qualifies for that).

As with all programming languages, you learn best by trying things out. I recommend you try some of the examples out for yourself. You can use my BrainFuck interpreter, WinBF, in its applet form or if you have the Java2 SDK and want file support you can get the WinBF source code from the download page, or there are plenty of other implementations out there. If you are using my version, you may want to turn on Print Tape Trace, which displays the data left on the tape when the program ends.

BF code is shown in blue, pseudo code in green and comments in red.

The basics - moving, adding and multiplying.

One of the most common composite operations in BF is moving a number. Lets say the pointer is at a number that we want to move one cell to the right. Our tools are limited to increment (+), decrement (-) and the brackets [ ], which act like a "while non zero" loop. So we can move a number in pseudo-code like this:

//move A to B
input A
while(cell A non-zero) {
  move to cell B
  increment cell B
  move to cell A
  decrement cell A
output B
which translates compactly to BF:
; [>+<-] > :
Ok - that was faily easy, note that we can use that to add two numbers together - by moving A into B we add the value of A to the value that was previously in B. However this method destroys the value that was initially in cell A. To preserve the value we need to copy it somewhere. To do that we move it to two locations and move one of them back:
//copy A into B
input A
while(cell A non-zero) {
  increment B and C
  decrement A
move C to A
output B
or in BF:
; [>+>+<<-] >> [<<+>>-] < :
Right - now lets go for multiplication. Think of multiplication of A and B as adding A to D, B times.
//multiply A and B into D
input A, B
while(cell B non-zero) {
  copy A into D using C as temp
  decrement B
output D
; > ; [< [>>+>+<<<-] >> [<<+>>-] <-] >> : 
In part 2 - hello world, conditional execution, and much more...

[Part 3 >>>]