Dan Forbes - 2 months ago 5
Brainfuck Question

# Hello, World! in Brainfuck

The following code snippet is from Wikipedia, and is the preamble to what seems to be the standard Hello World! program in Brainfuck...

1. +++++ +++++ initialize counter (cell #0) to 10
2. [ use loop to set the next four cells to 70/100/30/10
3. > +++++ ++ add 7 to cell #1
4. > +++++ +++++ add 10 to cell #2
5. > +++ add 3 to cell #3
6. > + add 1 to cell #4
7. <<<< - decrement counter (cell #0)
8. ]

I understand the gist of what's going on here, but what I don't understand is the mechanics of what's happening on lines 3 through 6. If
+++++ +++++
adds 10 to the value in
a[0]
, why does incrementing the pointer by one and executing
++*ptr
seven times result in
a[1]
equalling 70? Shouldn't
a[1] = 7
? It seems like
a[1]
through
a[4]
are magically being increased by a factor of ten, and I don't understand why.

The [] characters indicate a loop. The 10 +s before it indicate how many times the loop will run. This becomes clear when you understand what the various commands mean, and the <<<< - sequence of commands.

Each time the loop runs, it executes the following steps:

> move the pointer 1 space to the right
+++++ ++ add 7 to the current pointer
etc 3 more times > > >
<<<< - move back to the counter and decrement

This has the effect of adding "7, 10, 3, 1" 10 times. To put it another way, if you write the values at the first 5 pointer locations as you run the loop like they're in an array:

[10, 0, 0, 0, 0]     at first
[9, 7, 10, 3, 1]     after first run
[8, 14, 20, 6, 2]    after second
...
[0, 70, 100, 30, 10] up to this, the loop ends since the counter is 0,
and control continues
Source (Stackoverflow)