Programming Search⌘K

Conceptintro

While loop

Also called while loop, while statement, pre-test loop, condition-controlled loop, indefinite loop, entry-controlled loop, while let, until loop, sentinel loop.

A while loop tests a condition before each pass and runs its body while the condition is true. It fits loops whose number of passes is not known at the start.

Applies to
core-languages

Idea

Some loops cannot know their count in advance: read input until it ends, retry until a request works, halve a number until it reaches 1. A while loop states only the condition to go on. It tests the condition, runs the body if the condition is true, and tests again.

# The number of passes is not known before the loop starts.
n, steps = 27, 0
while n != 1:
    n = n // 2 if n % 2 == 0 else 3 * n + 1
    steps += 1
print("27 reaches 1 after", steps, "steps")

# The condition is tested first, so the body can run zero times.
count = 0
while count > 0:
    count -= 1
print("no pass:", count)

# A while loop that empties a list from the end.
stack = [1, 2, 3]
while stack:
    print("pop", stack.pop())

# while ... else: the else part runs when the condition becomes false.
k = 3
while k > 0:
    k -= 1
else:
    print("done, k =", k)
Output
27 reaches 1 after 111 steps
no pass: 0
pop 3
pop 2
pop 1
done, k = 0

The first loop follows the Collatz rule from 27, and nobody can tell from the code how many passes it needs: the answer is 111. The second loop shows the main property of a while loop: the condition is false at the start, so the body never runs. The third loop runs while the list is not empty, and each pass makes the list shorter. The last loop uses the else clause of Python, which runs when the condition becomes false.

How it works

Test, then run. Wikipedia calls this form a pre-test loop: "the condition is checked and if it holds the body is executed. Afterwards, the condition is checked again, and if it holds the body is executed again"1. Python's while statement "repeatedly tests the expression and, if it is true, executes the first suite"2. MDN says the same for JavaScript: "The condition is evaluated before executing the statement"3. Because the test comes first, C# notes that "a while loop executes zero or more times"4.

The condition is tested once for each pass. The loop does not watch its condition all the time. Wikipedia names a "common misconception", namely "that the execution of the body terminates as soon as the condition does not hold anymore"1. If the body makes the condition false in its first line, the rest of the body still runs, and the loop ends only at the next test.

The condition must change. A while loop ends only when something in the body, or outside the program, makes the condition false. A loop over input reads one more item in each pass, a search moves its position, and a numeric method improves its estimate. If nothing changes, the loop is an infinite loop.

Forms in the languages.

  • C, C++, Java, C# and JavaScript write while (condition) body. Java and C# require a Boolean condition, and C and C++ accept any scalar, where 0 is false.
  • Go has no while keyword. A for with only a condition is the while loop: it runs "as long as a boolean condition evaluates to true. The condition is evaluated before each iteration"5.
  • Rust has while and while let. "A while loop expression allows repeating the evaluation of a block while a set of conditions remain true"6, and while let Some(y) = x.pop() runs while the pattern matches. The Rust book explains why while exists although loop, if and break can do the same: "this pattern is so common that Rust has a built-in language construct for it, called a while loop"7.
  • Bash runs a command as the condition. while executes the body "as long as test-commands has an exit status of zero", and until executes it "as long as test-commands has an exit status which is not zero"8.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the while loop of JavaScript, and a type test in the condition narrows the type in the body. No example file exists.
GoNative
RustNative
KotlinNativeKotlin has while (condition) with a Boolean condition. No example file exists because kotlinc is not installed.
SQLIdiomA query has no loops. T-SQL and PL/pgSQL have a WHILE loop in procedures.
BashNativeBash runs the body of while as long as a command succeeds, and the body of until as long as it fails. while read -r line reads a file line by line. No example file exists.
PowerShellNativePowerShell has while (condition). No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is a markup language and has no loops.
CSSDoes not applyCSS has no loops.
Regular expressionsDoes not applyA regular expression has no state to test. A quantifier such as * repeats a pattern as long as it matches.
Language Verdict Mechanism
Python native while condition: with an optional else; := reads and tests in one condition
JavaScript native while (condition) on a truthy or falsy value
TypeScript native the while loop of JavaScript; the condition narrows types in the body
Java native while (condition) with a boolean or Boolean condition
Kotlin native while (condition) with a Boolean condition
C# native while (condition) with a bool condition
Go native for condition { } with no while keyword
Rust native while condition { } and while let pattern = expr { }
C native while (expression); any non-zero scalar is true
C++ native while (condition); the condition can declare a variable
Bash native while and until on the exit status of a command; while read -r line
PowerShell native while (condition)
SQL idiom no loops in queries; WHILE in procedural extensions such as T-SQL and PL/pgSQL
Regex n/a no conditions on state; a quantifier repeats as long as the pattern matches
HTML n/a no loops
CSS n/a no loops

The while loop is almost the same in all general-purpose languages. The differences are in the condition: Java, C#, Kotlin, Go and Rust require a Boolean, Python, JavaScript, C and C++ test the truth of any value, and Bash tests the exit status of a command. Go spells the loop with for, and Rust and Python can bind a value in the condition.

