Programming Search⌘K

Conceptintro

Loop

Also called loop, loop statement, iteration, iteration statement, repetition, looping construct, loop body, loop condition, pre-test loop, post-test loop, definite iteration, indefinite iteration.

A loop runs the same block of code again and again: a fixed number of times, while a condition is true, or once for each element of a collection.

Applies to
core-languages

Idea

Many jobs repeat one step: add up a list of prices, read the lines of a file, retry a request, move each object in a game by one frame. A loop writes the step once and runs it again and again. Wikipedia defines a loop as "a control flow construct that allows code to be executed repeatedly, usually with minor alterations between repetitions"1.

# A counted loop: the body runs once for each number in a range.
total = 0
for i in range(1, 6):
    total += i
print("sum 1..5 =", total)

# A condition loop: the body runs while the condition is true.
n, steps = 100, 0
while n > 1:
    n //= 2
    steps += 1
print("halvings of 100:", steps)

# A loop over a collection: the body runs once for each element.
for word in ["red", "green", "blue"]:
    print(word, len(word))

# continue skips to the next pass, and break leaves the loop.
for k in range(10):
    if k % 2 == 0:
        continue
    if k > 7:
        break
    print("odd", k)


# Recursion can do the same job as a loop.
def total_to(n):
    return 0 if n == 0 else n + total_to(n - 1)


print("recursive sum 1..5 =", total_to(5))
Output
sum 1..5 = 15
halvings of 100: 6
red 3
green 5
blue 4
odd 1
odd 3
odd 5
odd 7
recursive sum 1..5 = 15

The three loops show the three main kinds. The first runs a known number of times. The second runs until its condition becomes false, and the program does not know the count before it starts: 100 becomes 50, 25, 12, 6, 3 and 1 in six steps. The third runs once for each element of a list. The fourth loop leaves early with break and skips the even numbers with continue. The last function gets the same sum with recursion and no loop statement.

How it works

The body and the condition. "A conditional loop is usually composed of two parts: a condition and a body"1. The body is a block of statements. The condition decides if the body runs one more time. Each run of the body is an iteration, or a pass. The Control flow article puts the two main cases like this: "the body is executed once for each item of a collection (definite iteration), until a condition is met (indefinite iteration)"2.

When the test runs. A pre-test loop tests the condition before each pass, so the body can run zero times. Python's while statement "repeatedly tests the expression and, if it is true, executes the first suite"3, and in Go "The condition is evaluated before each iteration"4. A post-test loop tests after each pass, so the body runs at least once: in Java, "Executing a do statement always executes the contained Statement at least once"5. See while loop and do-while loop.

Counted loops and loops over collections. A counted loop has a loop variable that takes the values of a range. The three-part for loop of C, Java, C# and JavaScript has an initialization, a condition and an update, and it is a pre-test loop with a counter, see for loop. A loop over a collection gets each element from the collection itself. In Python, the for statement "is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object"3, see for-each loop and iterators.

Exits. Most languages let the body change the normal order. break "terminates the current loop the program is in", and continue "skips to the next iteration of the current loop"1. A return in the body also ends the loop. "In the case of nested loops, the break and continue statements apply to the inner most loop"1, and Java, Go, Rust and JavaScript add labels to leave an outer loop.

One loop or many. The languages have different numbers of loop statements. C# has four, for, foreach, do and while, which "repeatedly execute a statement or a block of statements"6. Go has only one: a for statement "specifies repeated execution of a block"4, and its forms are a condition loop, a three-part loop and a range loop. "Rust supports four loop expressions"7: loop, while, for and a labeled block. In Rust, a loop is an expression, and a loop can give a value with break.

