loops in C#

loops in cshap

Loops repeat action so you don't have to write same logic again and again. loops helps to execute a line of code repeatedly until it reaches the defined condition. There are various loops in C# programming; i.e., While Loop, Do While loop, For loop, Foreach loop. Let's try to use each of them for a simple example.

Let's understand the loop one by one with example.

While Loop


While loop checks the condition first and then executes the defined line of code, if the condition is true and keeps on executing as long as the condition is true. If the condition is false, it will get out of the while loop.

Below we have example to demonstrate the while loop

We have defined a static integer array of length 3. We need to print all the items present in the defined array. While loop will continue to print as long as defined var and whileInt is less than the length of int array as whileInt will go on increments of 1, each time the loop executes it.


while loop




DoWhile Loop


DoWhile loop checks the condition at the end of the loop due to which DoWhile loop guarantees to execute at least once and keep on executing as long as the defined conditions remain true. Let's see how to use DoWhile loop to print the same array items.



dowhile


For loop


For loop also checks the condition first and then executes if conditions are true the same as while does, but in while loop, we make initialization of the variable first and a condition check is done at the different places. But in  the for loop, both are done at the same place.

for loop


Foreach loop


Foreach loop is used to iterate the items of a collection like Array, List, Generics, etc. We do not need to calculate the length of the collection. We can directly print all the items one by one.
let us under with the example.

foreach

Summary

  1. we understood about diffrent types of loop with example.
  2. we had a look on While loop
  3. we had a look on DoWhile loop
  4. we had a look on For loop
  5. we had a look on Foreach loop

Comments

Popular Posts

How to position controls using Canvas control in WPF using MVVM

Change font and size in visual studio

DataGrid in WPF MVVM