C# – Loops

In programming often requires repeated execution of a sequence of operations. A loop is a basic programming construct that allows repeated execution of a fragment of source code. Depending on the type of the loop, the code in it is repeated a fixed number of times or repeats until a given condition is true (exists). Loops that never end are called infinite loops. Using an infinite loop is rarely needed except in cases where somewhere in the body of the loop a break operator is used to terminate its execution prematurely. We will cover this later but now let’s look how to create a loop in the C# language.

While loop

In the while loop, first of all the Boolean expression is calculated and if it is true the sequence of operations in the body of the loop is executed. Then again the input condition is checked and if it is true again the body of the loop is executed. All this is repeated again and again until at some point the conditional expression returns value false.

At this point the loop stops and the program continues to the next line, immediately after the body of the loop. The body of the while loop may not be executed even once if in the beginning the condition of the cycle returns false. If the condition of the cycle is never broken the loop will be executed indefinitely

The general form of the while loop is

while(condition) statement;

where statement can be a single statement or a block of statements, and condition defines the condition that controls the loop and may be any valid Boolean expression. The statement is performed while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop.

using System;
 class WhileDemo {
 static void Main() {
 int num;
 int mag;
 num = 435679;
 mag = 0; 
 Console.WriteLine("Number: " + num);
 while(num > 0) { 
 mag++;
 num = num / 10; 
 };    
 Console.WriteLine("Magnitude: " + mag);
 } 
}

The while loop works like this: The value of num is tested. If num is greater than 0, the mag counter is incremented, and num is divided by 10. As long as the value in num is greater than 0, the loop repeats. When num is 0, the loop terminates and mag contains the order of magnitude of the original value.

Do – While Loop

It is similar to a while loop, except that it tests the condition at the end of the loop body. The Do – While loop executes the loop once irrespective of whether the condition is true or not.

do { 
 executable code;
 }  while (condition); 
int[] numbers = new int[] { 6, 7, 8, 10 }; 

// Sum values from the array until we get a total that's greater than 10, 
// or until we run out of values.
 int sum = 0;
 int i = 0;
do {    
sum += numbers[i]; 
    i++; 
	} 
while (sum <= 10 && i < numbers.Length); 
 
System.Console.WriteLine(sum); // 13

The do-while loop is used when we want to guarantee that the sequence of operations in it will be executed repeatedly and at least once in the beginning of the loop.

For Loops

For-loops are a slightly more complicated than while and do-while loops but on the other hand they can solve more complicated tasks with less code. Here is the scheme describing for-loops:

For Loop

They contain an initialization block (A), condition (B), body (D) and updating commands for the loop variables (C). We will explain them in details shortly. Before that, let’s look at how the program code of a for-loop looks like:

for (initialization; condition; update)
 {  
 loop's body;
 } 

It consists of an initialization part for the counter (in the pattern int i = 0), a Boolean condition (i < 10), an expression for updating the counter (i++, it might be i– or for instance, i = i + 3) and body of the loop. The counter of the loop distinguishes it from other types of loops. Most often the counter changes from a given initial value to a final one in ascending order, for example from 1 to 100.

The number of iterations of a given forloop is usually known before its execution starts. A for-loop can have one or several loop variables that move in ascending or descending order or with a step. It is possible one loop variable to increase and the other – to decrease. It is even possible to make a loop from 2 to 1024 in steps of multiplication by 2, since the update of the loop variables can contain not only addition, but any other arithmetic (as well as other) operations.
Since none of the listed elements of the for-loops is mandatory, we can skip them all and we will get an infinite loop:

for ( ; ; )
 {  
 // Loop body
 } 
for (int i = 1, sum = 1; i <= 128; i = i * 2, sum += i) {
  Console.WriteLine("i={0}, sum={1}", i, sum);
 } 
i=1, sum=1 i=2, sum=3 i=4, sum=7 i=8, sum=15 i=16, sum=31 i=32, sum=63 i=64, sum=127 i=128, sum=255 

The foreach Loop

The foreach loop cycles through the elements of a collection. A collection is a group of objects. C# defines several types of collections, of which one is an array.

foreach will iterate over any object of a class that implements IEnumerable (take note that IEnumerable inherits from it). Such objects include some built-in ones, but not limit to: List, T[] (arrays of any type), Dictionary, as well as interfaces like IQueryable and ICollection, etc.

foreach(ItemType itemVariable in enumerableObject)    
 statement;
  • The type ItemType does not need to match the precise type of the items, it just needs to be assignable from the type of the items
  • Instead of ItemType, alternatively var can be used which will infer the items type from the enumerableObject by inspecting the generic argument of the IEnumerable implementation
  • The statement can be a block, a single statement or even an empty statement (;)
  • If enumerableObject is not implementing IEnumerable, the code will not compile
  • During each iteration the current item is cast to ItemType (even if this is not specified but compiler-inferred via var) and if the item cannot be cast an InvalidCastException will be thrown
var list = new List<string>();
 list.Add("Ion");
 list.Add("Andrei");
 foreach(var name in list) { 
    Console.WriteLine("Hello " + name);
 }

0 0 vote
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
1 Comment
oldest
newest most voted
Inline Feedbacks
View all comments
1
0
Would love your thoughts, please comment.x
()
x