Programming in Brainfuck

Your First Program

Just to review, the Brainfuck instructions are:

Lets start off with a simple program:

[-]
Which is equivalent to:
while(a[p]) {
    a[p]--;
}
This will keep decrementing the byte at the pointer until it reaches zero. This is how to set the byte at the pointer to zero. However, as all bytes in the array start off equal to zero, this code actually doesn't do much as a standalone program. Let's give the loop something to work on:
++++++++++[-]
Which is equivalent to:
p += 10;
while(a[p]) {
    a[p]--;
}
The string of +'s increments the byte at the pointer ten times (one for each +) and then the loop keeps decrementing it until it reaches zero.

Of course, we can't see that it's doing anything, so let's write a program that actually does something we can see:

++++++++++++++++++++++++++++++++[>+>+<<-]
>>+++++++++++++++++++++++++<<
++++++++++[>>.-<.<-]
Which is equivalent to:
p+=32;
while(a[p]) {
    p++;
    a[p]++;
    p++;
    a[p]++;
    p-=2;
    a[p]--;
}

p+=2;
a[p]+=25;
p-=2;

p+=10;
while(a[p]) {
    p+=2;
    putchar(array[p]);
    a[p]--;
    p--;
    putchar(array[p]);
    p--;
    a[p]--;
}
Obviously, this program counts down from nine to zero (it is obvious, isn't it???) and breaks down as follows:
++++++++++++++++++++++++++++++++[>+>+<<-]
As we output characters via ASCII value, the 32 +'s set a[0]=32, the ASCII value for a space. The loop ([>+>+<<-]) then copies the value from a[0] to a[1] and a[2] by moving to and incrementing each respectively before moving back to a[0] and decrementing it. When a[0] reached zero, both a[1] and a[2] will equal 32 and p is back at zero.
>>+++++++++++++++++++++++++<<
Here, we increment p twice, putting us at a[2], then increment a[2] 25 times, leaving it with a value of 57, the ASCII Value for the character 9, and then decrement p twice, putting us back at a[0].
++++++++++[>>.-<.<-]
Now we increment a[0] 10 times, leaving it with a value of 10 and enter a loop ([>>.-<.<-]) which increments p by two (putting us at a[2]), prints out the character equal to the value there, decrements a[2], decrements p (putting us at a[1]), prints out the character equal to the value there, decrements p (putting us back at a[0]) and decrements it's value.

In short, the program sets a[0]=10, a[1]=32, and a[2]=57. It then loops, printing a[2] (characters 9 through 0) followed by a[1] (a space) and decrementing a[0] and a[2] each iteration. The same program in C might look like:

cntr=10;
space=32;
num=57;
while(cntr) {
    putchar(num);
    putchar(space);
    num--;
    cntr--;
}
But honestly, isn't the Brainfuck version much more fun? :)

"Oh yea, loads of fun. I can't wait to see what's next."

Next? Hmmm... How about getting some input? Click here for some examples of input processing.


Home | Introduction | First Program | Input Processing | Building Blocks | Resources | bf2pl

cydathria dot com