Cycles
Loops are control constructs, allowing you to execute some action multiple times depending on certain conditions. The following types of loops are available in C#:
-
for
-
foreach
-
while
-
do...while
For loop
The for loop has the following formal definition:
For ([actions_before_executing_the_cycle]; [condition]; [actions_after_executing])
{
// actions
}
The for loop declaration has three parts. The first part of the loop declaration is some actions that are executed once before the loop is executed. This is usually where the variables that will 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 be executed.
And the third part is some actions that are performed after the loop block is completed. These actions are executed every time the loop block is completed.
After the loop declaration, the loop actions themselves are placed in curly braces.
Let's consider the standard for loop:
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 i < 4 condition. That is, as long as the variable i is less than 4, the loop will be executed.
And the third part - the actions to be performed after completing the actions from the loop block - increments the variable i by one.
The whole process of the loop can be visualized as follows:
-
The variable int i = 1 is defined
-
The i < 4 condition is checked. It is true (because 1 is less than 4), so the loop block is executed, namely the Console.WriteLine(i) instruction, which displays the value of the i variable on the console.
-
The loop block has finished executing, so the third part of the loop declaration - i++ - is executed. After that, the i variable will be equal to 2.
-
The i < 4 condition 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 (because 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 checked again. Now it returns false because the value of the variable i is NOT less than 4, so the loop finishes execution. The rest of the program, which comes after the loop, is executed next
In the end, the loop block will run 3 times until the value of i is equal to 4. And each time this value will be incremented by 1. A single execution of the loop block is called an iteration. So here the loop will perform three iterations. The result of the program is:
1
2
3
If the for loop block contains one instruction, we can shorten it by removing the curly brackets:
for (int i = 1; i < 4; i++)
Console.WriteLine(i);
// or like this
for (int i = 1; i < 4; i++) Console.WriteLine(i);
It is not necessary to declare a variable in the first part of the loop and change its value in the third part - it can be any actions. For example:
var i = 1;
for (Console.WriteLine(“Begin loop execution”); i < 4; Console.WriteLine($“i = {i}”))
{
i++;
}
Here again the loop is triggered as long as the variable i is less than 4, only the incrementing of the variable i happens in the loop block. Console output of this program:
Start of loop execution
i = 2
i = 3
i = 4
We don't have to specify all the conditions when we declare the loop. For example, we can write it like this:
int i = 1;
for (; ;)
{
Console.WriteLine($“i = {i}”);
i++;
}
Formally, the loop definition remains the same, only now we have empty blocks in the definition: for (; ; ;). We have no initialized variable, no condition, so the loop will run forever - an infinite loop.
We can also omit a number of blocks:
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 condition of loop execution. And there is an increment of the variable in the for block itself.
It is also worth mentioning that you can define several variables in a loop declaration:
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, i and j, are defined. The loop is executed until i is equal to 10. After each iteration, variables i and j are incremented by one. Console output of the program:
do..while loop
The do loop first executes the loop code and then checks the condition in the while instruction. As long as this condition is true, the loop repeats.
Do
{
loop actions
}
while (condition)
For example:
int i = 6;
do
{
Console.WriteLine(i);
i--;
}
while (i > 0);
Here, the loop code will run 6 times until i is zero. But it is important to note that the do loop guarantees at least one execution of actions even if the condition in the while instruction is not true. That is, we can write:
int i = -1;
do
{
Console.WriteLine(i);
i--;
}
while (i > 0);
Even though we have a variable i less than 0, the loop will still execute once.
While loop
Unlike the do loop, the while loop immediately checks if some condition is true, and if the condition is true, the loop code is executed:
while (condition)
{
loop actions
}
For example:
int i = 6;
while (i > 0)
{
Console.WriteLine(i);
i--;
}
Foreach loop
The foreach loop is designed to loop through a set or collection of elements. Its general definition is:
foreach(type_data variable in collection)
{
// loop action
}
After the foreach statement, the variable definition comes first in parentheses. Then the in keyword and then the collection whose elements should be searched.
During execution, the loop sequentially searches the elements of the collection and places them into the variable, so we can perform some actions with them in the loop block.
For example, let's take a string. A string is basically a collection of characters. And .NET allows us to loop through all the elements of the string - its characters using foreach loop.
foreach(char c in “Tom”)
{
Console.WriteLine(c);
}
Here, the foreach loop runs through all the characters of the string “Tom” and places 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 execute three times. Console output of the program:
T
o
m
It is worth noting that the variable defined in the loop declaration must be of the same type as the elements of the collection being searched. For example, the elements of a string are values of type char - characters. Therefore, the variable c has the char type. However, in reality, it is not always obvious what type the elements of a collection are. In this case, we can define the variable using the var operator:
foreach(var c in “Tom”)
{
Console.WriteLine(c);
}
In what follows, we'll take a closer look at what collections are in .NET and which collections can be searched using the foreach loop.
The continue and break operators
Sometimes there is a situation when we need to exit a loop without waiting for its completion. In this case we can use the break operator.
For example:
for (int i = 0; i < 9; i++)
{
if (i == 5)
break;
Console.WriteLine(i);
}
Although the loop condition says that the loop will be executed until the counter i reaches the value 9, in reality the loop will be triggered 5 times. Because when the counter i reaches the value 5, the break statement will be triggered and the loop will terminate.
0
1
2
3
4
Now let's set ourselves another task. What if we want the loop to skip the current iteration instead of terminating during the check. For this purpose, we can use the continue operator:
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 that does not satisfy the check condition, will simply skip that number and move on to the next iteration:
0
1
2
3
4
6
7
8
It should be noted that the break and continue operators can be used in any type of loops.
Nested loops
Some loops can be nested within other loops. For example:
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 loop for (int i = 1; i < 10; i++) is executed 9 times, i.e. it has 9 iterations. But within each iteration, the nested loop for (int j = 1; j < 10; j++) is executed nine times. As a result, this program will print the multiplication table.