Loops (Visual C# Express)
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 choose depends on your programming task and your personal coding preference. One major 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 using a for keyword:
while Loops
The while loop versions look like this:
// 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
Using do-while loops looks like this:
// 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 (Visual C#)
How to: Iterate Through a Collection (Visual C#)
How to: Iterate Through an Array (Visual C#)
Reference
Iteration Statements (C# Reference)
Using foreach with Arrays (C# Programming Guide)