Imagine a situation where we need to display the same word on the screen, say the word "HELLO", 10 times. What do we do?
You can take and write a command 10 times cout << "HELLO";
But what if, it’s necessary not 10 times, but 20, 30, 40 times ?, and if 200 times? In this case, copying will take a very long time. And if it is necessary for the user to choose how many times he should display information on the screen?
To cope with the challenge, a special statement called LOOP
Loop - it is an algorithmic construction in which a certain sequence of commands is repeated several times.
In the C++ programming language, there are two types of loops: a loop with a variable (for) and a loop with a condition (while and do ... while)
We begin our acquaintance with the loops from the first view.
A LOOP WITH A VARIABLE OR WITH A KNOWN NUMBER OF STEPS (FOR)
It often happens that we know the number of repetitions of any action, or we can calculate the number of repetitions using the data we know. Some programming languages have a command like REPEAT (number of times) - that is, we can specify the exact number of repetitions.
It is interesting to trace how this loop works on a machine level:
1. a specific memory cell is allocated in memory and the number of repetitions is recorded in it,
2. When the program executes the loop body once, the contents of this cell (counter) are reduced by one.
3. The execution of the cycle ends when there is zero in this cell.
In the C ++ programming language, there is no such construct, but there is a for construct.
The general form of the for loop statement is as follows:
for (/*part 1*/; /*part 2*/; /*part 3*/ )
{
/* one or more statements - body of loop*/;
}
This statement requires us to
1. explicitly allocated a memory cell, which will be a counter, and set its initial value
2. write a condition under which the body of the cycle will be executed
3. indicated how it will change the value in this cell.
In the practical part, we will try to display the word Hello 10 times. And in further tasks we will analyze this construction in more detail.