Programming Search⌘K

Conceptintro

For loop

Also called for loop, for statement, three-part for loop, C-style for loop, counted loop, counting loop, numeric for loop, range loop, loop counter, loop variable, for range.

A for loop runs its body once for each value of a loop variable. The three-part form of C has an initialization, a condition and an update, and many languages loop over a range of numbers.

Applies to
core-languages

Idea

A for loop is the loop for counting. It gives a loop variable a first value, runs the body, steps the variable, and stops when the variable passes a limit. The loop header holds all the control, so a reader sees at once how many times the body runs.

squares = []
for i in range(1, 6):
    squares.append(i * i)
print(squares)

# range(start, stop, step): the stop value is not included.
print(list(range(0, 10, 3)))
print(list(range(5, 0, -1)))

# The C loop for (i = 0; i < 5; i++) is a while loop with a counter.
i = 0
while i < 5:
    i += 1
print("after the loop, i =", i)

# In Python, the loop variable stays after the loop with its last value.
for j in range(3):
    pass
print("j =", j)

# A change to the loop variable in the body does not change the next value.
for k in range(3):
    print("k is", k)
    k = 100
Output
[1, 4, 9, 16, 25]
[0, 3, 6, 9]
[5, 4, 3, 2, 1]
after the loop, i = 5
j = 2
k is 0
k is 1
k is 2

range(1, 6) gives the numbers 1 to 5, so the first loop makes five squares. A third argument sets the step, and a negative step counts down. The while loop shows what the three-part loop of C does: set a counter, test it before each pass, and step it after each pass. The last two loops show two rules of Python: the variable j keeps its last value after the loop, and the assignment k = 100 has no effect on the next pass.

How it works

The three parts. The for loop of C, C++, Java, C#, JavaScript and Go has a header with three parts: an initialization, a condition and an update. In Java, "The basic for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false"1. The Go specification gives the order: "the init statement is executed once before evaluating the condition for the first iteration; the post statement is executed after each execution of the block (and only if the block was executed)"2. So a three-part for loop is a while loop with two more slots. cppreference says that the C for loop is "Used as a shorter equivalent of while loop"3. The C++ page writes the loop as a block with the initialization and a while loop, with one difference: "Executing a continue statement in statement will evaluate expression"4.

Empty parts. Any of the three parts can be empty. In Go, "Any element of the ForClause may be empty but the semicolons are required unless there is only a condition"2. In C++, an "Empty condition is equivalent to true"4, so for (;;) loops until a break. Wikipedia notes that "Although using the for keyword, the three-part C-style loop is a condition-based construct, not a numeric-based one"5: the three parts can hold any code, not only a counter.

Ranges. Python, Rust, Kotlin and Bash write a counted loop as a loop over a range of numbers. Python has no three-part loop, and its for statement takes the values of an iterable: "iterating range(3) successively yields 0, 1, and then 2"6. The Rust Reference adds the numbers 1 to 10 with for n in 1..117. The range 1..11 does not include 11, and 1..=10 is the same range written with its last value. Go can loop over an integer: for i := range n gives the "integer values from zero to an upper limit"2. Bash has both forms: for name in words and an arithmetic for (( expr1 ; expr2 ; expr3 )), which repeats "until it evaluates to zero"8.

The scope of the loop variable. The rules differ by language and by version.

  • In C, a variable declared in the initialization "is in scope in the entire loop body, including the remainder of init-clause, the entire cond-expression, the entire iteration-expression and the entire loop-statement"3, and it does not exist after the loop. C++, Java, C# and JavaScript with let have the same rule.
  • In Python, "Names in the target list are not deleted when the loop is finished"6, so the variable is still there after the loop.
  • In JavaScript, a var in the header belongs to the whole function. MDN shows that closures made in a loop then all see the last value, "because variables declared with var are only function-scoped, but not lexically scoped"9.
  • In Go, "Each iteration has its own separate declared variable (or variables) [Go 1.22]"2. "Prior to [Go 1.22], iterations share one set of variables instead of having their own separate variables"2.

In languages

