The foreach loop is used with arrays and collections. The foreach loop accessed arrays in a unique way without using counters. The foreach statement takes the form:
foreach(type identifier in expression) statement(s);
where:
type is the data type, such as int or string.
identifier is the variable name.
expression is the name of the array(or collection).
statement(s) is the statement or block of statements to be executed.
Consider, for example, the following array:
int[,] myIntArray = {{1,3,5},{2,4,6});
We can display the elements of this array by using the following statement:
foreach(int i in myIntArray)
Console.Write(“{0}”,i);
The result should be:
1 3 5 2 4 6
It is important to notice that the number of dimension doesn’t matter because foreach accesses all the elements sequentially. If the array is a one-dimensional array like this:
int[] myIntArray = {1,3,5,2,4,6};
we can still display it by using the same statement. If the array is a string array, we need only to change the type from int to string:
foreach(string i in myIntArray)
Console.Write(“{0}”,i);
Tuesday, March 16, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment