User Tools

Site Tools


foreach

This is an old revision of the document!


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, 21, 34, 55 };
 
            // 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, 55};
 
        for(int u : nums){
            System.out.println( u );
        }
    }
}

Javascript

<!DOCTYPE HTML>
<!-- HTML Grundstruktur -->
<html>
  <body>
    <script>
      // 
      function alerter(item, index) {
          alert("fibonacci number "+index+" is "+item);
      }
 
      var fibarray = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ];
 
      fibarray.foreach(alerter);
    </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.1498585329.txt.gz · Last modified: 2017/06/27 19:42 by gg