Module: cycles. Loop with parameter (for)


Problem

1/17

Loops in programming

Theory Click to read/hide

Imagine a situation where we need to display the same word on the screen, let's say the word "HELLO", 10 times. What should we do?
You can take and write the command 10 times writeln('HELLO');

But what if you need 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 that the user can choose how many times to display information on the screen? 

To cope with this task, we can use a special construction called LOOP

A loop is an algorithmic construction in which a certain sequence of commands is repeated several times.


In the Pascal programming language, there are two kinds of loops: a loop with a variable (for) and a loop with a condition (while)

Let's start our acquaintance with cycles from the first type.

LOOP WITH A VARIABLE OR WITH A KNOWN NUMBER OF STEPS (FOR)

It often happens that we know the number of repetitions of some actions, or we can calculate the number of repetitions using the data known to us. Some programming languages ​​have a command that in Russian sounds like REPEAT (number of times) - that is, we can specify the exact number of repetitions. 

It is interesting to see how this cycle works at the machine level:
1. a certain memory cell is allocated in memory and the number of repetitions is written to it,
2. when the program executes the loop body once, the contents of this cell (counter) is decremented by one.
3. loop execution ends when this cell is zero.

In the programming language Pascal, there is no such construction, but there is a for construction.  

The general form of the for loop statement is as follows:

for *start value* to *end value* do
begin
      /*one statement or block of statements - loop body*/;
end;
This construction requires that we
1. explicitly allocated a memory cell, which will be a counter, and set its initial value
2. Specify how the value in this cell will change.
3. a condition was written under which the loop body will be executed

In the practical part, we will try to display the word Hello 10 times. In the following tasks, we will analyze this construction in more detail.

Problem

The following program displays the word Hello 10 times.
Please note that we have completed 3 necessary steps

1. explicitly allocated a memory cell that will be a counter and put in it the initial value  - i := 1 
2. indicated how the value in the given cell will change  - to - after executing the loop body, the value of the i variable will increase by 1
3. registered the last value at which the cycle body will be executed - 10   - loop body (writeln command) will be executed as long as i is less than or equal to 10

RUN THE PROGRAM, MAKE SURE IT DISPLAYS THE WORD "Hello" 10 times