Jump to content

Brainfuck programming language/Examples

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 130.94.161.238 (talk) at 03:25, 20 May 2002. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Character I/O
,.
Take one character from the keyboard and output it to the screen.

Simple loop
,[.,]
A continuous loop that takes keyboard input and echoes it to the screen. Note that this assumes 0 to signal the end of input; implementations vary on this point. A version assuming a -1 to signal end of input would be
,+[-.,+]
and one assuming that the current byte stays unchanged on end of input would be
,[.[-],]

Pointer manipulation
,[.>,]
a continuous loop that puts keyboard input into our pointer, outputs it to the screen, then increments our pointer location. This has an advantage over the previous loop, because it is saving our keystrokes into the character array for some theoretical future use. The loop before simply overwrote the same initial byte in the array because it never moved the pointer. Again, this version assumes a 0 to signal end of input.

Additional examples here

Conditional statements
,----------[----------------------.,----------]
This will take lowercase input from the keyboard and make it uppercase. To exit, press press the enter key. Lets look at this program. Pretty long for such a simple task, and it doesn't even do any data validation! the bulk of the visible work it's doing is subtracting 32 from the pointer reference before its output. This is because ASCII uppercase letters are offset -32 from lowercase. But let's look at the whole thing.

First, we input the first character using the (,) and immediately subtract 10. ASCII 10 is the line feed. If the user hit enter, the next command, a loop declaration ([) will not run because we effectively set our pointer ref to zero! Let's examine what happened if the user didn't hit enter, and pressed a valid lowercase letter: So the internal code block is run--first, it decrements the pointer reference by 22. This is because we have already decremented our value by 10. 10 + 22 equals 32. We have changed our value to uppercase.

Next we output it. Now we input the next character, and again subtract 10. If this character was a linefeed, we exit the loop; otherwise, we go back to the start of the loop, subtract another 22, output, and so on.

See also : Brainfuck programming language