View Single Post
  #1 (permalink)  
Old 05-27-2008, 09:50 AM
Xav's Avatar   
Xav Xav is offline
Code Slinger
 
Join Date: Mar 2008
Location: The North Pole
Posts: 11,010
Last Blog:
Web slideshow in JavaS...
Credits: 1
Rep Power: 86
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Default Tutorial: Looping in C#, Part 2

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:
  1. foreach (*initialization* in *objectcollection*)
  2. {
  3.  //Code goes here.
  4. }
Here is an example of a foreach loop:

csharp Code:
  1. int numbers = {1,2,3,4,5};
  2. foreach (int num in numbers)
  3. {
  4.  MessageBox.Show(num.ToString());
  5. }

The While/Do While Loop
The while loop executes until a certain condition is met. It takes the following syntax:

csharp Code:
  1. while (condition)
  2. {
  3.  //Code goes here.
  4. }
Here is an example (which in this case could easily be done using a for loop):

csharp Code:
  1. int x = 0;
  2. while (x < 10)
  3. {
  4.  MessageBox.Show(x.ToString());
  5.  x++;
  6. }
The Do While loop is similiar:

csharp Code:
  1. do
  2. {
  3.  //Code goes here.
  4. } while (condition);
For example:

csharp Code:
  1. int x = 0;
  2. do
  3. {
  4.  MessageBox.Show(x.ToString());
  5.  x++;
  6. } 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!
__________________


Mr. Xav | Website | Forums | Blog
Reply With Quote

Sponsored Links