LanguageVerdictNote
PythonIdiom
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the three-part for loop of JavaScript, and a let counter gets the type number. No example file exists.
GoNative
RustIdiom
KotlinIdiomKotlin has no three-part for loop. It loops over ranges with for (i in 1..10), until, downTo and step. No example file exists because kotlinc is not installed.
SQLIdiomA query has no loops. A function such as generate_series in PostgreSQL or a recursive common table expression makes a range of rows to join with.
BashNativeBash has the arithmetic loop for (( i = 0; i < n; i++ )) and for i in {1..10} over a brace expansion. No example file exists.
PowerShellNativePowerShell has for ($i = 0; $i -lt 10; $i++) and foreach over a range such as 1..10. 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. A selector such as :nth-child(2n+1) chooses every second element.
Regular expressionsDoes not applyA regular expression has no counters. The quantifier {n} repeats a pattern n times.
Language Verdict Mechanism
Python idiom no three-part loop; for i in range(start, stop, step) over a range object
JavaScript native for (init; condition; update); let makes a new binding for each pass
TypeScript native the for loop of JavaScript; the counter gets the type number
Java native the basic for with lists of initializers and updates; the variable lives in the loop
Kotlin idiom no three-part loop; for (i in 1..10), until, downTo and step
C# native for (init; condition; iterator) with lists of expressions in the first and last parts
Go native for init; cond; post; for i := range n; a new variable for each pass in Go 1.22
Rust idiom no three-part loop; for i in 0..n, (0..n).rev() and step_by
C native for (init; cond; update); the first part can declare the counter
C++ native the loop of C; a range-based for for containers and ranges
Bash native for (( i = 0; i < n; i++ )) and for i in {1..10}
PowerShell native for ($i = 0; $i -lt 10; $i++) and foreach ($i in 1..10)
SQL idiom no loops in queries; generate_series or a recursive common table expression makes a range of rows
Regex n/a no counters; the quantifier {n} repeats a pattern n times
HTML n/a no loops; HTML is a markup language
CSS n/a no loops; :nth-child(2n+1) selects every second element

Two families exist. C, C++, Java, C#, JavaScript, Go and Bash have the three-part loop. Python, Rust and Kotlin dropped it and loop over a range object, so the bounds and the step are values. The second family cannot forget the update or test the wrong variable, which are common bugs of the first.

The example files show these differences. Python shows that adding 0.1 ten times does not give 1.0, computes each value from an integer counter, and counts down with a negative step. JavaScript compares closures over let and var counters, uses two counters in one header and leaves all three parts empty. Java steps two variables and counts over a range of characters. C# counts down and doubles its counter. Go uses the three-part loop, range over an integer and a closure for each pass. Rust uses half-open and inclusive ranges, rev and step_by. C counts down with an unsigned counter in the safe order. C++ loops with an index, with an empty condition and with a reverse iterator.

PythonGitHub
# Adding 0.1 ten times does not give exactly 1.0.
x = 0.0
for _ in range(10):
    x += 0.1
print(x, x == 1.0)

# Compute each value from an integer counter instead.
values = [i / 10 for i in range(1, 11)]
print(values[-1], values[-1] == 1.0)

# range does not build a list, and it knows its length.
r = range(0, 1_000_000_000, 7)
print(len(r), r[3], 21 in r)

# A negative step counts down.
for i in range(10, 0, -3):
    print("countdown", i)
Output
0.9999999999999999 False
1.0 True
142857143 21 True
countdown 10
countdown 7
countdown 4
countdown 1
  • Verdict: idiom. Python has no three-part loop, and a counted loop is a for over a range. A float counter that adds 0.1 ten times ends at 0.9999999999999999, so the loop computes each value from an integer counter. A range of 142857143 numbers uses little memory, because it computes its values. A negative step counts down from 10 by 3.
#include <print>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> names{"ann", "bob", "cy"};

    // The counter i lives only in the loop.
    for (std::size_t i = 0; i < names.size(); ++i) {
        std::println("{}: {}", i, names[i]);
    }

    // An empty condition is true, so for (;;) loops until break.
    int tries = 0;
    for (;;) {
        if (++tries == 3) {
            break;
        }
    }
    std::println("tries: {}", tries);

    // The header can declare a variable of any type, here a reverse iterator.
    for (auto it = names.rbegin(); it != names.rend(); ++it) {
        std::println("reverse: {}", *it);
    }
}
Output
0: ann
1: bob
2: cy
tries: 3
reverse: cy
reverse: bob
reverse: ann
  • Verdict: native. C++ has the three-part loop of C. The index loop compares with names.size(), for (;;) has an empty condition and stops at break, and the last loop steps a reverse iterator instead of a number.
JavaGitHub
public class Main {
    public static void main(String[] args) {
        // Two variables in the header: i counts up and j counts down.
        for (int i = 0, j = 10; i < j; i += 3, j -= 3) {
            System.out.println(i + " " + j);
        }

        // A char counter loops over a range of letters.
        StringBuilder sb = new StringBuilder();
        for (char c = 'a'; c <= 'e'; c++) {
            sb.append(c);
        }
        System.out.println(sb);

        // A counter declared before the loop keeps its value after it.
        int k;
        for (k = 1; k * k < 50; k++) {
        }
        System.out.println("first k with k*k >= 50: " + k);
    }
}
Output
0 10
3 7
abcde
first k with k*k >= 50: 8
  • Verdict: native. The basic for takes lists of declarations and updates, so i and j step together until they cross. A char counter goes from 'a' to 'e'. A variable declared in the header exists only in the loop, so the last loop declares k before it to read its final value.
