Friday 17 November 2017

Brainfuck: Double a number

Below snippet double the number 3.
+++                #Initialize the cell with number
[
 >                 # Move to next cell
 ++                # Increment the cell by 2
 <                 # Move to previous cell
 -                 # Decrement the cell value by 1
]                  # Repeat this step until the first cell is 0
>.                 # Go to second cell and print the value

What if you want to read a number from user and double it. Procedure is straight forward. First you read the number, Since the number stored in ASCII format, convert the ASCII value to decimal. Follow above same steps.


Below logic double the number.
,                #Initialize the cell with number

# Logic to convert ASCII numbers to their decimal format
>
++++++++         # Init second cell to 8 
[
 -
 <
 ------
 >
]

# Double the number
<
[
 >                 # Move to next cell
 ++                # Increment the cell by 2
 <                 # Move to previous cell
 -                 # Decrement the cell value by 1
]                  # Repeat this step until the first cell is 0


Previous                                                 Next                                                 Home

No comments:

Post a Comment