Loops allow you to repeat a segment of code multiple times. C# has three basic types of loops. You choose the type of loop based on the type of task you need to perform. Your choices are as follows:
You can loop a set number of times with a for loop.
You can loop through all the items in a collection of data using a foreach loop.
You can loop while a certain condition holds true, using a while loop.
The for and foreach loops are ideal for chewing through sets of data that have known, fixed sizes. The while loop is a more flexible construct that allows you to continue processing until a complex condition is met. The while loop is often used with repetitive tasks or calculations that don't have a set number of iterations.