Lesson 3
Loops in brainfuck
[ jumps past its matching ] when the cell under the pointer is zero; ] jumps back to its [ when it is not. That is the only control flow brainfuck has.
The lesson
In this implementation, reading past the end of the input gives 0. So ,[.,] copies the whole input. It prints, reads again and stops on 0.
Brainfuck has its own page, and Run opens this example in the editor.
Example
Output
Exercise 1
Print every input byte plus one (HAL becomes IBM).
Run tries your program on the input below. Check runs it on every test.
| Input | Expected output |
|---|---|
HAL | IBM |
hello | ifmmp |
abc xyz | bcd!yz{ |
Output
A hint
Start from the copy loop and change one byte before printing.
One answer
Answer: Print every input byte plus one (HAL becomes IBM).
Expected output
IBM
| Input | Expected output |
|---|---|
HAL | IBM |
hello | ifmmp |
abc xyz | bcd!yz{ |
Output
Exercise 2
Print every input byte twice (ab becomes aabb).
Run tries your program on the input below. Check runs it on every test.
| Input | Expected output |
|---|---|
ab | aabb |
hello | hheelllloo |
x y | xx yy |
Output
A hint
Printing does not change the cell, so print it again.
One answer
Answer: Print every input byte twice (ab becomes aabb).
Expected output
aabb
| Input | Expected output |
|---|---|
ab | aabb |
hello | hheelllloo |
x y | xx yy |
Output