Loops in C#
Tags: webdev, beginners, programming, coding
Published: 2023-09-05 03:43:57

Loops are control structures, allowing you to perform some action many times, depending on certain conditions. C# has the following types of loops:

- for

- foreach

- while

- do…while

**for loop**

The for loop has the following formal definition:

```cs
for ([actions_before loop execution]; [condition]; [actions after execution])
{ 
// actions
} 
```

The _for_ loop declaration has three parts. The first part of the loop declaration is some actions that are performed once before the loop is executed. This is usually where the variables to be used in the loop are defined.

The second part is the condition under which the loop will be executed. As long as the condition is true, the loop will run.

And the third part - some actions that are performed after the completion of the loop block. These actions are executed each time the loop block ends.

After the declaration of the cycle, the actions of the cycle are placed in curly braces.

Consider a standard for loop:

```cs
for (int i = 1; i < 4; i++)
{
    Console.WriteLine(i);
}
```
Here the first part of the loop declaration - int i = 1 - creates and initializes the variable i.

The second part is the condition i < 4. That is, as long as the variable i is less than 4, the loop will be executed.

And the third part - the actions performed after the completion of the actions from the cycle block - increasing the variable i by one.

The whole process of the cycle can be represented as follows:

The variable int i = 1 is defined

The condition i < 4 is checked. It is true (since 1 is less than 4), so the loop block is executed, namely the Console.WriteLine(i) statement, which prints the value of the variable i to the console

The loop block has finished executing, so the third part of the loop declaration, i++, is executed. After that, the variable i will be equal to 2.

The condition i < 4 is checked again. It is true (because 2 is less than 4), so the loop block is executed again - Console.WriteLine(i)

The loop block has finished executing, so the i++ expression is executed again. After that, the variable i will be equal to 3.

The condition i < 4 is checked again. It is true (since 3 is less than 4), so the loop block is executed again - Console.WriteLine(i)

The loop block has finished executing, so the i++ expression is executed again. After that, the variable i will be equal to 4.

The condition i < 4 is tested again. Now it returns false because i is NOT less than 4, so the loop terminates. Then the rest of the program is already executed, which comes after the loop

As a result, the loop block will run 3 times until the value of i becomes equal to 4. And each time this value will increase by 1. Executing the loop block once is called an iteration. So here the loop will execute three iterations. The result of the program:

```cs
1
2
3
```
If the for loop block contains one statement, then we can shorten it by removing the curly frees:

```cs
for (int i = 1; i < 4; i++)
    Console.WriteLine(i);
 
// or so
for (int i = 1; i < 4; i++) Console.WriteLine(i);
```
At the same time, it is not necessary to declare a variable in the first part of the loop, and change its value in the third part - these can be any actions. For example:

```cs
var i = 1;
 
for (Console.WriteLine("Begin loop"); i < 4; Console.WriteLine($"i = {i}"))
{
    i++;
}
```
Here again, the loop runs while the variable i is less than 4, only the increment of the variable i occurs in the loop block. Console output of this program:

```cs
Starting a loop
i = 2
i = 3
i = 4
```
We don't have to specify all conditions when declaring a loop. For example, we can write like this:

```cs
int i = 1;
for (; ;)
{
    Console.WriteLine($"i = {i}");
    i++;
}
```
Formally, the definition of the cycle remains the same, only now the blocks in the definition are empty: for (; ;). We don't have an initialized variable, no condition, so the loop will run forever - an infinite loop.

We can also omit a number of blocks:

```cs
int i = 1;
for (; i<4;)
{
    Console.WriteLine($"i = {i}");
    i++;
}
```
This example is essentially equivalent to the first example: we also have a counter variable, only it is defined outside the loop. We have a loop execution condition. And there is an increment of the variable already in the for block itself.
It's also worth noting that you can define multiple variables in a loop declaration:

```cs
for (int i = 1, j = 1; i < 10; i++, j++)
    Console.WriteLine($"{i * j}");
```
Here, in the first part of the loop declaration, two variables are defined: i and j. The loop is executed until i equals 10. After each iteration, the variables i and j are incremented by one. Console output of the program:

