Loops In C#

If we need to execute a line of code repeatedly until it reaches the defined condition, we make use of loops in C#. 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.

If we need to print the items of an array, use all of the loops one by one.

Using 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.

See the example below

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 the defined var and while it is less than the length of the int array it will go on increments of 1, each time the loop executes it.

WhileLoop

Using 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 the DoWhile loop to print the same array of items.

DoWhile Loop

Using For loop

For loop also checks the condition first and then executes if conditions are true the same as a while does, but in a 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

The foreach loop is used to iterate the items of a collection like Array, List, Generics, etc. For using foreach for the example given above, we do not need to calculate the length of the collection. We can directly print all the items one by one.

Foreach loop

Thank you.

Next Recommended Reading Looping Statements in C#