|
Friday, 23 December 2011 00:02 |
The while loop
The while loop is probably the most simple one, so we will start with that. The while loop simply executes a block of code as long as the condition you give it is true. A small example, and then some more explanation:
while(number < 5)
{
Console.WriteLine(number);
number = number + 1;
}
The do loop
The opposite is true for the do loop, which works like the while loop in other aspects through. The do loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once.
do
{
Console.WriteLine(number);
number = number + 1;
} while(number < 5);
The for loop
The for loop is a bit different. It's preferred when you know how many iterations you want, either because you know the exact amount of iterations, or because you have a variable containing the amount. Here is an example on the for loop.
for(int i = 0; i < number; i++)
{
Console.WriteLine(i);
}
The foreach loop
The last loop we will look at, is the foreach loop. It operates on collections of items, for instance arrays or other built-in list types.
ArrayList list = new ArrayList();
list.Add("John Doe");
list.Add("Jane Doe");
list.Add("Someone Else");
foreach(string name in list)
{
Console.WriteLine(name);
}
 Read more: |