Export (0) Print
Expand All

Loops

Visual Studio 2008

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.

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);
}

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]);
}

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++;
}

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);

Community Additions

ADD
Show:
© 2015 Microsoft