Code patternsControlWhile
While
Repeats a piece of program as long as a condition holds.
Watch it run
The form “Until a newline” works on 2 cells, named “letter” and “count”. Press Play, drag the step slider forwards and back, or edit the line:
The figure needs JavaScript. The program below is the result for the example values.
A loop tests one cell, at its start and again at its end. A "while" works the condition out into that cell before the loop, and works it out again as the last thing in the body.
Here the condition is "the letter just read is not a newline". Taking 10 off the letter makes a newline zero, and zero is what the loop can see.
The code
This is the program the figure ran. It is brainfuck as it stands: copy it, or open it in the playground, where you can change it:
,----------[>+<,----------]
What it needs
- The condition must be in the cell under the pointer when the body ends.
- First form: the input must contain a newline, and the cells must wrap (0 − 10 has to be a number).
- Any cell size that wraps.
Common mistakes
- Working out the condition only once, before the loop. The closing bracket then tests an old value.
- Input that ends without a newline: with "0 at the end of input" the first form never sees a zero and reads for ever. The stepper adds the newline for you.
What it costs
A plain step is one command. An optimised step is one step of an interpreter that folds runs of the same command and flat loops. Choose the values and watch the two bars; What costs what explains how cost is counted:
The figure needs JavaScript. The table below has the measured steps.
Cost as a formula, and measured
| Form | Plain steps | Optimised steps |
|---|---|---|
| Until a newline | 12 + 15 per letter | 3 + 4 per letter |
| Until the end of the input | 2 + 5 per letter | 2 + 3 per letter |
| Form | Values | Bits | Characters | Plain steps | Optimised steps |
|---|---|---|---|---|---|
| Until a newline | the line = "" | 8 | 27 | 12 | 3 |
| Until a newline | the line = "hello" | 8 | 27 | 87 | 23 |
| Until the end of the input | the input = "hello" | 8 | 7 | 27 | 17 |
Other forms
Until the end of the input
Counts all letters. Works where , gives 0 at the end of the input.
,[>+<,]
Run this form step by step
The form “Until the end of the input” works on 2 cells, named “letter” and “count”. Press Play, drag the step slider forwards and back, or edit the input:
The figure needs JavaScript. The program below is the result for the example values.
Where it is used
- Read a line into memory is this loop with "store the letter" as its body.
- A counted loop is the special case "while the counter is not zero".
Sources
- Source: Esolang wiki: Brainfuck algorithms: sections "while (x) { code }" and "Read until newline".
Every program on this page was run on many inputs, in plain and in optimised mode, and compared with JavaScript. The explanations are written for this page.