Thursday, February 10, 2011

for-each Loop

The for-each loop is an iteration construct that is popular in a number of scripting languages (e.g. Perl, PHP, Tcl/Tk), build tools (GNU Make) and function libraries (e.g. for_each in <algorithm> in C++). The for-each loop is a less verbose way to iterate through arrays or classes that implement the the System.Collections.IEnumerable interface in C# or the java.lang.Iterable interface in Java.
In C#, the keywords foreach and in are used when creating the for-each loop while in Java the keyword for and the operator : are used.
C# Code
string[] greek_alphabet = {"alpha", "beta", "gamma", "delta", "epsilon"};

foreach(string str in greek_alphabet)
Console.WriteLine(str + " is a letter of the greek alphabet");

Java Code
String[] greek_alphabet = {"alpha", "beta", "gamma", "delta", "epsilon"};

for(String str : greek_alphabet)
System.out.println(str + " is a letter of the greek alphabet");

No comments:

Post a Comment