Our Learning Journey

Loops in C#


In C#, a loop is a programming construct used to execute a block of code repeatedly until a specified condition is met. Loops are essential for automating repetitive tasks and iterating over collections of data. C# provides several types of loops:

for loop: A for loop iterates over a block of code a specified number of times. It consists of three parts: initialization, condition, and iteration expression. For example, if we want to count from 1 to 5, we’d use a for loop.

for (int i = 0; i < 5; i++)
{
    // Code to be repeated
    Console.WriteLine(i);
}

This loop starts with i being 1, keeps going as long as i is less than or equal to 5, and increases i by 1 each time.

while loop: A while loop repeatedly executes a block of code as long as a specified condition is true. We use this when we’re not sure how many times we need to do something, but we know the condition when we want to stop. For example, if we want to keep adding numbers until the total is less than 100, we’d use a while loop.

int total = 0;
int number = 1;
while (total < 100)
{
    // Do something here
    total += number;
    number++;
}

This loop keeps going as long as the total is less than 100. It adds the number to the total each time, and increases the number by 1.

do-while loop: A do-while loop is similar to a while loop, but it always executes the block of code at least once before evaluating the condition.

int i = 0;
do
{
    // Code to be repeated
    Console.WriteLine(i);
    i++;
} while (i < 5);

This loop prints the value of x and increments it by 1 each time, but it will always run at least once because the condition is checked after the first run.

foreach loop: A foreach loop iterates over elements in a collection, such as arrays, lists, or other enumerable types.

int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
    // Code to be repeated
    Console.WriteLine(num);
}

This loop goes through each number in the numbers array and does something with each one. Here, it prints each number to the console.

Each type of loop has its use cases and advantages. It’s essential to choose the appropriate loop depending on the situation to write efficient and maintainable code.

Leave a Reply

Your email address will not be published. Required fields are marked *