The example files show these differences. Python reads lines with := in the condition and stops Newton's method at a tolerance. JavaScript loops over the matches of a regular expression with exec. Java loops with an Iterator and hasNext. C# reads lines from a StringReader until ReadLine returns null. Go writes a while loop with for and a Scanner. Rust uses while and while let. C walks a string with a pointer until the null character. C++ reads words from a stream in the condition.

PythonGitHub
import io

# := reads a line and tests it in one condition; "" ends the loop.
f = io.StringIO("alpha\nbeta\ngamma\n")
while line := f.readline():
    print("read", line.strip())

# Newton's method: loop until the estimate is close enough.
x = 2.0
guess = 1.0
steps = 0
while abs(guess * guess - x) > 1e-12:
    guess = (guess + x / guess) / 2
    steps += 1
print(round(guess, 10), steps)
Output
read alpha
read beta
read gamma
1.4142135624 5
  • Verdict: native. while line := f.readline() reads and tests in one condition, and the empty string at the end of the file is false. Newton's method for the square root of 2 stops when the error is under a tolerance, after 5 passes that the code does not state.
#include <print>
#include <sstream>
#include <string>

int main() {
    // The condition reads a word and is false at the end of the stream.
    std::istringstream in("the quick brown fox");
    std::string word;
    int count = 0;
    while (in >> word) {
        ++count;
        std::println("{}: {}", count, word);
    }

    // The same pattern reads numbers.
    std::istringstream nums("4 8 15 16 23 42");
    int x = 0;
    int total = 0;
    while (nums >> x) {
        total += x;
    }
    std::println("total: {}", total);
}
Output
1: the
2: quick
3: brown
4: fox
total: 108
  • Verdict: native. in >> word reads a word and converts the stream to false when no word is left, so the read is the condition. The second loop sums numbers with the same pattern.
JavaGitHub
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // An Iterator loop: hasNext is the condition.
        List<Integer> nums = new ArrayList<>(List.of(5, 8, 13, 21));
        Iterator<Integer> it = nums.iterator();
        while (it.hasNext()) {
            int x = it.next();
            if (x % 2 == 0) {
                it.remove();
            }
        }
        System.out.println(nums);

        // Count the digits: the count is not known in advance.
        long n = 9_876_543_210L;
        int digits = 0;
        while (n > 0) {
            n /= 10;
            digits++;
        }
        System.out.println("digits: " + digits);

        // The condition is tested only between passes.
        int i = 0;
        while (i < 1) {
            i = 5;
            System.out.println("the body runs to its end, i = " + i);
        }
    }
}
Output
[5, 13, 21]
digits: 10
the body runs to its end, i = 5
  • Verdict: native. A while loop over an Iterator tests hasNext, and it.remove() removes the even number with no ConcurrentModificationException. The digit loop runs 10 times for a 10-digit number. In the last loop, the body makes the condition false in its first line, and the println after it still runs.
#include <stdio.h>

int main(void) {
    /* Walk a string with a pointer until the null character. */
    const char *s = "hello, world";
    const char *p = s;
    int commas = 0;
    while (*p != '\0') {
        if (*p == ',') {
            commas++;
        }
        p++;
    }
    printf("length %d, commas %d\n", (int)(p - s), commas);

    /* Euclid's algorithm. */
    int a = 1071, b = 462;
    while (b != 0) {
        int t = a % b;
        a = b;
        b = t;
    }
    printf("gcd: %d\n", a);

    /* A condition that is false at the start: zero passes. */
    int n = 0;
    while (n > 0) {
        n--;
    }
    printf("n: %d\n", n);
    return 0;
}
Output
length 12, commas 1
gcd: 21
n: 0
  • Verdict: native. The first loop runs until the pointer reaches the null character that ends a C string, so the number of passes is the length of the string. Euclid's algorithm runs while the remainder is not 0. The last loop runs zero times.
using System.IO;

// ReadLine returns null at the end of the text.
var reader = new StringReader("one\ntwo\nthree");
string? line;
int count = 0;
while ((line = reader.ReadLine()) != null)
{
    count++;
    Console.WriteLine($"{count}: {line}");
}

// Euclid's algorithm: loop until the remainder is 0.
int a = 1071, b = 462;
while (b != 0)
{
    (a, b) = (b, a % b);
}
Console.WriteLine($"gcd: {a}");
Output
1: one
2: two
3: three
gcd: 21
  • Verdict: native. The condition assigns the next line and tests it for null, the usual read loop of C#. Euclid's algorithm runs while the remainder is not 0, and a tuple assignment updates both variables at once.
JavaScriptGitHub
// exec with the g flag returns the next match, then null at the end.
const re = /\d+/g;
const text = "a1 b22 c333";
let m;
while ((m = re.exec(text)) !== null) {
  console.log(m[0], "at", m.index);
}

// A while loop whose condition is false at the start never runs.
let n = 0;
while (n > 0) n--;
console.log("n:", n);