#include <stddef.h>
#include <stdio.h>

int main(void) {
    int a[] = {10, 20, 30, 40};
    size_t n = sizeof a / sizeof a[0];

    /* Count up with the half-open bound i < n. */
    for (size_t i = 0; i < n; i++) {
        printf("%s%d", i ? " " : "", a[i]);
    }
    printf("\n");

    /* Count down with an unsigned counter: test first, then decrement. */
    for (size_t i = n; i-- > 0;) {
        printf("%s%d", i + 1 < n ? " " : "", a[i]);
    }
    printf("\n");

    /* The comma operator steps two counters. */
    for (int lo = 0, hi = 9; lo < hi; lo += 4, hi -= 4) {
        printf("%d %d\n", lo, hi);
    }

    /* A counter declared before the loop keeps its value after it. */
    int k;
    for (k = 0; k * k <= 30; k++) {
    }
    printf("k = %d\n", k);
    return 0;
}
Output
10 20 30 40
40 30 20 10
0 9
4 5
k = 6
  • Verdict: native. The loop i < n visits the indices 0 to n - 1. A size_t counter cannot go below 0, so the downward loop tests i-- > 0, which stops after index 0. The comma operator updates two counters in the last part. k is declared before the loop, so its final value 6 is still there after the loop.
// Count down from 5 to 1.
var down = new List<int>();
for (int i = 5; i >= 1; i--)
{
    down.Add(i);
}
Console.WriteLine(string.Join(" ", down));

// The update can be any expression: here each pass doubles p.
var powers = new List<int>();
for (int p = 1; p <= 100; p *= 2)
{
    powers.Add(p);
}
Console.WriteLine(string.Join(" ", powers));

// Several expressions in the initializer and iterator sections.
for (int i = 0, j = 3; i < j; i++, j--)
{
    Console.WriteLine($"{i} {j}");
}
Output
5 4 3 2 1
1 2 4 8 16 32 64
0 3
1 2
  • Verdict: native. The for statement of C# has an initializer, a condition and an iterator section. The first loop counts down. The second loop doubles its counter, so the update is not always ++. The third loop declares two counters and steps both in the iterator section.
JavaScriptGitHub
// Each pass of a let loop has its own i, so each closure sees its own value.
const withLet = [];
for (let i = 0; i < 3; i++) withLet.push(() => i);
console.log("let:", withLet.map((f) => f()).join(" "));

// A var counter is one variable for the whole function.
const withVar = [];
for (var j = 0; j < 3; j++) withVar.push(() => j);
console.log("var:", withVar.map((f) => f()).join(" "));
console.log("j after the loop:", j);

// Two counters in one header walk from both ends.
const letters = ["a", "b", "c", "d", "e"];
for (let lo = 0, hi = letters.length - 1; lo < hi; lo++, hi--) {
  [letters[lo], letters[hi]] = [letters[hi], letters[lo]];
}
console.log(letters.join(""));

// All three parts can be empty.
let n = 0;
for (;;) {
  if (++n === 3) break;
}
console.log("n:", n);
Output
let: 0 1 2
var: 3 3 3
j after the loop: 3
edcba
n: 3
  • Verdict: native. With let, each pass has a new binding, so the three closures return 0, 1 and 2. With var, the closures share one variable, which is 3 after the loop and still exists there. Two counters in one header reverse the array in place. for (;;) has no condition and stops only at break.
package main

import "fmt"

func main() {
	// The three-part form with an init, a condition and a post statement.
	for i := 0; i < 3; i++ {
		fmt.Println("i =", i)
	}

	// range over an integer counts from 0 to n-1.
	sum := 0
	for i := range 5 {
		sum += i
	}
	fmt.Println("sum of range 5:", sum)

	// Each pass has its own i, so each closure keeps its own value.
	var fs []func() int
	for i := 0; i < 3; i++ {
		fs = append(fs, func() int { return i })
	}
	for _, f := range fs {
		fmt.Print(f())
	}
	fmt.Println()

	// Two variables step together with a parallel assignment.
	for i, j := 0, 4; i < j; i, j = i+1, j-1 {
		fmt.Println(i, j)
	}
}
Output
i = 0
i = 1
i = 2
sum of range 5: 10
012
0 4
1 3
  • Verdict: native. Go has the three-part for with no parentheses and range over an integer. The module of the examples declares a Go version after 1.22, so each pass has its own i and the closures return 0, 1 and 2. Go has no comma operator, so two counters step with a parallel assignment.
