Taskintro
Loop over a collection
Also called for each item, iterate over a list, iterate over an array, foreach task, for-of loop, enhanced for loop, range over a slice, sum a list with a loop, Loops/Foreach.
Visit each item of a list with a for-each loop and add the items, and know which loops give the items, which give the keys, and when the sum needs a wider type.
- Evidence
- Code in 10 languages
Task
Visit each item of a list in order, and add the items. The function total(items) returns the sum of the items, and 0 for the empty list. For example, total([1, 2, 3]) is 6.
items has from 0 to 1000 items, and each item is a 32-bit signed integer. The sum can be outside the 32-bit range, so the result is a 64-bit integer. Rosetta Code asks for a for-each loop when the language has one1, so the solutions use one in each language except C.
Solutions
| Language | The loop |
|---|---|
| Python | for x in items: |
| JavaScript, TypeScript | for (const x of items) |
| Java | for (int x : items) |
| C# | foreach (int x in items) |
| C++ | for (int x : items) |
| Go | for _, x := range items |
| Rust | for &x in items |
| Bash | for x in "$@" |
| C | for (size_t i = 0; i < n; i++) |
- Python. The
forstatement "iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence"2. - JavaScript and TypeScript.
for...of"executes a loop that operates on a sequence of values sourced from an iterable object"3. A sum of 1000 32-bit numbers is far below 2^53, so anumberholds it exactly. - Java. The enhanced
fortakes "an array type (§10.1) or a subtype of the raw type Iterable"4. The sum is along. - C#.
foreachruns the body "for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface"5. The sum is along. - C++. The range-based
for"Executes a for loop over a range"6. The sum is along long. - Go. A
forwith arangeclause gives the index and the value of each item7. The solution drops the index with_. The items areint32and the sum isint64. - Rust. "you can use a for loop and execute some code for each item in a collection"8.
for &x in itemscopies eachi32out of the slice. The sum isi64. - Bash.
for name in wordsruns the commands "once for each word in the resultant list"9. The function takes the items as arguments, so the loop reads"$@". - C. The function gets a pointer and a length, so it uses an index loop.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: the loop body does not run, and the sum stays 0.single: one item, so the sum is the item.negative: the items can be negative, and the sum can be negative.limitandlimit-low: the sum is outside the 32-bit range. A 32-bit sum wraps around and gives a wrong answer.
Pitfalls
- JavaScript
for...ingives the keys, not the items. It "iterates over all enumerable string properties of an object"10, and "Array indexes are just enumerable properties with integer names"10. Soxis the string"0", then"1", and+joins strings:
const items = [1, 2, 3];
let a = 0;
for (const x in items) {
a += x;
}
let b = 0;
for (const x of items) {
b += x;
}
console.log(a, b);
0012 6
- A 32-bit sum wraps around. In Java, "If an integer addition overflows, then the result is the low-order bits of the mathematical sum"11. Use a 64-bit sum:
public class Main {
public static void main(String[] args) {
int[] items = {2147483647, 2147483647, 2};
int bad = 0;
long good = 0;
for (int x : items) {
bad += x;
good += x;
}
System.out.println(bad + " " + good);
}
}
0 4294967296
- The order of a map loop depends on the language. In Go, "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next"7. In Python, "Dictionaries preserve insertion order"12. If the order matters, loop over a sorted list of the keys.
- Do not add or remove items in the loop. A for-each loop can skip items or fail when the collection changes under it. See iterator invalidation.
See for-each loop for the loop itself.
Related tasks
- Write a counted loop: a loop over numbers, not items.
- Loop with an index: the index and the item together.
- Loop over several collections at once: one loop over two or more lists.
- Reverse a list: walk a list from the end.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-a-collection/.
def total(items: list[int]) -> int:
"""Return the sum of the items, using a for-each loop."""
s = 0
for x in items:
s += x
return s
test_total.py 22 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-a-collection/.
import pytest
from total import total
CASES = {
"three": ([1, 2, 3], 6),
"mixed": ([10, -4, 7, 0, 3], 16),
"empty": ([], 0),
"single": ([7], 7),
"negative": ([-5, 2, -1], -4),
"limit": ([2147483647, 2147483647, 2], 4294967296),
"limit-low": ([-2147483648, -2147483648], -4294967296),
}
@pytest.mark.parametrize("name", CASES)
def test_total(name):
items, want = CASES[name]
assert total(items) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
#include "total.hpp"
#include <vector>
long long total(const std::vector<int> &items) {
// A long long sum: an int sum can overflow, which is undefined.
long long s = 0;
for (int x : items) {
s += x;
}
return s;
}
total.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
#pragma once
#include <vector>
// total returns the sum of the items as a long long.
long long total(const std::vector<int> &items);
test_total.cpp 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
#include "total.hpp"
#include <climits>
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<int> &items, long long want) {
if (total(items) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("three", {1, 2, 3}, 6);
check("mixed", {10, -4, 7, 0, 3}, 16);
check("empty", {}, 0);
check("single", {7}, 7);
check("negative", {-5, 2, -1}, -4);
check("limit", {INT_MAX, INT_MAX, 2}, 4294967296LL);
check("limit-low", {INT_MIN, INT_MIN}, -4294967296LL);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
final class Total {
private Total() {}
/** Returns the sum of the items, using an enhanced for loop. */
static long total(int[] items) {
// A long sum: an int sum wraps around past Integer.MAX_VALUE.
long s = 0;
for (int x : items) {
s += x;
}
return s;
}
}
TotalTest.java 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class TotalTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("three", new int[] {1, 2, 3}, 6L),
Arguments.of("mixed", new int[] {10, -4, 7, 0, 3}, 16L),
Arguments.of("empty", new int[] {}, 0L),
Arguments.of("single", new int[] {7}, 7L),
Arguments.of("negative", new int[] {-5, 2, -1}, -4L),
Arguments.of("limit", new int[] {2147483647, 2147483647, 2}, 4294967296L),
Arguments.of("limit-low", new int[] {Integer.MIN_VALUE, Integer.MIN_VALUE}, -4294967296L));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void total(String name, int[] items, long want) {
assertEquals(want, Total.total(items), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
#include "total.h"
long long total(const int *items, size_t n) {
// A long long sum: an int sum can overflow, which is undefined.
long long s = 0;
for (size_t i = 0; i < n; i++) {
s += items[i];
}
return s;
}
total.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
#ifndef TOTAL_H
#define TOTAL_H
#include <stddef.h>
// total returns the sum of the n items as a long long.
long long total(const int *items, size_t n);
#endif
test_total.c 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
#include "total.h"
#include <limits.h>
#include <stdio.h>
static int failures = 0;
static void check(const char *name, const int *items, size_t n, long long want) {
long long got = total(items, n);
if (got != want) {
fprintf(stderr, "case %s failed: got %lld, want %lld\n", name, got, want);
failures++;
}
}
#define CHECK(name, want, ...) \
do { \
const int items[] = {__VA_ARGS__}; \
check(name, items, sizeof items / sizeof items[0], want); \
} while (0)
int main(void) {
CHECK("three", 6, 1, 2, 3);
CHECK("mixed", 16, 10, -4, 7, 0, 3);
check("empty", NULL, 0, 0);
CHECK("single", 7, 7);
CHECK("negative", -4, -5, 2, -1);
CHECK("limit", 4294967296LL, INT_MAX, INT_MAX, 2);
CHECK("limit-low", -4294967296LL, INT_MIN, INT_MIN);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
public static class Total
{
// Returns the sum of the items, using a foreach loop.
public static long Of(IEnumerable<int> items)
{
// A long sum: an int sum wraps around past int.MaxValue.
long s = 0;
foreach (int x in items)
{
s += x;
}
return s;
}
}
TotalTests.cs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
using Xunit;
public sealed class TotalTests
{
public static TheoryData<string, int[], long> Cases => new()
{
{ "three", new int[] { 1, 2, 3 }, 6 },
{ "mixed", new int[] { 10, -4, 7, 0, 3 }, 16 },
{ "empty", new int[0], 0 },
{ "single", new int[] { 7 }, 7 },
{ "negative", new int[] { -5, 2, -1 }, -4 },
{ "limit", new int[] { 2147483647, 2147483647, 2 }, 4294967296 },
{ "limit-low", new int[] { int.MinValue, int.MinValue }, -4294967296 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] items, long want)
{
Assert.NotNull(name);
Assert.Equal(want, Total.Of(items));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
/**
* Returns the sum of the items, using a for...of loop.
* @param {number[]} items
* @returns {number}
*/
export function total(items) {
let s = 0;
// for...of gives the items. for...in would give the keys as strings.
for (const x of items) {
s += x;
}
return s;
}
total.test.js 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { total } from "./total.js";
const cases = [
["three", [1, 2, 3], 6],
["mixed", [10, -4, 7, 0, 3], 16],
["empty", [], 0],
["single", [7], 7],
["negative", [-5, 2, -1], -4],
["limit", [2147483647, 2147483647, 2], 4294967296],
["limit-low", [-2147483648, -2147483648], -4294967296],
];
for (const [name, items, want] of cases) {
test(name, () => {
assert.equal(total(items), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
export function total(items: readonly number[]): number {
let s = 0;
// for...of gives the items. for...in would give the keys as strings.
for (const x of items) {
s += x;
}
return s;
}
total.test.ts 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { total } from "./total.ts";
const cases: [string, number[], number][] = [
["three", [1, 2, 3], 6],
["mixed", [10, -4, 7, 0, 3], 16],
["empty", [], 0],
["single", [7], 7],
["negative", [-5, 2, -1], -4],
["limit", [2147483647, 2147483647, 2], 4294967296],
["limit-low", [-2147483648, -2147483648], -4294967296],
];
for (const [name, items, want] of cases) {
test(name, () => {
assert.equal(total(items), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
// Package total adds the items of a slice with a range loop.
package total
// Total returns the sum of the items as an int64.
func Total(items []int32) int64 {
var s int64
// range gives the index and a copy of each item. _ drops the index.
for _, x := range items {
s += int64(x)
}
return s
}
total_test.go 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
package total
import (
"math"
"testing"
)
var cases = []struct {
name string
items []int32
want int64
}{
{"three", []int32{1, 2, 3}, 6},
{"mixed", []int32{10, -4, 7, 0, 3}, 16},
{"empty", []int32{}, 0},
{"single", []int32{7}, 7},
{"negative", []int32{-5, 2, -1}, -4},
{"limit", []int32{math.MaxInt32, math.MaxInt32, 2}, 4294967296},
{"limit-low", []int32{math.MinInt32, math.MinInt32}, -4294967296},
}
func TestTotal(t *testing.T) {
for _, c := range cases {
if got := Total(c.items); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
/// Returns the sum of the items as an i64, using a for loop.
pub fn total(items: &[i32]) -> i64 {
let mut s: i64 = 0;
// &x copies each i32 out of the slice.
for &x in items {
s += i64::from(x);
}
s
}
tests/total_test.rs 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-a-collection/.
use algo_loop_over_a_collection::total;
#[test]
fn cases() {
let cases: &[(&str, &[i32], i64)] = &[
("three", &[1, 2, 3], 6),
("mixed", &[10, -4, 7, 0, 3], 16),
("empty", &[], 0),
("single", &[7], 7),
("negative", &[-5, 2, -1], -4),
("limit", &[i32::MAX, i32::MAX, 2], 4294967296),
("limit-low", &[i32::MIN, i32::MIN], -4294967296),
];
for &(name, items, want) in cases {
assert_eq!(total(items), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-a-collection/.
# total ITEM...
# Prints the sum of the items. Bash arithmetic uses 64-bit integers.
total() {
local s=0 x
for x in "$@"; do
((s += x))
done
printf '%s\n' "$s"
}
test_total.bats 25 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-a-collection/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/total.sh"
}
check() { # check WANT ITEM...
local want=$1
shift
local got
got=$(total "$@"; printf x)
[ "$got" = "$want"$'\n'x ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "three" { check 6 1 2 3; }
@test "mixed" { check 16 10 -4 7 0 3; }
@test "empty" { check 0; }
@test "single" { check 7 7; }
@test "negative" { check -4 -5 2 -1; }
@test "limit" { check 4294967296 2147483647 2147483647 2; }
@test "limit-low" { check -4294967296 -2147483648 -2147483648; }
References
- Loops/Foreach, Rosetta Code (the RosettaCodeData mirror), Task
- More Control Flow Tools, The Python Tutorial, 4.2 for Statements
- for...of, MDN Web Docs, Description
- The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.14.2 The enhanced for statement
- Iteration statements, C# language reference, The foreach statement
- Range-based for loop, cppreference.com, Description
- The Go Programming Language Specification, For statements with range clause
- Control Flow, The Rust Programming Language, Looping Through a Collection with for
- Bash Reference Manual, 3.2.5.1 Looping Constructs
- for...in, MDN Web Docs, Description
- The Java Language Specification, Java SE 25 Edition, Chapter 15, 15.18.2 Additive Operators (+ and -) for Numeric Types
- Built-in Types, The Python Standard Library, Mapping Types, dict
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag RG9JMG Edit this page History Report an error Markdown