It
is time to write first application in Brainfuck.
Problem: Print numbers from 0
to 9.
Approach 1
Let
me start with naïve approach.
By
default, all the array cells are initialized with 0.
Final
output should be like below.
As
per ASCII table, decimal number 48 represents 0, 49 represent 1 etc.,
Number
|
ASCII equivalent
|
0
|
48
|
1
|
49
|
2
|
50
|
3
|
51
|
4
|
52
|
5
|
53
|
6
|
54
|
7
|
55
|
8
|
56
|
9
|
57
|
To
get the output, we should fill the 0th cell with 48, 1st
cell with 49, 2nd cell with 50 etc.,
‘+’
command is used to increment the value of the cell by 1.
‘.’
Is used to print the value at the current cell.
‘>’
command is used to move the data pointer to once cell right.
48
+’s make the cell value to 48. After that we can print the value and move to
next cell. Do 49 +’s to make the cell value to 49, next print the value and
move to next cell, repeat this procedure for next 8 times.
Find
the below working application.
++++++++++++++++++++++++++++++++++++++++++++++++
.
>
+++++++++++++++++++++++++++++++++++++++++++++++++
.
>
++++++++++++++++++++++++++++++++++++++++++++++++++
.
>
+++++++++++++++++++++++++++++++++++++++++++++++++++
.
>
++++++++++++++++++++++++++++++++++++++++++++++++++++
.
>
+++++++++++++++++++++++++++++++++++++++++++++++++++++
.
>
++++++++++++++++++++++++++++++++++++++++++++++++++++++
.
>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
.
>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.
>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.
Output
0123456789
Approach2
To
print the values from 0 to 9, we should fill the cells like below.
48
|
49
|
50
|
51
|
52
|
53
|
54
|
55
|
56
|
57
|
We
can perform the operation using looping.
Step 1: First let us
initialize the counter (first cell) to 10.
‘++++++++++’ initialize first cell to 10.
Step 2: By using the loop [],
fill all the cell values to 50.
[
> +++++ Fill each cell with 5
> +++++
> +++++
> +++++
> +++++
> +++++
> +++++
> +++++
> +++++
> +++++
<<<<<<<<<< - Move the data pointer to 0th cell
]
After
this step, array looks like below.
50
|
50
|
50
|
50
|
50
|
50
|
50
|
50
|
50
|
50
|
Step 3: We need to convert
above table to print 0 to 9. First cell has value 50, we should decrement by 2 to make it 48.
Apply
the same procedure for all other cells.
Find
the below working application.
++++++++++ initialize counter (cell #0) to 10
[
> +++++ Fill each cell with 5
> +++++
> +++++
> +++++
> +++++
> +++++
> +++++
> +++++
> +++++
> +++++
<<<<<<<<<< - Move the data pointer to 0th cell
]
All the cells has value 50
> --
.
> -
.
>
.
> +
.
> ++
.
> +++
.
> ++++
.
> +++++
.
> ++++++
.
> +++++++
.