RustGitHub
fn main() {
    // A half-open range does not include its end; an inclusive range does.
    let a: Vec<i32> = (0..5).collect();
    let b: Vec<i32> = (1..=5).collect();
    println!("{a:?} {b:?}");

    // rev counts down and step_by counts by a step.
    let down: Vec<i32> = (1..=5).rev().collect();
    let odd: Vec<i32> = (1..10).step_by(2).collect();
    println!("{down:?} {odd:?}");

    for i in (1..=3).rev() {
        println!("countdown {i}");
    }

    // The loop variable is a new immutable binding for each pass.
    let mut total = 0;
    for i in 1..=100 {
        total += i;
    }
    println!("total: {total}");
}
Output
[0, 1, 2, 3, 4] [1, 2, 3, 4, 5]
[5, 4, 3, 2, 1] [1, 3, 5, 7, 9]
countdown 3
countdown 2
countdown 1
total: 5050
  • Verdict: idiom. Rust has no three-part loop. A counted loop is a for over a range: 0..5 leaves out 5 and 1..=5 includes it. rev turns a range around and step_by(2) takes every second value. The loop variable is a new binding in each pass, and the body cannot change it.
  • Loops over collections. A for-each loop takes the elements of a collection, not numbers, and has no counter. See for-each loop.
  • Several variables. C, C++, Java, C# and JavaScript allow lists in the first and last parts, for example for (i = 0, j = n - 1; i < j; i++, j--), which walks from both ends.
  • Downward and stepped loops. A loop can count down or count by a step: for (i = 10; i > 0; i--) in C, range(10, 0, -1) in Python and (1..=10).rev() in Rust.
  • Loops with an index. A loop that needs the position and the element uses enumerate in Python, entries() in JavaScript or the index and value of range in Go.
  • Vectorized code. NumPy, SQL and array languages apply one operation to all elements and need no explicit loop.

Pitfalls

  • Off-by-one bounds. for (i = 0; i <= n; i++) runs n + 1 times and reads a[n], one past the end. Use the half-open form i < n. See off-by-one errors.
  • Unsigned counters that count down. In C and C++, for (size_t i = n - 1; i >= 0; i--) never ends, because an unsigned value is always 0 or more. Test before the decrement: for (size_t i = n; i-- > 0; ).
  • Floating-point counters. The Control flow article warns that a loop from 0.1 to 1.0 by 0.1 "might iterate 9 or 10 times, depending on various factors such as rounding error, hardware, compiler"5. Count with an integer and compute the value from it.
  • A changed bound. In C and Java, the condition runs again before each pass, so a loop that adds elements to a list while it tests i < list.size() can run forever.
  • Closures over the counter. A closure made in the body can see a later value of the counter. This depends on the language and the version, as described in the section on scope. See loop variable capture.

Cost

A three-part loop compiles to the same code as the equivalent while loop: one test and one jump for each pass. Compilers know the pattern of a counter that steps by a constant, so they unroll such loops, remove bounds checks that the condition already proves, and use vector instructions. In Python, for i in range(n) is slower than a vectorized operation, because each pass runs bytecode, but range does not build a list, so it uses the same memory for any n.

History

ALGOL 60 had a general for statement. A for clause "causes the statement S which it precedes to be repeatedly executed zero or more times"10, and a for list could hold values, a step-until element and a while element. The report also said that after a normal exit, "the value of the controlled variable is undefined after the exit"10. BASIC and Pascal kept the counted form: the Control flow article shows FOR I = 1 TO N in BASIC and for I := 1 to N do in Pascal5. Wikipedia says that the syntax of the three-part loop "came from B and was originally invented by Stephen C. Johnson"11. C++, Java, JavaScript, C# and Go copied it, and Python, Rust and Kotlin replaced it with a loop over a range.

References

  1. The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.14.1 The basic for Statement
  2. The Go Programming Language Specification, For statements with for clause; For statements with range clause
  3. for loop, C reference, cppreference.com, Explanation
  4. for loop, C++ reference, cppreference.com, Explanation; Notes
  5. Control flow, Wikipedia, Loops; Numeric; Condition-controlled
  6. Compound statements, The Python Language Reference, 8.3 The for statement
  7. Loops and other breakable expressions, The Rust Reference, Iterator loops
  8. Looping Constructs, Bash Reference Manual, for (( expr1 ; expr2 ; expr3 ))
  9. for, MDN Web Docs, Introduction; Lexical declarations in the initialization block
  10. J. W. Backus et al., Revised Report on the Algorithmic Language ALGOL 60, edited by P. Naur, 1963, 4.6 For statements
  11. Loop (statement), Wikipedia, Three-part for loop; Enumeration; Loop counter

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