Loops and recursion. A loop and a recursive function can compute the same things. "In most functional programming languages, recursion is used instead of traditional loops"1, because variables do not change, so a counter cannot step. To make deep recursion safe, these languages "implement tail call optimisation, which allows the same stack frame to be used for each iteration of the loop"1. Python does not do this, so a deep recursion fails where a loop works, as the Python example shows. See recursion.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the loops of JavaScript, for, while, do...while, for...of and for...in, and the type checker gives the loop variable a type. No example file exists.
GoNative
RustNative
KotlinNativeKotlin has for over ranges and iterables, while and do-while, and labels such as break@outer. No example file exists because kotlinc is not installed.
SQLIdiomA query works on all the rows of a set, so it needs no loop. A recursive common table expression repeats a query, and the procedural extensions such as PL/pgSQL have LOOP, WHILE and FOR.
BashNativeBash has for over a list of words, an arithmetic for with three expressions, while, and until, which loops while a command fails. No example file exists.
PowerShellNativePowerShell has for, foreach, while, do-while and do-until, and the ForEach-Object cmdlet runs a block for each object in a pipeline. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no loops. A script or a template language repeats content.
CSSDoes not applyCSS has no loops. A rule applies to all the elements that its selector matches, and preprocessors such as Sass add loops that run before the browser reads the file.
Regular expressionsIdiomThe quantifiers *, + and {n,m} repeat a part of a pattern, which is the only repetition in a regular expression.
Language Verdict Mechanism
Python native while and for ... in over iterables; range; else clause on loops; comprehensions
JavaScript native for, while, do...while, for...of, for...in; labels; Array.prototype.forEach
TypeScript native the loops of JavaScript; the type checker gives the type of the loop variable
Java native for, enhanced for, while, do; labeled break and continue; streams
Kotlin native for over ranges and iterables, while, do-while; labels such as break@outer
C# native for, foreach, while, do; await foreach for async streams; LINQ
Go native one statement for: condition, three-part and range forms; labels
Rust native loop, while, while let, for over iterators; loop labels; break with a value
C native for, while, do; break, continue and goto
C++ native the loops of C; range-based for; algorithms such as std::for_each
Bash native for ... in, the arithmetic for ((...)), while and until on exit status
PowerShell native for, foreach, while, do-while, do-until; ForEach-Object in pipelines
SQL idiom set operations on all rows replace loops; recursive common table expressions; loops in procedural extensions
Regex idiom quantifiers such as *, + and {n,m} repeat a pattern
HTML n/a no loops; a script or a template language repeats content
CSS n/a no loops; a rule applies to all the elements that its selector matches

All general-purpose languages have loops, but they differ in the number of loop statements, in the scope of the loop variable, and in the exits. Python has only two loop statements and an else clause. Go has one. Rust treats a loop as an expression. SQL works on sets of rows, so a query does not need a loop.

The example files show these differences. Python uses for ... else, replaces a loop with sum and a comprehension, and shows that deep recursion fails where a loop does not. JavaScript has five loop statements, a labeled break and forEach. Java uses its four loop forms, a labeled break and a stream. C# uses for, foreach, while, do and LINQ. Go writes all its loops with for. Rust uses loop with a value, while let and for over a range. C uses for, while, do and a goto loop. C++ uses a range-based for and std::accumulate.

PythonGitHub
# for ... else: the else part runs when the loop ends without break.
def find(items, target):
    for i, x in enumerate(items):
        if x == target:
            print("found", target, "at", i)
            break
    else:
        print(target, "not found")


find([4, 8, 15], 8)
find([4, 8, 15], 16)

# A built-in function or a comprehension can replace a loop.
print(sum(range(1, 101)))
print([x * x for x in range(5)])


# Deep recursion fails, because Python does not remove tail calls.
def count(n):
    return 0 if n == 0 else 1 + count(n - 1)


try:
    count(100_000)
except RecursionError as e:
    print(type(e).__name__)

# The same repetition as a loop has no depth limit.
i = 0
while i < 100_000:
    i += 1
print(i)
Output
found 8 at 1
16 not found
5050
[0, 1, 4, 9, 16]
RecursionError
100000
  • Verdict: native. Python has two loop statements, while and for. The else clause of the for runs only when the loop does not break, so it reports the failed search. sum and a list comprehension replace two short loops. A recursion 100 000 levels deep raises RecursionError, and a while loop with the same number of passes does not.
#include <numeric>
#include <print>
#include <vector>

int main() {
    std::vector<int> v{3, 1, 4, 1, 5};

    // The range-based for visits each element.
    int sum = 0;
    for (int x : v) {
        sum += x;
    }
    std::println("range for: {}", sum);

    // The classic three-part for with an index.
    std::vector<int> picked;
    for (std::size_t i = 0; i < v.size(); i += 2) {
        picked.push_back(v[i]);
    }
    std::println("step 2: {} {} {}", picked[0], picked[1], picked[2]);

    // An algorithm hides the loop.
    std::println("accumulate: {}", std::accumulate(v.begin(), v.end(), 0));
}
Output
range for: 14
step 2: 3 4 5
accumulate: 14
  • Verdict: native. C++ has the loops of C and a range-based for that visits each element of a container. The index loop with a step of 2 visits the elements at 0, 2 and 4. std::accumulate gets the same sum as the range-based for with no loop statement in the caller.
