Loops in C#
Types of loop in c#-by Sagar Jaybhay
For, foreach, while and do while
These are 4 types of loop available in c#.
For and foreach are iteration based loops. In for loop, we required counter which will be initialized, use condition and increment or decrement.
Foreach loop: – Is basically used for iterating over the collection. And a collection of anything means inbuilt data type or user-defined types. When you used foreach loop then there is no need of initializing a counter, no condition checking and no increment of counter required.
You can use a break and continue inside of the loop. If you want to get outside of the loop on any specific condition then you can use the break statement.
While:-In while loop you need to initialize variable first then you need to put condition inside (). You need to increment or decrement the variable which you used in condition checking else the loop becomes never-ending. In a while loop condition is checked first and then control goes inside of while loop if the condition doesn’t fulfill it’s not executed that code inside the condition.
Do While: – In this loop, condition checking is done at the end of the loop. Means it guarantee the user loop will execute at least once.
What is the difference between while and do while loop?
In while loop condition checking at the beginning, and in do while condition checking is done at the end of the loop. Do while guaranteeing that it will execute at least once.