Module: (C++) Loops. Loop with parameter (for)


Problem

1/17

Programming Loops

Theory Click to read/hide

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.

Problem

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

1. we explicitly allocated a memory cell (i variable) that will be a counter and put the initial value in it  - i=1 
2. we write a condition under which the body of the loop will be executed - i<=10   - loop body (printf command) will be executed while the value in variable i is less than or equal to 10
3. indicated how it will change the value in this cell (i variable)  - i++ - after the execution of the loop body, the value of the variable i will increase by 1

START THE PROGRAM, MAKE SURE THAT IT WILL OUTPUT THE WORD "Hello" 10 times