Loops
In C# we have different kind of loops:
The while loop
The do loop
The for loop
The foreach loop
The while Loop
A while loop will
check a condition and then continues to execute a block of code as long as the
condition evaluates to a boolean value of true.
MessageBox.Show("Outside Loop: "+ myInt.ToString());
MessageBox.Show("Outside Loop: "+ myInt.ToString())
Example:
int myInt = 0;
while (myInt < 10)
{
MessageBox.Show("Inside
Loop: "+ myInt.ToString());myInt++;
}
MessageBox.Show("Outside
Loop: "+ myInt.ToString());
OUTPUT:
The do Loop
A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time. On the other hand, a while loop evaluates its boolean expression at the beginning and there is generally no guarantee that the statements inside the loop will be executed, unless you program the code to explicitly do so .
Example:
int myInt = 0;
do
{
MessageBox.Show("Inside
Loop: " + myInt.ToString());
myInt++;
} while (myInt
< 10);
MessageBox.Show("Outside Loop: " +
myInt.ToString());The for Loop
A for loop works
like a while loop, except that the syntax of the for loop includes
initialization and condition modification. for loops are appropriate when you
know exactly how many times you want to perform the statements within the loop.
Example:
for (int i = 0; i
< 10; i++)
{
MessageBox.Show("Inside
Loop: "+ myInt.ToString());myInt++;
}
OUTPUT:
The foreach Loop
A foreach loop is used to iterate through the items in a list. It
operates on arrays or collections.
Example:
for (int i = 0; i
< 10; i++)
{
MessageBox.Show("Inside
Loop: "+ myInt.ToString());myInt++;
}