Search code examples
brainfuck

Prints '+' to the screen 20 times using a loop and arithmetic operators


I have a simple Brainfuck program called "PuraPuraNanya", which prints the character + to the screen 20 times using a loop and arithmetic operators.

++++++++++[>+>+++>++++>+++++<<<<-]>++.

Here are explanations of what the program does:

  • ++++++++++ initializes the value of the current memory cell to 10.
  • [ starts a loop.
  • >+ moves the value of the current memory cell to the next cell and increments it by 1.
  • >+++ moves the value of the current memory cell to the second next cell and increments it by 3.
  • >++++ moves the value of the current memory cell to the third next cell and increments it by 4.
  • >+++++ moves the value of the current memory cell to the fourth next cell and increments it by 5.
  • <<<<- moves the cursor to the first memory cell and decrements its value by 1.
  • ] closes the loop.
  • >++ moves the cursor to the next memory cell and increments its value by 2.
  • . prints the character + to the screen.

I expected the program to print the character + to the screen 20 times. However, when I ran the program, there were no errors and the compiler did not produce the expected output. Can anyone help me check and identify where the mistake is?

Test :


Solution

  • So. The memory starts as all 0s. Before you start the loop, memory is:

    10 0 0 0 0 ...
    

    The > commands don't move values as you said, they only move the pointer. Then you increment some cells. So after the first time through the loop, your memory will be:

    9 1 3 4 5
    

    with the pointer back at the (just decremented) 9. After the second time through,

    8 2 6 8 10
    

    After the 10th iteration of the loop, memory is

    0 10 30 40 50
    

    and the loop terminates because you ended at a 0 (at the leftmost cell).

    Then you move right one cell and increment twice. This makes a 12:

    0 12 30 40 50
    

    Then you output a 12.

    Unfortunately, 12 is the ASCII code for "form feed", a control character and not a printable character. What that looks like will depend on your interpreter/compiler.

    If you wanted to output a + you would want to output a 43 and not a 12. And if you wanted to output it 20 times you would probably want to use a loop to do that; maybe you want one loop to help build a 20 and a 43, and then another loop to output the 43 20 times while decrementing the 20.

    Alternatively, you could just put 43 (+) commands and then 20 (.) commands, and no loops.)