Looping Statements
This documentation is archived and is not being maintained.

Looping Statements (C# vs Java)

Looping statements repeat a specified block of code until a given condition is met.

The syntax and operation of for loops is the same in both C# and Java:

for (int i = 0; i<=9; i++)
{
    System.Console.WriteLine(i);
}

foreach Loops

C# introduces a new loop type called the foreach loop, which is similar to Visual Basic's For Each. The foreach loop enables iterating through each item in a container class, such as an array, that supports the IEnumerable interface. The following code illustrates the use of the foreach statement to output the contents of an array:

static void Main()
{
    string[] arr= new string[] {"Jan", "Feb", "Mar"};

    foreach (string s in arr)
    {
        System.Console.WriteLine(s);
    }
}

For more information, see Arrays (C# vs Java).

while and do...while Loops

The syntax and operation of while and do...while statements are the same in both languages:

while (condition)
{
    // statements
}
do
{
    // statements
}
while(condition);  // Don't forget the trailing ; in do...while loops
Show:
© 2016 Microsoft