Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write if else statements in Brainfuck

I have just discovered a programming language, which is called Brainfuck.

My question is how to write an if-else statement in Brainfuck?

Is it done by comparing two cells? If yes, then how do I compare two cells in this program?

Thank you

like image 890
The Confused Programmer Avatar asked Sep 05 '17 13:09

The Confused Programmer


People also ask

How do you write the if else condition?

Conditional Statements Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

What is the logic in an IF ELSE statement?

What is an if/else statement. The if/else statement is a logical, conditional expression that evaluates a condition and will only execute the block of code below it, if the condition is true.

Does the else statement have a conditional?

Else statement allows conditional execution based on the evaluation of an expression.


1 Answers

You need a [x,1] structure, where x can either be 0 or something else. the shortest way to explain it is to make a loop where you know that the pointer does not end the loop where it started.

let's say those cells are named cell1 and cell2

You do operations that change the value of cell1 and cell2's value does not change.

After manipulating values, make your pointer point cell1 and then you do your alternatives.

[-]> cell1 = 0
[-]+ cell2 = 1
|manipulations that change cell1 value
|goto to cell1
[                          // if cell1 != 0
    [-]>[-]                // both cell1 and cell2 now equal 0 
                              if you want the loop to end and want to prevent the 
                              next loop from starting
    |do something
    |goto cell1            // Make sure you point again to cell1 to exit the loop
]>[                        // else
    |do something else
    |goto cell1            // Make sure you point again to cell1 to exit the loop
]

In this example, I use // to mark the comments and I use | to mark operations. Losing track of the pointer is your worst enemy, so it might help to separate your code and to put some comments.


Now! to end up answering your question : no you don't compare two cells, you do operations that either result 0 or something else and then you check if that cell == 0.

the operations you do CAN compare two cells, but you have to make your own sequence to do so


Here's the Wikipedia page for Brainfuck where you can see a lot of simple and complex algorithm for Brainfuck, and welcome to the community :)

https://esolangs.org/wiki/Brainfuck_algorithms#if_.28x.29_.7B_code1_.7D_else_.7B_code2_.7D

like image 75
Sirmyself Avatar answered Dec 20 '22 13:12

Sirmyself