Professional Documents
Culture Documents
do
for
foreach
in
while
DO
Example
In the following example, the do-while loop statements execute as long as the variable x is less
than 5.
public class TestDoWhile
{
public static void Main ()
{
int x = 0;
do
{
Console.WriteLine(x);
x++;
} while (x < 5);
}
}
/*
Output:
0
1
2
3
4
*/
FOR
By using a for loop, you can run a statement or a block of statements repeatedly until a specified
expression evaluates to false. This kind of loop is useful for iterating over arrays and for other
applications in which you know in advance how many times you want the loop to iterate.
SYNTAX:
for (initializer; condition; iterator)
body
Example
In the following example, the value of i is written to the console and incremented by 1 during
each iteration of the loop.
class ForLoopTest
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}
/*
Output:
1
2
3
4
5
*/
FOR EACH
The foreach statement repeats a group of embedded statements for each element
in an array or an object collection that implements the
System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T>
interface.
A foreach loop can also be exited by the goto, return, or throw statements.
Example
a foreach loop that maintains a count of the number of elements in the array
class ForEachTest
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
System.Console.WriteLine(element);
}
System.Console.WriteLine();
// Compare the previous loop to a similar for loop.
for (int i = 0; i < fibarray.Length; i++)
{
System.Console.WriteLine(fibarray[i]);
}
System.Console.WriteLine();
// You can maintain a count of the elements in the collection.
int count = 0;
foreach (int element in fibarray)
{
count += 1;
System.Console.WriteLine("Element #{0}: {1}", count, element);
}
System.Console.WriteLine("Number of elements in the array: {0}",
count);
}
// Output:
// 0
// 1
// 1
// 2
// 3
// 5
// 8
// 13
// 0
//
//
//
//
//
//
//
1
1
2
3
5
8
13
//
//
//
//
//
//
//
//
//
Element #1: 0
Element #2: 1
Element #3: 1
Element #4: 2
Element #5: 3
Element #6: 5
Element #7: 8
Element #8: 13
Number of elements in the array: 8
WHILE:
The while statement executes a statement or a block of statements until a
specified expression evaluates to false.
class WhileTest
{
static void Main()
{
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
}
}
/*
Output:
Current value of n is 1
Current value of n is 2
Current value of n is 3
Current value of n is 4
Current value of n is 5
*/