Loops
A loop is a statement, or set of statements, that are repeated for a specified number of times or until some condition is met. The type of loop you use depends on your programming task and your personal coding preference. One main difference between C# and other languages, such as C++, is the foreach loop, designed to simplify iterating through arrays or collections.
foreach Loops
C# introduces a way of creating loops that may be new to C++ and C programmers: the foreach loop. Instead of creating a variable simply to index an array or other data structure such as a collection, the foreach loop does some of the hard work for you:
// An array of integers
int[] array1 = {0, 1, 2, 3, 4, 5};
foreach (int n in array1)
{
System.Console.WriteLine(n.ToString());
}
// An array of strings
string[] array2 = {"hello", "world"};
foreach (string s in array2)
{
System.Console.WriteLine(s);
}
for Loops
Here is how the same loops would be created by using a for keyword:
// An array of integers
int[] array1 = {0, 1, 2, 3, 4, 5};
for (int i=0; i<6; i+)
{
System.Console.WriteLine(array1[i].ToString());
}
// An array of strings
string[] array2 = {"hello", "world"};
for (int i=0; i<2; i+)
{
System.Console.WriteLine(array2[i]);
}
while Loops
The while loop versions are in the following examples:
// An array of integers
int[] array1 = {0, 1, 2, 3, 4, 5};
int x = 0;
while (x < 6)
{
System.Console.WriteLine(array1[x].ToString());
x++;
}
// An array of strings
string[] array2 = {"hello", "world"};
int y = 0;
while (y < 2)
{
System.Console.WriteLine(array2[y]);
y++;
}
do-while Loops
The do-while loop versions are in the following examples:
// An array of integers
int[] array1 = {0, 1, 2, 3, 4, 5};
int x = 0;
do
{
System.Console.WriteLine(array1[x].ToString());
x++;
} while(x < 6);
// An array of strings
string[] array2 = {"hello", "world"};
int y = 0;
do
{
System.Console.WriteLine(array2[y]);
y++;
} while(y < 2);
See Also
Tasks
How to: Break Out of an Iterative Statement
How to: Iterate Through a Collection
How to: Iterate Through an Array