Programming Search⌘K

Conceptadvanced

Loop and a half

Also called loop and a half, loop-and-a-half problem, n and a half times loop, middle-exit loop, test in the middle, mid-test loop, exit when, priming read, read loop, fencepost loop.

A loop and a half runs the first part of its body n times and the second part n - 1 times, so its exit test belongs in the middle, written with break or with a read in the condition.

Applies to
core-languages

Idea

Many loops read something, test it, and then use it: read a line, stop at the end of the file, process the line. The read must happen once more than the processing, because the last read finds the end and nothing follows it. A loop like this does its first half n times and its second half n - 1 times. The natural place for the exit test is in the middle of the body, not at the top or the bottom.

# Read numbers until 0 and add them up. The test is in the middle.
data = iter([5, 3, 8, 0, 9])
total = 0
while True:
    x = next(data)  # first half: read
    if x == 0:  # the test
        break
    total += x  # second half: process
print("total:", total)

# The same loop without a break repeats the read before the loop.
data = iter([5, 3, 8, 0, 9])
total = 0
x = next(data)
while x != 0:
    total += x
    x = next(data)
print("total:", total)

# With := the read goes into the condition.
data = iter([5, 3, 8, 0, 9])
total = 0
while (x := next(data)) != 0:
    total += x
print("total:", total)

# A list with separators: the separator goes between items, n - 1 times.
out = ""
for i, item in enumerate(["a", "b", "c"]):
    if i > 0:
        out += ", "
    out += item
print(out)
Output
total: 16
total: 16
total: 16
a, b, c

The three loops compute the same sum and stop at the 0, so the 9 after it is never read. The first loop has its test in the middle and a break. The second has the test at the top, so it must read once before the loop and again at the end of the body: the read appears twice. The third puts the read into the condition with :=. The last loop shows the same shape in output: three items need two separators.

How it works

The problem. "Common loop structures sometimes result in duplicated code, either repeated statements or repeated conditions"1. "A common case is where the start of the loop is always executed, but the end may be skipped on the last iteration"1. Dijkstra called it a loop that is performed "n and a half times"1. Typical cases are "reading data in the first part, checking for end of data, and then processing the data in the second part; or processing, checking for end, and then preparing for the next iteration"1. "In these cases, the first part of the loop is executed n times, but the second part is only executed n−1 times"1.

Four solutions.

  1. Repeat the first half. Read once before a while loop and again at the end of the body. This is the priming read of the second loop in the example. It works with a plain while loop, but the read appears in two places, and a later change can update one copy and not the other.
  2. Test in the body with a flag or an if. A conditional "inside the loop (possibly duplicating the condition but not the statements)"1 avoids a second copy of the code, but the loop tests the same thing twice.
  3. Exit in the middle with break. "Since the 1990s this has been the most commonly taught solution, using a break statement"1: loop, the first half, if condition break, the second half, repeat. Ada has a statement for it: exit when X = 0;1.
  4. Move the first half into the condition. If the first half is a single read, an assignment in the loop condition does it: while ((c = getchar()) != EOF) in C, while (line := f.readline()) in Python, while (reader.ReadLine() is { } line) in C# and while let Some(x) = it.next() in Rust.

The reversed condition. With break, the test is the condition to stop, not the condition to go on. "A subtlety of this solution is that the condition is the opposite of a usual while condition: rewriting while condition ... repeat with an exit in the middle requires reversing the condition: loop ... if not condition exit ... repeat"1.

