LearnBrainfuck basics

Making a decision

By the end of this lesson you can make a program do something only if a cell is not zero, and something else if it is.

Only if there is something

Here is a small program with a box for its input, which starts as the letter a. Press Play, then empty the box and press Play again:

Is it a zero?

This program prints the letter N, unless the digit it reads is 0. Its first 48 commands are minus signs. Press Play with the input 5, then change the input to 0 and press Play again:

Or else

This program prints 1 if there is input. Write the missing part, so that it prints 0 if there is none. The words in it are comments, which the machine skips. Empty the input box to try the case without input:

Not for zero

Now use both ideas together. Write a program that reads one digit and prints an exclamation mark (number 33), but not if the digit is 0. It is tried with 5, with 0 and with 9:

Check yourself

A free exercise

Read two characters and print an exclamation mark only if they differ. Take one off the other first. Harder: print = only if they are the same, which needs a flag. Nothing is checked here:

What you can do now

You can turn a comparison into the question is this cell zero?, run a part of a program only if a cell is not zero, and use a flag for or else. These are the pieces of this lesson:

The pieces of Lesson 8.
PieceWhat it does
[ … [−]]Run the part in between once if the cell is not zero, and skip it if the cell is zero. The [−] at the end empties the cell, so the loop does not go round again.
Take a number off, then [Ask whether a cell held that number: it is zero now only if it did.
A flag cellSet a second cell to 1, clear it inside the first part, and ask about it with a second pair of brackets. That is or else.

The Patterns have these shapes ready to use: if, if ... else and equal? The single question also has a price when the numbers get large; Lesson 4 of Build toward a chatbot shows it.

You now know every part a program is made of. In Lesson 9 you put them together into a program of your own.