// Binary search: the range shrinks until it is empty.
const a = [2, 3, 5, 7, 11, 13];
let lo = 0;
let hi = a.length;
while (lo < hi) {
  const mid = (lo + hi) >> 1;
  if (a[mid] < 11) lo = mid + 1;
  else hi = mid;
}
console.log("11 is at", lo);
Output
1 at 1
22 at 4
333 at 8
n: 0
11 is at 4
  • Verdict: native. The condition assigns the next match and compares it with null, so the loop ends after the last match. The second loop never runs its body. The binary search halves the range [lo, hi) until it is empty, and the number of passes depends on the data.
package main

import (
	"bufio"
	"fmt"
	"strings"
)

func main() {
	// for with only a condition is the while loop of Go.
	n, digits := 9876543210, 0
	for n > 0 {
		n /= 10
		digits++
	}
	fmt.Println("digits:", digits)

	// Scan returns false at the end of the input.
	sc := bufio.NewScanner(strings.NewReader("alpha beta\ngamma"))
	sc.Split(bufio.ScanWords)
	words := 0
	for sc.Scan() {
		words++
		fmt.Println(words, sc.Text())
	}

	// Euclid's algorithm.
	a, b := 1071, 462
	for b != 0 {
		a, b = b, a%b
	}
	fmt.Println("gcd:", a)
}
Output
digits: 10
1 alpha
2 beta
3 gamma
gcd: 21
  • Verdict: native. Go has no while keyword, and for n > 0 { } is the while loop. for sc.Scan() reads words until the input ends. Euclid's algorithm uses a parallel assignment in the body.
RustGitHub
fn main() {
    // while with a Boolean condition.
    let mut n: u64 = 9_876_543_210;
    let mut digits = 0;
    while n > 0 {
        n /= 10;
        digits += 1;
    }
    println!("digits: {digits}");

    // while let loops while the pattern matches.
    let mut stack = vec!["a", "b", "c"];
    while let Some(top) = stack.pop() {
        println!("pop {top}");
    }

    // Two while let loops count the runs of equal values.
    let mut it = [1, 1, 2, 3, 3, 3].iter().peekable();
    while let Some(x) = it.next() {
        let mut run = 1;
        while it.peek() == Some(&x) {
            it.next();
            run += 1;
        }
        println!("{x} x{run}");
    }
}
Output
digits: 10
pop c
pop b
pop a
1 x2
2 x1
3 x3
  • Verdict: native. Rust has while with a bool condition and while let, which loops while a pattern matches. stack.pop() returns None when the vector is empty, and that ends the loop. The inner loop peeks at the next value and runs while it is equal to the current one.
  • Do-while loop. A post-test loop runs the body before the first test, so the body runs at least once. See do-while loop.
  • Until loop. The until loop of Bash runs while a command fails8, so it is a while loop with the condition reversed. The repeat ... until loop of Pascal also stops when its condition becomes true, but it tests after the body, so it is a do-while loop.
  • Read loops. A loop that reads, tests for the end and then processes is a loop and a half. An assignment in the condition, such as while ((line = reader.ReadLine()) != null) or while (line := f.readline()), writes it as one while loop.
  • Sentinel values. A special value, such as -1, null or an empty line, marks the end of the input, and the loop condition tests for it.
  • Loops with a counter. A while loop with a counter is a for loop, and the for loop is the clearer form when the count is known.

Pitfalls

  • A body that does not change the condition. while (i < n) { sum += a[i]; } with no i++ loops forever.
  • A semicolon after the condition. In C, C++, Java and JavaScript, while (x > 0); has an empty body, so the loop runs forever or not at all, and the block below it runs once.
  • Floating-point tests. while (x != 1.0) can miss 1.0 by a rounding error. Test with < or with a tolerance.
  • The test runs only between passes. A body that makes the condition false still runs to its end. Use break when the body must stop at once.
  • Assignment instead of comparison. while (x = 0) in C assigns 0 and never runs the body. while (x = 1) runs forever.

Cost

A while loop compiles to a test and a conditional jump for each pass, and compilers often move the test to the end of the body and add one jump before the loop, so each pass has only one jump. The total cost is the number of passes times the cost of the body and the test, so a slow condition, such as a function call that scans a list, can cost more than the body.

History

ALGOL 60 had no separate while statement, but its for statement had a while element: for V := E while F do S9 assigns E to V, tests F, and runs S again and again while F is true. Later languages made while a statement of its own. C has while (expression) statement, and C++, Java, C# and JavaScript copied the C form. Go merged while into for, and Rust gave while a pattern form with while let.

References

  1. Loop (statement), Wikipedia, Conditional loop; Pre-test loop
  2. Compound statements, The Python Language Reference, 8.2 The while statement
  3. while, MDN Web Docs, Introduction
  4. Iteration statements, C# language reference, The while statement
  5. The Go Programming Language Specification, For statements with single condition
  6. Loops and other breakable expressions, The Rust Reference, Predicate loops; while let patterns
  7. Control Flow, The Rust Programming Language, Conditional Loops with while
  8. Looping Constructs, Bash Reference Manual, until; while
  9. J. W. Backus et al., Revised Report on the Algorithmic Language ALGOL 60, edited by P. Naur, 1963, 4.6.4.3 While-element

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/E2YAB0/text.yaml