JavaGitHub
import java.util.List;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum += i;
        }
        System.out.println("for: " + sum);

        for (String s : List.of("x", "y")) {
            System.out.println("enhanced for: " + s);
        }

        int n = 100;
        int steps = 0;
        while (n > 1) {
            n /= 2;
            steps++;
        }
        System.out.println("while: " + steps);

        // The body of a do statement runs at least once.
        int runs = 0;
        do {
            runs++;
        } while (runs < 0);
        System.out.println("do: " + runs);

        // A labeled break leaves the outer loop.
        outer:
        for (int a = 0; a < 3; a++) {
            for (int b = 0; b < 3; b++) {
                if (a + b == 3) {
                    System.out.println("break outer at " + a + " " + b);
                    break outer;
                }
            }
        }

        // A stream replaces the counted loop.
        System.out.println("stream: " + IntStream.rangeClosed(1, 5).sum());
    }
}
Output
for: 15
enhanced for: x
enhanced for: y
while: 6
do: 1
break outer at 1 2
stream: 15
  • Verdict: native. Java has the basic for, the enhanced for over arrays and Iterable objects, while and do. The do body runs once although runs < 0 is false. break outer leaves both loops. IntStream.rangeClosed(1, 5).sum() gets the same sum as the first loop with no loop statement.
#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 5; i++) {
        sum += i;
    }
    printf("for: %d\n", sum);

    int n = 100, steps = 0;
    while (n > 1) {
        n /= 2;
        steps++;
    }
    printf("while: %d\n", steps);

    /* The do body runs before the first test. */
    int runs = 0;
    do {
        runs++;
    } while (runs < 0);
    printf("do: %d\n", runs);

    /* Before structured loops, a loop was a backward jump. */
    int k = 0;
again:
    k++;
    if (k < 3) {
        goto again;
    }
    printf("goto: %d\n", k);
    return 0;
}
Output
for: 15
while: 6
do: 1
goto: 3
  • Verdict: native. C has for, while and do. The do body runs once although the condition is false. The last loop is a label and a goto that jumps back, the form of a loop in assembly language and in early Fortran. The structured loops do the same job and are easier to read.
using System.Linq;

int sum = 0;
for (int i = 1; i <= 5; i++)
{
    sum += i;
}
Console.WriteLine($"for: {sum}");

foreach (var name in new[] { "ann", "bob" })
{
    Console.WriteLine($"foreach: {name}");
}

int n = 100;
int steps = 0;
while (n > 1)
{
    n /= 2;
    steps++;
}
Console.WriteLine($"while: {steps}");

// The do loop runs its body one or more times.
int runs = 0;
do
{
    runs++;
} while (runs < 0);
Console.WriteLine($"do: {runs}");

// LINQ replaces a loop that filters and sums.
int evens = Enumerable.Range(1, 10).Where(x => x % 2 == 0).Sum();
Console.WriteLine($"linq: {evens}");
Output
for: 15
foreach: ann
foreach: bob
while: 6
do: 1
linq: 30
  • Verdict: native. C# has four iteration statements: for, foreach, while and do. The do body runs once although its condition is false. Enumerable.Range(1, 10).Where(...).Sum() adds the even numbers 2, 4, 6, 8 and 10 with no loop statement.
JavaScriptGitHub
const out = [];
for (let i = 0; i < 3; i++) out.push(i);
console.log("for:", out.join(" "));

let n = 100;
let steps = 0;
while (n > 1) {
  n = Math.floor(n / 2);
  steps++;
}
console.log("while:", steps);

// The body of do...while runs once even when the condition is false.
let tries = 0;
do {
  tries++;
} while (tries < 0);
console.log("do...while:", tries);

for (const ch of "abc") console.log("for...of:", ch);
for (const key in { x: 1, y: 2 }) console.log("for...in:", key);

[10, 20].forEach((v, i) => console.log("forEach:", i, v));

// A label lets break leave the outer loop.
outer: for (let a = 0; a < 3; a++) {
  for (let b = 0; b < 3; b++) {
    if (a * b === 2) {
      console.log("break outer at", a, b);
      break outer;
    }
  }
}
Output
for: 0 1 2
while: 6
do...while: 1
for...of: a
for...of: b
for...of: c
for...in: x
for...in: y
forEach: 0 10
forEach: 1 20
break outer at 1 2
  • Verdict: native. JavaScript has five loop statements: for, while, do...while, for...of over the values of an iterable and for...in over the property names of an object. The do...while body runs once although its condition is false at the start. forEach takes the body as a function. break outer leaves both loops at the first pair whose product is 2.
package main

import "fmt"

func main() {
	// The three-part form.
	sum := 0
	for i := 1; i <= 5; i++ {
		sum += i
	}
	fmt.Println("three-part:", sum)

	// The condition-only form is a while loop.
	n, steps := 100, 0
	for n > 1 {
		n /= 2
		steps++
	}
	fmt.Println("condition:", steps)

	// The range form loops over a slice, a map, a string or an integer.
	for i, w := range []string{"red", "green"} {
		fmt.Println("range:", i, w)
	}
	count := []int{}
	for i := range 3 {
		count = append(count, i)
	}
	fmt.Println("range 3:", count)

	// A for with no condition loops until break.
	k := 0
	for {
		k++
		if k == 4 {
			break
		}
	}
	fmt.Println("forever stopped at", k)
}
Output
three-part: 15
condition: 6
range: 0 red
range: 1 green
range 3: [0 1 2]
forever stopped at 4
  • Verdict: native. Go has one loop statement, for, in four forms: the three-part loop, a loop with only a condition, a range loop and a loop with no condition. range 3 counts from 0 to 2. The loop with no condition ends only at break.