Assignment expressions in Python. Python did not allow an assignment in a condition until PEP 572 added :=. The PEP labels the use # Loop-and-a-half and gives the example while (command := input("> ")) != "quit":2. It also rewrites a loop from the standard library that started with while True: line = fp.readline() if not line: break as while line := fp.readline():2.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiomTypeScript uses the forms of JavaScript, an endless loop with break or an assignment in the condition. No example file exists.
GoIdiom
RustIdiom
KotlinIdiomKotlin uses while (true) with break, because an assignment is not an expression in Kotlin. No example file exists because kotlinc is not installed.
SQLIdiomA query has no loops. A cursor loop in PL/pgSQL fetches a row, leaves with EXIT WHEN NOT FOUND, and then processes the row.
BashIdiomIn while IFS= read -r line, the read command is the condition, and its exit status ends the loop at the end of the input. No example file exists.
PowerShellIdiomPowerShell uses while ($true) with break in the middle of the body. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no loops.
CSSDoes not applyCSS has no loops.
Regular expressionsDoes not applyA regular expression has no loops with a body.
Language Verdict Mechanism
Python idiom while True: with if ...: break; while (x := read()) != end:; iter(f, sentinel)
JavaScript idiom while (true) or for (;;) with break; an assignment in the condition
TypeScript idiom the forms of JavaScript
Java idiom while (true) with break; while ((line = r.readLine()) != null)
Kotlin idiom while (true) with break; generateSequence with takeWhile
C# idiom while (true) with break; while (r.ReadLine() is { } line)
Go idiom for { ...; if done { break }; ... }; for scanner.Scan() { }
Rust idiom loop with break; let ... else { break }; while let Some(x) = it.next()
C idiom for (;;) with break; while ((c = getchar()) != EOF)
C++ idiom while (std::getline(in, line)) and while (in >> x); for (;;) with break
Bash idiom while IFS= read -r line; do ...; done; the read is the condition
PowerShell idiom while ($true) with break
SQL idiom no loops in queries; a cursor loop in PL/pgSQL uses FETCH and EXIT WHEN NOT FOUND
Regex n/a no loops
HTML n/a no loops
CSS n/a no loops

Few languages have a loop statement with the test in the middle, so all the rows are idioms. Ada has exit when, and Dahl proposed a loop ... while ... repeat statement in 1972. The languages differ in how much of the first half can move into the condition: C, C++, Java, C#, Go, Rust and Python allow an assignment or a binding there, and the stream and scanner types of C++ and Go return a value that the condition tests.

The example files show these differences. Python loops with iter(callable, sentinel) and asks for input again until it is valid. JavaScript puts separators between items and reads commands up to a stop word. Java reads lines with a break and with an assignment in the condition. C# retries int.TryParse and reads lines with a pattern in the condition. Go reads with ReadString up to io.EOF and with a Scanner. Rust uses loop with let ... else and joins items with a first element taken out. C parses numbers with strtol and stops in the middle. C++ reads lines in the condition and joins them with a changing separator.

PythonGitHub
import io

f = io.StringIO("10\n20\nend\n30\n")
# iter(callable, sentinel) calls readline until it returns the sentinel.
for line in iter(f.readline, "end\n"):
    print("got", line.strip())

# Ask, test, then complain and ask again.
answers = iter(["abc", "-4", "7"])
while True:
    text = next(answers)
    if text.isdigit():
        break
    print("not a positive number:", text)
print("accepted", int(text))
Output
got 10
got 20
not a positive number: abc
not a positive number: -4
accepted 7
  • Verdict: idiom. iter(f.readline, "end\n") turns the read and the test into an iterator, so a plain for loop does the loop and a half with no break. The prompt loop reads 3 times and complains 2 times, with the break in the middle of the body.
#include <print>
#include <sstream>
#include <string>
#include <vector>

int main() {
    // getline returns the stream, which converts to false at the end.
    std::istringstream in("north\nsouth\n\neast\n");
    std::string line;
    std::vector<std::string> seen;
    while (std::getline(in, line) && !line.empty())
        seen.push_back(line);

    // A separator that is empty for the first item.
    std::string out;
    const char* sep = "";
    for (const auto& s : seen) {
        out += sep;
        out += s;
        sep = " -> ";
    }
    std::println("{}", out);
    std::println("rest: {}", std::getline(in, line) ? line : "none");
}
Output
north -> south
rest: east
  • Verdict: idiom. std::getline reads a line and returns the stream, and the stream converts to false at the end of the input, so the read and the test sit in one condition. The loop also stops at the blank line, and east stays in the stream. The separator starts empty and changes after the first item, so it appears between the items only.
