Friday, 17 November 2017

Brainfuck: Sum of two numbers

Read two numbers from user and print the sum of those numbers.

How to read input from user?
‘,’ command is used to read the input from user.

How to calculate the sum of two numbers?
First of all when you read the input from user, it is stored in the cells as ASCII number.

Decimal Number
ASCII Equivalent
0
48
1
49
2
50
3
51
4
52
5
53
6
54
7
55
8
56
9
57

By subtracting the ASCII equivalent of a number with 48 we can get the actual number.
0 = 48 – 48
1 = 49 – 48
2 = 50 – 48
3 = 51 – 48
4 = 52 – 48
5 = 53 - 48
6 = 54 - 48
7 = 55 - 48
8 = 56 – 48
9 = 57 – 48

After reading the two numbers, we should make them to their decimal equivalents.

I already explained how to do that in my previous post.

,                # Read first number    
>                # Move the data pointer to next cell
,                # Read the second number
>                # Move the data pointer to third cell 

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

# Sum the numbers
<                  # Move the pointer from 3rd cell to 2nd cell
[
  -
  <
  +
  >
]

# Move to 1st cell and print the sum
< .




Previous                                                 Next                                                 Home

No comments:

Post a Comment