Loops

by CameronM 4. February 2009 19:26

Loops enable blocks of code to be run a number of times depending on the results of an expression, sometimes called the loop-termination criteria.

while

As the name suggests, a while loop continues to execute while the condition expression remains true.

// while loop
int number = 0;
 
while (number < 3)
{
    Console.WriteLine(number);
    number++;
}

do

Similar to a while loop, the do loop executes a code block while an expression remains true. Unlike a while loop, a do loop checks the condition after running the code. This means that a do loop will always run at least once.

// do loop
int number = 0;
 
do
{
    Console.WriteLine(number);
    number++;
} while (number < 3);

for

The for loop runs a block of code until an expression is false. It is useful when you know the number of times to iterate through the code, such as when iterating through an array.

The basic syntax is as follows:

for (initializer; condition; iterator)

initializer: the initial condition

condition: a Boolean expression to evaluate

iterator: defines what to do after each iteration

In the example below, we first create a string array and then iterate through the array. A couple of things to note, arrays are zero-based, so your initializer i needs to be set to 0. The maximum value to compare against in the condition will be the length of the array, minus 1. After each iteration we’ll increase i by one. This will enable us to iterate through every value in the array.

// for loop
string[] people = new string[] { "Dave""Peter""Frank" };
 
for (int i = 0; i < people.Length; i++)
{
    Console.WriteLine(people[i]);
}

foreach

The foreach statement iterates through a collection of values and executes a block of code each time. It is useful for dealing with arrays and Collections types, such as List<>.

// foreach loop
string[] people = new string[] { "Dave""Peter""Frank" };
 
foreach(var person in people)
{
    Console.WriteLine(person);
}

Tags: ,

C#