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:

,----------[>+<,----------]
Open in the playground27 characters

What it needs

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
Table 1. The cost as a function of the values. Exact formulas are checked on every case they run.
FormPlain stepsOptimised steps
Until a newline12 + 15 per letter3 + 4 per letter
Until the end of the input2 + 5 per letter2 + 3 per letter
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
Until a newlinethe line = ""827123
Until a newlinethe line = "hello"8278723
Until the end of the inputthe input = "hello"872717

Other forms

Until the end of the input

Counts all letters. Works where , gives 0 at the end of the input.

,[>+<,]
Open in the playground7 characters
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

Sources

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.