```cs
1
4
9
16
25
36
49
64
81
```
**do..while loop**

In a do loop, the loop code is executed first, and then the condition in the while statement is checked. And while this condition is true, the cycle repeats.

```cs
do
{
    cycle actions
}
while (condition)
```
For example:

```cs
int i = 6;
do
{
    Console.WriteLine(i);
    i--;
}
while (i > 0);
```
Here the loop code will run 6 times until i becomes zero. But it is important to note that the do loop guarantees that the actions will be performed at least once, even if the condition in the while statement is not true. That is, we can write:

```cs
int i = -1;
do
{
    Console.WriteLine(i);
    i--;
}
while (i > 0);
```
Although we have a variable i less than 0, the loop will still be executed once.

**while loop**

Unlike the do loop, the while loop immediately checks the truth of some condition, and if the condition is true, then the loop code is executed:

```cs
while (condition)
{
    cycle actions
}
```
For example:

```cs
int i = 6;
while (i > 0)
{
    Console.WriteLine(i);
    i--;
}
```
**foreach loop**

The foreach loop is designed to iterate over a set or collection of elements. Its general definition is:

```cs
foreach(datatype variable in collection)
{
    // cycle actions
}
```
After the foreach statement in parentheses, the variable definition comes first. Then the keyword in and then the collection, the elements of which must be iterated.

When executed, the loop sequentially iterates through the elements of the collection and places them in a variable, and thus in the loop block we can perform some actions with them.

For example, let's take a string. A string is essentially a collection of characters. And .NET allows you to loop through all the elements of a string - its characters with a foreach loop.

```cs
foreach(char c in "Tom")
{
    Console.WriteLine(c);
}
```

Here the foreach loop iterates through all the characters in the string "Tom" and puts each character into the character variable c. In the loop block, the value of the variable c is printed to the console. Since there are three characters in the string "Tom", the loop will be executed three times. Console output of the program:

```cs
T
O
M
```

It is worth noting that the variable that is defined in the loop declaration must match the type of the elements of the collection being iterated. So, the elements of a string are values ​​of type char - characters. So the variable c is of type char. However, in reality it is not always obvious what type the elements of a collection represent. In this case, we can define a variable using the var statement:

```cs
foreach(var c in "Tom")
{
    Console.WriteLine(c);
}
```

In the following, we will take a closer look at what collections are in .NET and which collections can be iterated with a foreach loop.

continue and break statements

Sometimes a situation arises when you want to exit the loop without waiting for it to complete. In this case, we can use the break statement.

For example:

```cs 
for (int i = 0; i < 9; i++)
{
    if (i == 5)
        break;
    Console.WriteLine(i);
}
```

Although the loop condition says that the loop will run until counter i reaches 9, in reality the loop will run 5 times. Since when the counter i reaches the value 5, the break statement will work, and the loop will end.

```cs 
0
1
2
3
4
```

Now let's set ourselves another task. But what if we want the loop to not end when checking, but simply skip the current iteration. To do this, we can use the _continue_ statement:

```cs
for (int i = 0; i < 9; i++)
{
    if (i == 5)
        continue;
    Console.WriteLine(i);
}
```

In this case, the loop, when it reaches the number 5, which does not satisfy the test condition, will simply skip this number and move on to the next iteration:

```cs
0
1
2
3
4
6
7
8
```

It is worth noting that the _break_ and _continue_ statements can be used in any type of loop.

**Nested Loops**

Some loops can be nested within others. For example:

```cs
for (int i = 1; i < 10; i++)
{
    for (int j = 1; j < 10; j++)
    {
        Console.Write($"{i * j} \t");
    }
    Console.WriteLine();
}
```

In this case, the for (int i = 1; i < 10; i++) loop is executed 9 times, that is, it has 9 iterations. But within each iteration, the nested for loop (int j = 1; j < 10; j++) is executed nine times. As a result, this program will display the multiplication table.

My [GitHub](https://github.com/ZafarUrakov)

References:
1.[metanit](https://metanit.com/sharp/tutorial/2.6.php)