loops in C#
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.
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.
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. 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.
Summary
- we understood about diffrent types of loop with example.
- we had a look on While loop
- we had a look on DoWhile loop
- we had a look on For loop
- we had a look on Foreach loop
Comments
Post a Comment