Looping in C# - Part 2
By Xav
Following on from my other tutorial, http://forum.codecal...-looping-c.html, here we will discover the other three types of loop: while,foreach,do while.
The Foreach Loop
This loop is very useful, as it cycles through every object in an ObjectCollection. For every iteration of the loop, there is a local variable available which contains the current object. Here is the syntax:
[HIGHLIGHT=csharp]
foreach (*initialization* in *objectcollection*)
{
//Code goes here.
}
[/HIGHLIGHT]
Here is an example of a foreach loop:
[HIGHLIGHT=csharp]
int numbers = {1,2,3,4,5};
foreach (int num in numbers)
{
MessageBox.Show(num.ToString());
}
[/HIGHLIGHT]
The While/Do While Loop
The while loop executes until a certain condition is met. It takes the following syntax:
[HIGHLIGHT=csharp]
while (condition)
{
//Code goes here.
}
[/HIGHLIGHT]
Here is an example (which in this case could easily be done using a for loop):
[HIGHLIGHT=csharp]
int x = 0;
while (x < 10)
{
MessageBox.Show(x.ToString());
x++;
}
[/HIGHLIGHT]
The Do While loop is similiar:
[HIGHLIGHT=csharp]
do
{
//Code goes here.
} while (condition);
[/HIGHLIGHT]
For example:
[HIGHLIGHT=csharp]
int x = 0;
do
{
MessageBox.Show(x.ToString());
x++;
} while (x < 10)
[/HIGHLIGHT]
Differences between While and Do While
There is one main difference between the Do and Do While loops - the Do loop always executes at least once, as the condition is at the bottom, not the top. However, there is a chance that the Do While loop may never execute at all. Bear this in mind when writing your code.
Test yourself: Add some controls to a form. Write a program that cycles through all the controls, and displays the name of each one to the user in a message box. Hint: Use the Form.Controls[] ObjectCollection. Another hint: It's an object collection...
Hope this helps!
Xav
P.S. If this was helpful, please +rep. Leave any comments/suggestions/praise below!


Sign In
Create Account


Back to top









