In C#, loops allow you to execute a block of code repeatedly based on a condition or until a certain condition is met. Here are the main types of loops in C#:
1. for Loop
The for loop is used when you know the exact number of times you want to execute a statement or a block of statements.
for (initialization; condition; increment/decrement)
{
// Code to execute
}
2. while Loop
The while loop repeats a block of code as long as a specified condition is true. It's often used when the number of iterations is unknown and depends on some runtime conditions.
Syntax:
while (condition)
{
// Code to execute
}
3. do...while Loop
The do...while loop is similar to the while loop, but it ensures the code block executes at least once before checking the condition.
do
{
// Code to execute
} while (condition);
4. foreach Loop
The foreach loop iterates over each element in a collection, such as an array or a list. It's especially useful for collections where you don't need to modify elements and just want to access them.
Syntax:
foreach (var item in collection)
{
// Code to execute
}
. break and continue Statements
break: Exits the loop immediately.continue: Skips the current iteration and moves to the next one.
Example with break and continue:
for (int i = 0; i < 10; i++)
{
if (i == 5)
break; // Exits loop when i is 5
if (i % 2 == 0)
continue; // Skips even numbers
Console.WriteLine(i);
}

amazing 🤩
ReplyDeleteWonderful
ReplyDelete