C# Examples

C# Example Code


C# Loop Controls

In C#, loop control statement allow you to execute a statement multiple times. C# has different veriety of loop statement such as for loop, while loop, do while loop, for each loop which will used based on programming requirment. Loop also usefull when you need to iterate arrays.

For Loop

For Loop consist of three variables initialization, condition and operation. Where initialization is used to set the initial value of the loop, condition is a boolean expression which decide whether the loop will continue and the operation to perform on the counter variable value.

Syntax

For Loop Example

For Loop With Break Example

For Loop Without Body Example

For Each Loop

For Each Loop is used to loop through the each element of array or collection. This is basically used to read all the elements in array or collections. The for each loop contains type variable and collection or array. Whereas type variable must be the same as type in the collection elements and collection could be any array or custome type array. Here type could be use as var also, in this case compiler will determine type at run time.

The improtant thing here is foreach loop through an array sequentially from start to end. It is similar to For loop except we don't have to define an incrementer and increment it and there is also no condition to be evaluated

Syntax

For Each Loop Example

For Each Loop With Array List Example

For Each Loop With Break Example

While Loop

In C# while loop executes a block of codes as long as a given condition or test expression is a true. In this loop, we define the incrementer outside the loop and then increment it inside the loop in a separate statement. If the given condition or test expression is a true then code block will be executed.

After the code is executed, the given condition or test expression will again be evaluated and the loop will continue till the given condition or the test expression is found to be true.

Syntax

While Loop Example

Do While Loop

Do While loop looks similar to While loop but it is different loop as compared to while loop because here the given condition is checked at the bottom of the loop. It is to be noted that do while loop is guaranteed to be executed at least one time.

Syntax

Do While Loop Example