Looping in C# - Part 2
By Xav
Following on from my other tutorial,
http://forum.codecall.net/c-tutorial...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:
csharp Code:
foreach (*initialization* in *objectcollection*)
{
//Code goes here.
}
Here is an example of a foreach loop:
csharp Code:
int numbers = {1,2,3,4,5};
foreach (int num in numbers)
{
MessageBox.Show(num.ToString());
}
The While/Do While Loop
The while loop executes until a certain condition is met. It takes the following syntax:
csharp Code:
while (condition)
{
//Code goes here.
}
Here is an example (which in this case could easily be done using a for loop):
csharp Code:
int x = 0;
while (x < 10)
{
MessageBox.Show(x.ToString());
x++;
}
The Do While loop is similiar:
csharp Code:
do
{
//Code goes here.
} while (condition);
For example:
csharp Code:
int x = 0;
do
{
MessageBox.Show(x.ToString());
x++;
} while (x < 10)
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!