Iteration Constructs: for Loop, foreach Loop, while , and do-while in C#

All programming languages provide ways to repeat blocks of code until a terminating condition has been met. Regardless of which language you have used in the past, the C# iteration statements should not raise too many eyebrows and should require little explanation. C# provides the following four iteration constructs:
• for loop
• foreach/in loop
• while loop
• do/while loop
Let’s quickly examine each looping construct in turn.



The for Loop
When you need to iterate over a block of code a fixed number of times, the for statement is the construct of champions. In essence, you are able to specify how many times a block of code repeats itself, as well as the terminating condition. Without belaboring the point, here is a sample of the syntax and ofcourse in C#:

// A basic for loop.
static void Main(string[] args)
{
// Note! 'i' is only visible within the scope of the for loop.
for(int i = 0; i < 10; i++)
{
Console.WriteLine("Number is: {0} ", i);
}
// 'i' is not visible here.
}

All of your old C, C++, and Java tricks still hold when building a C# for statement. You can create complex terminating conditions, build endless loops, and make use of the goto, continue, and break keywords. I’ll assume that you will bend this iteration construct as you see fit. Consult the .NET Framework 4.0 SDK documentation if you require further details on the C# for keyword.

The foreach Loop
The C# foreach keyword allows you to iterate over all items within an array, without the need to test for the array’s upper limit. Here are two examples using foreach, one to traverse an array of strings and the other to traverse an array of integers:
// Iterate array items using foreach.
static void Main(string[] args)
{
string[] books = {"Complex Algorithms",
"Do you Remember Classic COM?",
"C# and the .NET Platform"};
foreach (string s in books)
Console.WriteLine(s);
int[] myInts = { 10, 20, 30, 40 };
foreach (int i in myInts)
Console.WriteLine(i);
}


In addition to iterating over simple arrays, foreach is also able to iterate over system-supplied or user-defined collections. Hoever i will talk about this later, as this aspect of the foreach keyword entails an understanding of interface-based programming and the role of the IEnumerator and IEnumerable interfaces.

The while and do/while Looping Constructs
The while looping construct is useful should you wish to execute a block of statements until some terminating condition has been reached. Within the scope of a while loop, you will, of course, need to ensure this terminating event is indeed established; otherwise, you will be stuck in an endless loop.
In the following example, the message “In while loop” will be continuously printed until the user terminates the loop by entering yes at the command prompt:
static void Main(string[] args)
{
string userIsDone = "no";
// Test on a lower class copy of the string.
while(userIsDone.ToLower() != "yes")
{
Console.Write("Are you done? [yes] [no]: ");
userIsDone = Console.ReadLine();
Console.WriteLine("In while loop");
}
}

Closely related to the while loop is the do/while statement. Like a simple while loop, do/while is used when you need to perform some action for an undetermined number of times. The difference is that do/while loops are guaranteed to execute the corresponding block of code at least once (in contrast, it is possible that a simple while loop may never execute if the terminating condition is false from the onset).
static void Main(string[] args)
{
string userIsDone = "";

do
{
Console.WriteLine("In do/while loop");
Console.Write("Are you done? [yes] [no]: ");
userIsDone = Console.ReadLine();
}while(userIsDone.ToLower() != "yes"); // Note the semicolon!
}

Comments