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

}

Example:
for (int i = 0; i < 5; i++)
{
    Console.WriteLine("Value of i: " + i);
}

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

}

Example:
int i = 0;
while (i < 5)
{
    Console.WriteLine("Value of i: " + i);
    i++;
}

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);

Example:
int i = 0;
do
{
    Console.WriteLine("Value of i: " + i);
    i++;
} while (i < 5);

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

}

Example:
string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
    Console.WriteLine("Name: " + name);
}

. 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);

}

Summary

These loop structures in C# offer a lot of flexibility for handling repetitive tasks based on different conditions.

Comments

Post a Comment

Popular posts from this blog