Light Mode Image

C# Loops

Loops are the control structures that allow you to repeat a block of code multiple times.

 

There are several types of loops in C#.

 

1. For Loop

The for loop is used when the number of iterations is known beforehand.

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

 

In this example, the loop will iterate five times, starting from i = 0 and incrementing i by 1 in each iteration until i is no longer less than 5.

 

2. While Loop

The while loop is used when the number of iterations is not known beforehand, and the loop continues as long as a specified condition is true.

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

 

This loop will continue executing as long as i is less than 5.

 

3. Do-While Loop

The do-while loop is similar to the while loop, but the condition is checked after the block of code is executed, so it always runs at least once.

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

 

This loop will also continue executing as long as i is less than 5.

 

4. ForEach Loop

The foreach loop is used to iterate over elements in an array or a collection.

int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
    // Code to be repeated for each element in the array
}

 

This loop automatically iterates over each element in the numbers array.

 

These are the basic loop constructs in C# that you can use to control the flow of your program and repeat specific actions.