C# Loops

The C# language provides four types of loop operations:
1. while statement
2. do statement
3. for statement
4. foreach statement

while statement:

While is an entry-controlled loop statement. The test condition is evaluated and if the condition is true. Then the body of the loop is executed. after the execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop. It has the following syntax:

initialization;
while(test condition)
{
body of the loop
}

do statement:

On the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the test in the while statement is evaluated. The test condition is evaluated and if the condition is true. Then the body of the loop is executed. after the execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again.

This process of repeated execution of the body continues until the test condition finally becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. It has the following syntax:

do
{
body of the loop
}
while(test condition);

for statement:

for is an entry-controlled loop that provides a more concise loop control structure. It has the following syntax:

for(initialization;test condition;increment or decrement)
{
body of the loop
}

foreach statement:

The foreach statement is similar to the for statement. It enables us to iterate the elements in Arrays, List and HashTables. It has the following syntax:

foreach(type variable in expression)
{
body of the loop
}