foreach
This is an old revision of the document!
Table of Contents
foreach Schleife
Die foreach Schleife ist die einfachste aller Schleifen. Sie hat keinen Zähler mehr und funktioniert auf Basis von iterierbaren Datenstrukturen
In den folgenden Beispielen wird ein Array angelegt und mit einer foreach Schleife jedes Element des Arrays ausgegeben.
Bash
Die Bash kennt kein foreach.
C++
C++ kann das nur mit Hilfe der Standard Library
#include <vector> // vector #include <algorithm> // std:: #include <iostream> // cout int main() { // initialize a vector => it is iterable, a array not std::vector<int> nums{3, 4, 2, 8, 15, 267}; // declare the function which is called... auto print = [](const int& n) { std::cout << " " << n; }; // ...for every element in this vector std::for_each(nums.begin(), nums.end(), print); // print a new line at the end std::cout << "\n"; }
C#
using System; namespace ForLoop { class ShowFor { static void Main() { // Anlegen eines Arrays int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 }; // für jedes Element im Array foreach (int element in fibarray) { System.Console.WriteLine(element); } } } }
Golang
Go kennt eigentlich keine foreach Schleife.
Java
public class ForEachLoop { public static void main(String[] args) { int [] fibarray = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34}; for(int u : nums){ System.out.println( u ); } } }
Javascript
<!DOCTYPE HTML> <!-- HTML Grundstruktur --> <html> <body> <script> for(i = 1; i <= 10; i++) { alert("The counter is "+i); } </script> </body> </html>
Perl
#!/usr/bin/perl use strict; use warnings; for ($i = 1; $i <= 10; $i = $i + 1) { print "The counter is $i"; }
PHP
<?php for($i = 1; $i <= 10; $i++) { echo "The counter is $i"; }
Python3
Streng genommen ist die for Schleife in Python eine foreach Schleife und wird dadurch hier ausgelassen.
foreach.1498584950.txt.gz · Last modified: 2017/06/27 19:35 by gg