RustGitHub
fn main() {
    // loop is an expression: break gives its value.
    let mut n = 1;
    let first_over_100 = loop {
        n *= 3;
        if n > 100 {
            break n;
        }
    };
    println!("loop: {first_over_100}");

    // while let loops while a pattern matches.
    let mut stack = vec![1, 2, 3];
    let mut popped = Vec::new();
    while let Some(top) = stack.pop() {
        popped.push(top);
    }
    println!("while let: {popped:?}");

    // for takes the values of an iterator, here a range.
    let mut sum = 0;
    for i in 1..=5 {
        sum += i;
    }
    println!("for: {sum}");

    // An iterator chain replaces the loop.
    let squares: Vec<i32> = (1..=4).map(|x| x * x).collect();
    println!("{squares:?}");
}
Output
loop: 243
while let: [3, 2, 1]
for: 15
[1, 4, 9, 16]
  • Verdict: native. Rust has loop, while and for. The loop gives 243, the value of its break, and it is the first power of 3 over 100. while let pops the stack until pop returns None. for takes the values of the range 1..=5, and map with collect builds a vector with no loop statement.
  • Nested loops. A loop in the body of another loop visits all the pairs, for example each cell of a grid. The inner loop runs completely for each pass of the outer loop.
  • Loops as expressions. In Rust, a loop gives the value of its break. In Python, a comprehension such as [x * x for x in xs] is a loop that builds a list.
  • Higher-order functions. map, filter, reduce and forEach hide the loop inside a function call. See higher-order functions.
  • Loop with an else. Python runs the else clause of a loop when the loop ends without break, which is useful for a search.
  • Infinite loops. A loop with no exit runs until the program stops, which is right for a server or an event loop and wrong anywhere else. See infinite loops.

Pitfalls

  • Off by one. i <= n instead of i < n runs one pass too many and can read past the end of an array. Half-open ranges such as range(0, n) help. See off-by-one errors.
  • A condition that never becomes false. If the body does not change the values that the condition tests, the loop never ends.
  • Changing a collection while looping over it. Adding or removing elements during a for-each loop raises an error for a Java list or a Python dictionary, and it can be undefined behavior for a C++ container. See iterator invalidation.
  • Capture of the loop variable. A closure made in a loop can see the last value of the variable. In Go, "Prior to [Go 1.22], iterations share one set of variables"4. A var variable in a JavaScript loop has the same trap. See loop variable capture.
  • Floating-point counters. for (x = 0.1; x != 1.0; x += 0.1) may never stop, because 0.1 is not exact in binary. Count with integers and compute the floating-point value from the count.

Cost

A loop compiles to a test and a jump back to the start of the body. Wikipedia notes that "When a program is compiled to machine code, looping may be achieved using jumps; but some loops can be optimized to run without jumping"1. The cost of the loop itself is small. The cost of the body times the number of passes is what counts, and two nested loops over n elements do n × n passes. Compilers unroll short loops, move constant work out of the body, and use vector instructions to do several passes at once.

History

FORTRAN had a DO loop from its first version. The first FORTRAN manual came out in October 1956, "with the first FORTRAN compiler delivered in April 1957"8. ALGOL 60 made the loop a structured statement. Its for clause "causes the statement S which it precedes to be repeatedly executed zero or more times"9, with step and until for counting and while for a condition. The three-part for of C "came from B and was originally invented by Stephen C. Johnson"1. In the late 1960s, structured programming built on the structured program theorem, which states that sequencing, selection and iteration "are sufficient to express any computable function"10. Since then, the structured loop with break and continue has replaced the backward goto in most code.

References

  1. Loop (statement), Wikipedia, Introduction; Conditional loop; Enumeration; Recursion; Loop counter; Early exit and continuation; Infinite loop
  2. Control flow, Wikipedia, Loops; Numeric; Condition-controlled
  3. Compound statements, The Python Language Reference, 8.2 The while statement; 8.3 The for statement
  4. The Go Programming Language Specification, For statements
  5. The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.12 The while Statement; 14.13 The do Statement; 14.14 The for Statement
  6. Iteration statements, C# language reference, Introduction
  7. Loops and other breakable expressions, The Rust Reference, Introduction; Infinite loops; Breaking and values
  8. Fortran, Wikipedia, History; FORTRAN 77
  9. J. W. Backus et al., Revised Report on the Algorithmic Language ALGOL 60, edited by P. Naur, 1963, 4.6 For statements
  10. Structured programming, Wikipedia, Theoretical foundation

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