Basics
C# Loops
Loop Structures
C# loops use for foreach and while with break and continue.
Introduction to C# Loops
Loops in C# are a fundamental concept that allow you to execute a block of code repeatedly. This can be useful for iterating over arrays, lists, or executing a task multiple times. C# provides several types of loops, including for, foreach, and while loops. In this guide, we'll explore how each of these loops works and demonstrate their usage with examples. Additionally, we'll introduce the break and continue statements, which provide control over the flow of loops.
The For Loop
The for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and increment/decrement. The loop continues to execute as long as the condition is true.
The Foreach Loop
The foreach loop is ideal for iterating over elements in a collection or an array. It automatically manages the iteration, making it easier to read and write than a for loop when working with collections.
The While Loop
The while loop continues to execute a block of code as long as a specified condition is true. It is particularly useful when the number of iterations is not known in advance.
Using Break and Continue
The break statement is used to exit a loop prematurely when a certain condition is met. On the other hand, the continue statement skips the current iteration and moves to the next one.
Conclusion
Understanding loops in C# is essential for writing efficient and concise code. Whether you're using a for, foreach, or while loop, knowing when and how to use each type is crucial. Additionally, break and continue statements provide greater control over your loop execution, allowing for more sophisticated logic.