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

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

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

Foreach loop

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.

Thank you.

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now