In C#, loops are used to execute a block of code repeatedly until a specified condition is met. Here are the main types of loops you'll encounter in C#: for
, while
, do..while
, and foreach
.
for
LoopThe for
loop is used when you know in advance how many times you want to execute a statement or a block of statements.
Syntax of for
Loop:
Example of for
Loop:
This loop will print the numbers 0 through 4.
while
LoopThe while
loop executes a block of code as long as a specified condition is true.
Syntax of while
Loop:
Example of while
Loop:
This loops continuously checks the condition before executing the block of code.
do..while
LoopThe do..while
loop is similar to the while
loop, but it checks the condition after executing the block of code. This guarantees the code block is executed at least once.
Syntax of do..while
Loop:
Example of do..while
Loop:
This loop ensures that the block of code runs at least once before checking the condition.
foreach
LoopThe foreach
loop is used to iterate over elements in a collection, such as an array or a list, without needing an explicit index.
Syntax of foreach
Loop:
Example of foreach
Loop:
This loop will print each fruit in the fruits
array.
Here's a complete example showing all types of loops:
These loops provide a versatile way to repeatedly execute code in your programs. If you have any specific questions or need more detailed examples, feel free to ask!