JavaGitHub
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class Main {
    public static void main(String[] args) throws IOException {
        // Read, test, process: the exit is in the middle.
        BufferedReader in = new BufferedReader(new StringReader("3\n4\n\n5\n"));
        int sum = 0;
        while (true) {
            String line = in.readLine();
            if (line == null || line.isEmpty()) {
                break;
            }
            sum += Integer.parseInt(line);
        }
        System.out.println("sum before the blank line: " + sum);

        // The read moves into the condition with an assignment.
        BufferedReader in2 = new BufferedReader(new StringReader("ab\ncde\n"));
        String line;
        int count = 0;
        while ((line = in2.readLine()) != null) {
            count += line.length();
        }
        System.out.println("characters: " + count);
    }
}
Output
sum before the blank line: 7
characters: 5
  • Verdict: idiom. The first loop declares line inside the body and leaves with break at the end of the input or at a blank line, so the 5 after the blank line is not added. The second loop puts the read into the condition, which needs line to be declared before the loop.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    /* for (;;) with the exit in the middle: parse, test, add. */
    const char *s = "12 7 30 x 5";
    char *end;
    long sum = 0;
    for (;;) {
        long v = strtol(s, &end, 10);
        if (end == s)
            break; /* no number was read */
        sum += v;
        s = end;
    }
    printf("sum: %ld, stopped at \"%s\"\n", sum, s);

    /* The read in the condition, in the style of while ((c = getchar()) != EOF). */
    const char *p = "a bc def";
    int c, letters = 0;
    while ((c = *p++) != '\0') {
        if (c != ' ')
            letters++;
    }
    printf("letters: %d\n", letters);
    return 0;
}
Output
sum: 49, stopped at " x 5"
letters: 6
  • Verdict: idiom. strtol reads a number and sets end to the first character it did not use. If end equals the start, no number was read, and the loop leaves in the middle, before it adds anything. The second loop reads a character and tests it in one condition, the form of the classic getchar loop. The parentheses around the assignment matter, because != binds tighter than =.
var inputs = new Queue<string>(new[] { "ten", "", "42" });
int value;
while (true)
{
    string text = inputs.Dequeue();
    if (int.TryParse(text, out value)) break;
    Console.WriteLine($"not a number: \"{text}\"");
}
Console.WriteLine($"value: {value}");

// The pattern { } matches any non-null value and names it.
var reader = new StringReader("alpha\nbeta\n");
while (reader.ReadLine() is { } line)
    Console.WriteLine($"line: {line}");
Output
not a number: "ten"
not a number: ""
value: 42
line: alpha
line: beta
  • Verdict: idiom. The retry loop reads, tests with TryParse and complains only when the test fails, so it reads 3 times and complains 2 times. The compiler knows that value is assigned after the loop, because the only exit is the break after TryParse. In the second loop, is { } line reads, tests for null and names the line in one condition.
JavaScriptGitHub
// Process, test, prepare: a list with separators between the items.
const items = ["x", "y", "z"];
let out = "";
let i = 0;
while (true) {
  out += items[i];
  i++;
  if (i === items.length) break;
  out += " | ";
}
console.log(out);

// Read commands until "stop".
const queue = ["ls", "cd", "stop", "rm"];
const done = [];
for (;;) {
  const cmd = queue.shift();
  if (cmd === "stop") break;
  done.push(cmd);
}
console.log(done.join(","), "left:", queue.join(","));
Output
x | y | z
ls,cd left: rm
  • Verdict: idiom. JavaScript has no middle-test loop, so both loops are endless loops with a break in the middle. The first adds an item 3 times and a separator 2 times. It assumes at least one item: with an empty list it would add undefined. items.join(" | ") does the same job in one call.
package main

import (
	"bufio"
	"fmt"
	"io"
	"strconv"
	"strings"
)

