The foreach tutorial shows how to loop over data in different computer languages, including C#, F#, C++, Java, Kotlin, Go, Python, Ruby, Perl, PHP, JavaScript, TypeScript, Dart, Bash, and AWK.
last modified January 9, 2023
The foreach tutorial shows how to loop over data in different computer languages, including C#, F#, C++, Java, Kotlin, Go, Python, Ruby, Perl, PHP, JavaScript, TypeScript, Dart, Bash, and AWK.
C# has the foreach keyword and the ForEach method to loop over containers.
Program.cs
using System; using System.Collections.Generic;
var chars = new char[] {‘a’, ‘b’, ‘c’, ‘x’, ‘y’, ‘z’};
foreach (var c in chars) { Console.WriteLine(c); }
Console.WriteLine("———————–");
var vals = new List<int> {1, 2, 3, 4, 5, 6}; foreach (var val in vals) { Console.WriteLine(val); }
Console.WriteLine("———————–");
var domains = new Dictionary<string, string> { {“sk”, “Slovakia”}, {“ru”, “Russia”}, {“de”, “Germany”}, {“no”, “Norway”} };
foreach (var pair in domains) { Console.WriteLine($"{pair.Key} - {pair.Value}"); }
Console.WriteLine("———————–");
foreach ((var Key, var Value) in domains) { Console.WriteLine($"{Key} - {Value}"); }
In the example, we loop over elements of an array, list, and dictionary with foreach statement.
sk - Slovakia ru - Russia de - Germany no - Norway
In the next example, we loop over elements with ForEach method.
Program.cs
using System; using System.Linq; using System.Collections.Generic;
int[] vals = {1, 2, 3, 4, 5}; Array.ForEach(vals, e => Console.WriteLine(e));
Console.WriteLine("———————–");
var words = new List<string> {“tea”, “falcon”, “book”, “sky”}; words.ForEach(e => Console.WriteLine(e));
Console.WriteLine("———————–");
var domains = new Dictionary<string, string> { {“sk”, “Slovakia”}, {“ru”, “Russia”}, {“de”, “Germany”}, {“no”, “Norway”} };
domains.ToList().ForEach(pair => Console.WriteLine($"{pair.Key} - {pair.Value}"));
We loop over elements of an array, list, and dictionary with ForEach method.
sk - Slovakia ru - Russia de - Germany no - Norway
F# has for/in, List.iter, Map.iter forms to loop over elements.
Program.fs
let vals = [| 1; 2; 3; 4; 5 |]
for vl in vals do printfn “%d” vl
printfn “————————”
let nums = [ 1 .. 6 ] List.iter (fun i -> printfn “%d” i) nums
printfn “————————”
let data = seq { for i in 1 .. 10 -> (i, i * i) }
for (x, squared) in data do printfn “%d squared is %d” x squared
printfn “————————”
let countries = Map.empty. Add(“sk”, “Slovakia”). Add(“ru”, “Russia”). Add(“de”, “Germany”). Add(“no”, “Norway”)
countries |> Map.iter (fun key value -> printf “Key = %A, Value = %A\n” key value)
We loop over elements of an array, list, sequence, and map.
Key = “de”, Value = “Germany” Key = “no”, Value = “Norway” Key = “ru”, Value = “Russia” Key = “sk”, Value = “Slovakia”
C++ 11 introduced range-based for loop.
foreach.cpp
#include <iostream> #include <list> #include <map> #include <string>
int main() {
int vals[] {1, 2, 3, 4, 5};
for (auto val : vals) {
std::cout << val << std::endl;
}
std::list<std::string> words = { "falcon", "sky", "cloud", "book" };
for (auto word: words) {
std::cout << word << std::endl;
}
std::map<std::string, int> items {
{"coins", 3},
{"pens", 2},
{"keys", 1},
{"sheets", 12}
};
for (auto item: items) {
std::cout << item.first << ": " << item.second << std::endl;
}
}
We loop over an array, list, and map in C++.
$ ./foreach 1 2 3 4 5 falcon sky cloud book coins: 3 keys: 1 pens: 2 sheets: 12
In Java, we can use the enhanced-for loop and the forEach method to loop over elements of containers.
com/zetcode/ForEachEx.java
package com.zetcode;
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
public class JavaForeachEx {
public static void main(String[] args) {
int[] nums = { 3, 4, 2, 1, 6, 7 };
for (int e : nums) {
System.out.println(e);
}
System.out.println("-------------------------");
List<String> items = new ArrayList<>();
items.add("coins");
items.add("pens");
items.add("keys");
items.add("sheets");
items.forEach(System.out::println);
for (var item : items) {
System.out.println(item);
}
System.out.println("-------------------------");
Map<String, Integer> items2 = new HashMap<>();
items2.put("coins", 3);
items2.put("pens", 2);
items2.put("keys", 1);
items2.put("sheets", 12);
items2.forEach((k, v) -> System.out.printf("%s : %d%n", k, v));
for (Map.Entry<String, Integer> entry : items2.entrySet()) {
String k = entry.getKey();
Integer v = entry.getValue();
System.out.printf("%s : %d%n", k, v);
}
}
}
We loop over elements of an array, arraylist and hashmap.
sheets : 12 coins : 3 keys : 1 pens : 2 sheets : 12 coins : 3 keys : 1 pens : 2
Kotlin has foreEach and forEachIndexed methods and for/in form to loop over elements of containers.
KotlinForeach.kt
package com.zetcode
fun main() {
val nums = arrayOf(1, 2, 3, 4, 5, 6, 7)
nums.forEach { e -> print("$e ") }
println()
nums.forEachIndexed { i, e -> println("nums[$i] = $e") }
for (e in nums) {
print("$e ")
}
println("\n------------------------")
val words = listOf("pen", "cup", "dog", "person",
"cement", "coal", "spectacles")
words.forEach { e -> print("$e ") }
println()
for (word in words) {
print("$word ")
}
println()
words.forEachIndexed { i, e -> println("words[$i] = $e") }
println("------------------------")
val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
items.forEach { (k, v) -> println("There are $v $k") }
for ((k, v) in items) {
println("$k = $v")
}
}
We loop over elements of an array, list, and map in Kotlin.
There are 12 coins There are 45 books There are 33 cups There are 2 pens coins = 12 books = 45 cups = 33 pens = 2
Go has for/range form to loop over container elements.
foreach.go
package main
import “fmt”
func main() {
vals := [...]int{5, 4, 3, 2, 1}
for idx, e := range vals {
fmt.Printf("%d has index %d\n", e, idx)
}
fmt.Println("-----------------------")
data := map[string]string{
"de": "Germany",
"it": "Italy",
"sk": "Slovakia",
}
for k, v := range data {
fmt.Println(k, "=>", v)
}
fmt.Println("----------------------")
for k := range data {
fmt.Println(k, "=>", data[k])
}
}
We use for/range form to loop over elements of an array and map.
de => Germany it => Italy sk => Slovakia
Python has for/in form to iterate over elements of containers.
foreach.py
#!/usr/bin/python
vals = [1, 2, 3, 4, 5]
for val in vals: print(val)
data = { “coin”: 2, “pen”: 4, “cup”: 12, “lamp”: 3 }
for k, v in data.items(): print(f"{k}: {v}")
We loop over a list and a map in Python.
$ ./foreach.py 1 2 3 4 5 coin: 2 pen: 4 cup: 12 lamp: 3
Ruby has each and for/in to iterate over arrays and each and each_pair to iterate over hashes.
foreach.rb
#!/usr/bin/ruby
nums = [1, 2, 3, 4, 5]
nums.each do |num| puts num end
puts("——————–")
for e in nums do puts e end
puts("——————–")
stones = { 1 => “garnet”, 2 => “topaz”, 3 => “opal”, 4 => “amethyst” }
stones.each { |k, v| puts “Key: #{k}, Value: #{v}” }
puts("——————–")
stones.each_pair { |k, v| puts “Key: #{k}, Value: #{v}” }
In the example, we loop over an array and a hash.
Key: 1, Value: garnet Key: 2, Value: topaz Key: 3, Value: opal Key: 4, Value: amethyst
Perl has foreach statement to loop over elements of containers.
foreach.pl
#!/usr/bin/perl
use v5.30;
my @vals = (1..6); foreach my $val (@vals) {
say "$val ";
}
say “—————————”;
say “$_” foreach @vals;
say “—————————”;
my %stones = ( 1 => “garnet”, 2 => “topaz”, 3 => “opal”, 4 => “amethyst” );
foreach my $k (keys %stones) { say “$k => $stones{$k}”; }
We loop over an array and has in Perl with foreach.
1 => garnet 2 => topaz 3 => opal 4 => amethyst
PHP has foreach keyword to loop over elements of containers.
foreach.php
<?php
$planets = [ “Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”, “Uranus”, “Neptune” ];
foreach ($planets as $item) {
echo "$item ";
}
echo “\n”;
$benelux = [ ‘be’ => ‘Belgium’, ’lu’ => ‘Luxembourgh’, ’nl’ => ‘Netherlands’ ];
foreach ($benelux as $key => $value) {
echo "$key is $value\n";
}
We loop over a PHP array with foreach.
$ php foreach.php Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune be is Belgium lu is Luxembourgh nl is Netherlands
JavaScript has forEach method and for/in and for/of forms to loop over containers.
foreach.js
let words = [‘pen’, ‘pencil’, ‘falcon’, ‘rock’, ‘sky’, ’earth’];
words.forEach(e => console.log(e));
console.log("———————-");
words.forEach((word, idx) => {
console.log(${word} has index ${idx}
);
});
console.log("———————-");
for (let idx in words) {
console.log(`${words[idx]} has index ${idx}`);
}
console.log("———————-");
for (let word of words) {
console.log(word);
}
console.log("———————-");
let stones = new Map([[1, “garnet”], [2, “topaz”], [3, “opal”], [4, “amethyst”]]);
stones.forEach((k, v) => {
console.log(`${k}: ${v}`);
});
The example loops over elements of an array and a map.
garnet: 1 topaz: 2 opal: 3 amethyst: 4
TypeScript has forEach method and for/in and for/of forms to loop over containers.
foreach.ts
let words: string[] = [‘pen’, ‘pencil’, ‘falcon’, ‘rock’, ‘sky’, ’earth’];
words.forEach(e => console.log(e));
console.log("———————-");
words.forEach((word, idx) => {
console.log(${word} has index ${idx}
);
});
console.log("———————-");
for (let idx in words) {
console.log(`${words[idx]} has index ${idx}`);
}
console.log("———————-");
for (let word of words) {
console.log(word);
}
console.log("———————-");
let stones = new Map<number, string>([[1, “garnet”], [2, “topaz”], [3, “opal”], [4, “amethyst”]]);
stones.forEach((k, v) => {
console.log(`${k}: ${v}`);
});
The example loops over elements of a typed array and map.
garnet: 1 topaz: 2 opal: 3 amethyst: 4
In Dart, we have the forEach method to loop over containers.
foreach.dart
import ‘dart:io’;
void main() {
var vals = <int>[1, 2, 3, 4, 5];
vals.forEach((e) { stdout.write("$e “); });
print(”");
var fruit = {1: ‘Apple’, 2: ‘Banana’, 3: ‘Cherry’, 4: ‘Orange’};
fruit.forEach((key, val) { print(’{ key: $key, value: $val}’); });
print(’—————————’);
fruit.entries.forEach((e) { print(’{ key: ${e.key}, value: ${e.value} }’); });
print(’—————————’);
for (var key in fruit.keys) print(key); for (var value in fruit.values) print(value); }
We loop over a list and map in Dart with forEach.
1 2 3 4 Apple Banana Cherry Orange
In Bash, we have the for/in form to loop over containers.
foreach.sh
#!/usr/bin/bash
words=(falcon sky cloud water lord lawn)
for word in “${words[@]}” do echo “$word” done
echo “————————–”
stones=([1]=garnet [2]=topaz [3]=opan [4]=amethyst)
for k in “${!stones[@]}” do echo “$k: ${stones[$k]}” done
We loop over a plain array and an associative array in Bash with for/in.
4: amethyst 3: opan 2: topaz 1: garnet
In AWK, we have the for/in form to loop over containers.
foreach.awk
sky smile nine nice cup cloud tower
This is the words.txt file.
foreach.awk
#!/usr/bin/awk -f
BEGIN {
i = 0 }
{ words[i] = $0 i++ }
END { for (i in words) { print words[i] } }
We loop over an array of words in AWK with for/in.
$ ./foreach.awk words.txt sky smile nine nice cup cloud tower
In this article, we have used foreach loop to go over elements of containers in different computer languages.