C# Loops

Suppose you want to execute a set of statements 50 times in your program. Instead of writing the code 50 times, you can write the code inside a loop and specify a condition to execute the loop 50 times; thereby, saving the complexity and time involved in coding. an iteration statement or loop executes a statement or a set of statements in a repeated manner.

There are the following four types of iteration statements:

  • while loop - Evaluates a condition before executing a loop. The loop continues executing as long as the specified condition is true.

  • do...while loop - Executes the loop body at least once, before evaluating a condition.

  • for loop - Continues to execute the loop body until the condition specified in the loop becomes false.

  • foreach loop - Continues to execute the loop body for each element in an array or object collection.

While Loop

The while loop executes a statement or a block of statements as long as a Boolean expression (condition) evaluates to true. The while loop is mainly used in situations where you don't know in advance how many times the loop will be executed. The condition specified in the while loop is checked before starting the loop and the statements inside the loop execute as long as the specified condition is true. The loop terminates when the Boolean expression evaluates to false.

The following code snippet shows an example of the while loop:
int Number = 51;
  while (Number<=50)   //condition
  {
      Console.WriteLine("I will be executed 50 times");   //statement
      Number = Number + 1;   //Increment or decrement
  }

In the following code snippet, the condition is a Boolean expression and the statements can be any C# statements. Before the execution of any statement inside the while loop, the condition is evaluated. If the condition evaluates to true, the statements will be executed, otherwise not. Once the statements inside the while loop are executed, the program control is transferred to the starting point of the while loop to check the condition again for the next iteration.

Do...While Loop

The working of do...while loop is identical to that of the while loop, except that in the do...while loop, a condition is checked at the end of the loop after each iteration. It means that the do..while loop definitely executes at least once even if the condition is false. Unlike the while loop, a semicolon has to be placed after the while expression in the do...while loop; otherwise, the loop will not execute.

The following code snippet shows the syntax of the do...while loop:
int Number = 51;
  do{
    Console.WriteLine("I will be excuted 50 times ");   //statement
    Number = Number + 1;   //Increment of decrement
    }
  while(Number <= 50);   //condition

In the preceding code snippet, you can see that the Boolean expression inside the while block is not true but the loop is executed once, since in the do...while loop, the condition specified in the while block is checked after executing the loop once.

For Loop

The for loop is probably the most important of all loops. It works similar to the while loop, except that the syntax of the for loop also includes an initializer that initializes a variable and a loop expression that increments or decrements the variable's value. Unlike the while loop, the for loop is applied in the situation when you exactly know how many times you want to execute the statements.

The syntax of the for loop is as follows:
for (initializer; condition; loop expression){
 ....
 ....   //statments
 }

The description of the terms used in the preceding syntax is as follows:

  • initializer - Specifies the initial value of the variables used inside the loop. It is an expression that is evaluated before the first loop is executed. It is usually the initialization of a local variable as a loop counter.

  • condition - Specifies an expression that is checked before starting any new iteration of the loop. It must evaluate to true for another iteration to be executed.

  • loop expression - Specifies an expression that is evaluated after ending each iteration of the loop. You can use it for either incrementing or decrementing the loop counter.

The following code snippet shows the use of the for loop:
for ( int Number = 1; Number <= 50; Number++){
     console.WriteLine("I will be executed 50 times");
 }

In the preceding code snippet, the Number variable is initialized to 1. The loop iterates as long as the value of the Number variable are less than or equal to 50. After each iteration, the value of the Number variable increments by 1, and the statement inside the for loop executes as long as the specified condition inside the for loop is true.

Foreach Loop

The foreach loop iterates through all the items in a list. The list may be an array or a collection of objects. The foreach loop works the same as the for loop.

The syntax of the foreach loop is as follows:
foreach ( data_type variable_name in array_name){
     ....
     ....   //statements
}

The description of the terms used in the syntax is as follows:

  • data_type - Specifies the data type of variables. The data type of the variable and array must be the same.

  • variable_name - Represents the variable name that acts as a representative for each value of the item in the array_name array.

  • in - Denotes a keyword that is applied after the variable_name variable.

  • array_name - Represents the name of an array or a collection of objects, which you are accessing.

The following code snippet shows the use of the foreach loop:

string[] bookTitles = new string[] { "Alice in wonderland", "Pelican Brief", "Ignited Minds" };
foreach (string i in bookTitles){
 ....
 ....   //statements
}

In the preceding code snippet, an array of string type with the name bookTitles is defined and the foreach loop is used to the items of the bookTitles array.

In case, there exist one or more loops inside a loop then it is known as nested loops. For example, if a for loop is inside another for loop or do...while loop, then it is known as nested loops. You can also create an infinite loop if you do not want to terminate the loop. In an infinite loop, an unrealistic terminating condition is given, which is never met.



Write a comment


Name Email Message