func main() {
	// for with the test in the middle: read, test, process.
	r := bufio.NewReader(strings.NewReader("one\ntwo\n"))
	for {
		line, err := r.ReadString('\n')
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error:", err)
			return
		}
		fmt.Println("line:", strings.TrimSuffix(line, "\n"))
	}

	// Scan reads and reports success, so the read is the condition.
	sc := bufio.NewScanner(strings.NewReader("3 4 5"))
	sc.Split(bufio.ScanWords)
	sum := 0
	for sc.Scan() {
		n, err := strconv.Atoi(sc.Text())
		if err == nil {
			sum += n
		}
	}
	fmt.Println("sum:", sum)
}
Output
line: one
line: two
sum: 12
  • Verdict: idiom. Go writes the middle exit as an endless for with break. ReadString returns io.EOF with an empty string after the last newline, but if the input ended without a newline, it would return the last line and io.EOF together, and this loop would drop that line. Scanner hides the problem: Scan reads the next token and returns false at the end.
RustGitHub
fn main() {
    // loop with the exit in the middle: read, test, process.
    let mut input = "7\n2\nstop\n9".lines();
    let mut sum = 0;
    loop {
        let Some(line) = input.next() else { break };
        if line == "stop" {
            break;
        }
        sum += line.parse::<i32>().unwrap();
    }
    println!("sum: {sum}");
    println!("left: {:?}", input.collect::<Vec<_>>());

    // Separators between the items: take the first item out of the loop.
    let items = ["a", "b", "c"];
    let mut out = String::new();
    let mut it = items.iter();
    if let Some(first) = it.next() {
        out.push_str(first);
        for item in it {
            out.push_str(", ");
            out.push_str(item);
        }
    }
    println!("{out}");
}
Output
sum: 9
left: ["9"]
a, b, c
  • Verdict: idiom. loop has two exits in the middle: let ... else { break } at the end of the input and break at the stop word, so 9 stays unread. The join takes the first item out of the loop, so each pass of the for adds a separator and then an item. items.join(", ") does the same in one call.
  • Middle-test statements. Dahl's structure has the form loop, the first half, while test;, the second half, repeat. "If xxx1 is omitted, we get a loop with the test at the top (a traditional while loop). If xxx2 is omitted, we get a loop with the test at the bottom, equivalent to a do while loop in many languages"1.
  • Sentinel values. Many read loops stop at a special value, such as 0, an empty line or the end of the file. Python's iter(callable, sentinel) makes an iterator from a read function: it calls the function each time, and "if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned"3. A for loop over this iterator is a loop and a half with no break.
  • Joining with separators. The separator between items is the second half of a loop and a half. A join function, such as ", ".join(items) in Python, hides the loop.
  • Input validation. A loop that asks for input, tests it, and complains and asks again is a loop and a half: it asks n times and complains n - 1 times.

Pitfalls

  • Two copies of the first half. With a priming read, a change to one read and not to the other gives a loop that processes the wrong data. Use break or an assignment in the condition.
  • The negated test. The break test stops the loop, so it is the negation of the while condition. Check it with the last item and with an empty input.
  • Several exits. Each break is another way out of the loop, and a reader must check all of them. Keep one exit where possible.
  • The last partial item. A read can return data and the end of the input at the same time, as ReadString does in Go when the last line has no newline. Process the data before the test, or test for both.
  • Assignment instead of comparison. In C, while (c = getchar() != EOF) assigns the result of the comparison to c, because != binds tighter than =. Write while ((c = getchar()) != EOF).

Cost

A loop and a half costs the same as the other loops: one test and one jump for each pass. The break form and the condition form compile to almost the same code. The choice is about reading and maintenance: the duplicated read is the only form that adds code, and it adds no speed.

History

"This problem has been recognized at least since 1967 by Knuth, with Wirth suggesting solving it via early loop exit"1. Dijkstra gave it its name. "The following structure was proposed by Dahl in 1972"1: a loop with a while test in the middle, which "allows clear loop-and-a-half logic"1. Most languages chose break instead of a new statement, and C, and later Python with PEP 572, allowed the read to move into the loop condition.

References

  1. Control flow, Wikipedia, Loop-and-a-half problem; Early exit; Middle test
  2. PEP 572, Assignment Expressions, Capturing condition values; Examples from the Python standard library
  3. Built-in Functions, The Python Standard Library, iter

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/HVVV9Y/text.yaml