Type of variables for the for parameter. §9 Loop instruction with for parameter

Loops occupy a special place in Turbo Pascal. They begin to study them immediately after mastering the skills of input and output of information on the screen. After all, most problems come down to the fact that loops with a parameter and other constructs help facilitate the writing and functioning of a certain program block.

Types of cycles

There are three types in total:

  • with the parameter
  • with a precondition,
  • with a postcondition.

Loops with a parameter, otherwise they are called For ... to ... do or For ... downto .... do, repeat a certain sequence of actions many times. In principle, other varieties are used for the same purpose, only in the for loop the number of steps is known in advance.

In the other two constructs (While and Repeat), the number of iterations is initially unknown. Therefore, when studying the task, it is already necessary to understand which cycle will be used.

Basic definitions on the topic

Loops with parameters are repeated iterations. The counter is the main indicator with the help of which a given design is carried out. The boundaries of the interval show within what limits certain iterations will be performed. By the way, it is not at all necessary that the initial value be equal to 1. The user independently sets both boundaries of the interval. The body of the loop is a set of commands for which the number of repetitions has already been determined.

The concept of “loops with parameters” means that in this design a condition is checked, after which a set of iterations is performed. The counter increases (or decreases) and everything repeats. The body of the loop will be executed as long as the condition is true.

For ... to ... do: operating algorithm, syntax

As already mentioned, loops with a parameter are used in tasks that specify the “interval” in which to work. So, this could be an array of numbers, days of the week, lines of a poem, etc.

There are 2 types of design: for increasing the counter and for decreasing it. The first construction will be written as follows:

for original variable := border 1 to border 2 do

loop body;

Here: ref. variable declared by the user at the beginning of a program or block; border 1 and border 2- initial and final value of the interval; V body cycle a number of actions are prescribed that must be performed by the program. It must be remembered that if the body of the loop contains only 1 command, then the operator brackets begin...end can be omitted. In this version of the design, the counter, namely<исх.переменная>, will increase in increments of 1.

for original variable:= border 1 downto border 2 do

loop body;

Here is the ref. the variable will decrease in increments of 1.

The loop operation diagram with the For... to... do parameter will look like this:

  • The value of the upper boundary of the interval is set, i.e. border 2.
  • Source variable the parameter value is assigned border 1.
  • The condition is being checked: original variable ≤ limit 2.
  • Upon receiving the result True (True) the body of the loop is executed.
  • The counter is incremented by steps equal to 1.
  • Steps 3-5 are executed exactly until the condition is true: original variable > limit 2. As soon as this happens, the loop exits and control is transferred to the command following this construction.

In For... downto... do, the operating algorithm is similar to the above, with the exception of some points:

  • In the 3rd paragraph the condition is checked: original variable ≥ limit 2.
  • In the 5th line of the algorithm, the counter is decreased by 1.
  • In the 6th paragraph, commands 3-5 will be executed until the condition is satisfied: original variable< граница 2.

Everything else is similar in both operating algorithms.

Block diagram of a cycle with a parameter

Cycles with a parameter have the following block diagram (although it has already been presented above). A simplified organization of the design is also shown here.

Basic requirements for a cycle with a parameter

Loops with parameters require certain kinds of conditions.

  • The counter and span boundaries (i.e., source variable, boundary 1, and boundary 2) must be of the same data type. If there is only compatibility between the start and end values ​​of the segment and the source variable, then the program may behave incorrectly because the boundaries will be converted to the data type of the source parameter.
  • The data type to which the parameter values ​​must belong must be integer. It is highly recommended not to use the real type.
  • It is not advisable to forcibly change the value of the original variable parameter in the body of the loop. Otherwise, the user will have difficulty tracking down possible errors that may appear.
  • Unlike other types of loops, in For ... to ... do or For ... downto ... do the step cannot change by a parameter other than 1.

Turbo Pascal: how to break out of a loop

There are often problems in which looping occurs, i.e. the condition being checked is always true. The Break procedure helps to break out of loops with a precondition, postcondition, and parameter. That is, their work is terminated ahead of schedule.

Loops with pascal parameters (the programming of which assumes the “eternal” truth of the condition) can be stopped using Continue. Here the work is organized as follows: the current iteration ends its execution ahead of schedule, control is transferred to the next command, but without exiting the loop.

The Exit procedure is necessary in order to complete the work of a particular block in program code. It is called inside a procedure (function) and at the same moment, the execution of this “piece” immediately stops. If Exit is in the main block of the program, then it terminates its work.

The Halt procedure reduces the operating principle to the following: the program ends completely.

Examples of tasks with solutions

It will be useful for the user, after studying the topic “Loops with a parameter in Pascal,” to first study the examples and then practice writing code on their own. Simple tasks help the future programmer learn theory in practice, and then successfully apply it. On the topic “Loops with a parameter,” examples of problems with solutions can be found easy and complex. Here are 3 problems that explain the algorithms and provide explanations and comments for each solution.

Problem 1

Given a two-dimensional array of natural numbers in the range , chosen randomly. Find the number of all two-digit numbers whose sum of digits is a multiple of 2.

Algorithm of actions:

  1. Create a two-dimensional array.
  2. Check each number to see if it meets the following conditions:

a) if 9< Х < 100, то разделить его нацело на 10 посредством div;

b) select the second digit of a number by dividing via mod;

c) add the highlighted numbers;

d) divide the given amount by 2 using mod;

e) if the result is 0, then the counter is incremented by 1.

Problem 2

Dan one-dimensional array integer elements. Find the number of positive numbers.

Algorithm of actions:

  1. Create an array of integer elements created by randomize.
  2. In a loop with a parameter, insert an IF that will check the given element for compliance with the condition: X>0.
  3. If the condition is met, the counter is incremented by 1.
  4. After the cycle, the resulting counter value should be displayed on the screen.

Data given in parentheses () are comments. In line 11, you can display the array on the screen in two ways: leave a space between the numbers or allocate a certain number of cells for each element (in in this case there are 5 of them).

In line 12, the counter variable can also be increased in two ways: either by adding 1 to the previous value, or by using the standard Inc function.

Problem 3

Given a square matrix. Find the number of positive elements located on the main diagonal.

Explanations:

In an array of numbers, the main diagonal extends from the upper left corner to the lower right. Its peculiarity is the fact that the row and column indices coincide. Therefore, it is enough to organize 1 loop to move through the lines without enumerating the remaining elements.

Algorithm of actions:

  1. Create a square matrix.
  2. Assign the value “0” to the variable responsible for counting positive elements.
  3. Create a cycle to create a square matrix.
  4. Organize a loop to check the condition: if the number on the main diagonal is >0, then the counter is incremented by 1.
  5. After the loop ends, display the value of the variable storing the number of positive elements.

Confrontation between two programming languages: C and Turbo Pascal

As a rule, a self-respecting programmer knows several languages. For example, it could be C++, Turbo Pascal, Delphi, Java, etc. The opposition between the two of them was clearly expressed back in the 80s. (C and turbo pascal). At the end of the twentieth century, the same struggle was observed between C++ and Java.

In the virtual space, among three dozen programming languages, one can distinguish three of the brightest pairs, the confrontation of which amazed the greatest minds of cyberspace: ALGOL-60 and Fortran, Pascal and C, Java and C++. Of course, these feelings are subjective, but at one time or another one of the pair was the leader. This was explained by the requirements of industry and the need for one or another software product. In the 70s Fortran “ruled the world”, in the 80s - Turbo Pascal, in the 90s - C++. Of course, none of them "died". Rather, they have transformed into advanced software products.

When learning programming languages, you may notice that some topics have similar syntax. Thus, loops with a parameter in C are similar to similar constructs in Pascal, with the exception of some points.

It is interesting that the developers of Turbo Pascal (Old World) used the results of the developments of American scientists, while in the New World they actively applied the results of research by European specialists. In Europe, developers advocate more for the purity and compactness of programming languages, while American minds are more inclined to use newfangled trends in coding.

In most programs, there is a need to repeatedly execute a certain statement (or block of statements). Loop operators can be used to organize this kind of construction. The Pascal programming language uses the following types of loop operators: for, while, repeat (PascalABC.NET also uses the operator for loop each).

The block of statements that must be executed repeatedly is called the body of the loop.

for operator in Pascal

If number of body repetitions cycle is known in advance, then it is used for loop statement, which is also often called the loop operator with a parameter.

The for statement consists of two parts: the loop body and the header, which is intended to describe the initial and final values ​​of the loop parameter, as well as the option for changing it.

Depending on the direction of change of the loop parameter (increasing - to or decreasing - downto) in the Pascal language, the for loop operator can be written in one of two forms:

  • for parameter := start_value to end_value do
  • operator;
  • for parameter := start_value downto end_value do
  • operator;

The loop parameter variable can be any ordinal type. In this case, the initial and final values ​​must be of a type compatible with the type of the parameter variable.

Let's look at how the for loop works.

Before executing a loop statement, the initial value assigned to the parameter variable and the final value are calculated. Then the following operations are performed cyclically:

  1. The current value of the parameter is compared with the final value.
  2. If the condition parameter con_value is true, then the body of the loop is executed, otherwise the for statement completes its work and control is transferred to the operator following the loop.

Attention: in the Pascal language, the loop parameter, regardless of increasing or decreasing, changes by one each time.

Task. Display a list of squares of integers from 10 to 1.

Solution. In the problem stated, the cycle parameter decreases.

(Program code fragment)

  • for i:= 10 downto 1 do
  • writeln(i:2, " ", i * i);

Attention: if it is necessary to use more than one operator in the body of the loop, then a compound operator is used (operator brackets begin and end).

Example 2. The applicant’s grades on four exams are known. Determine the amount of points he scored.

Task. The applicant's grades on four exams are known. Determine the amount of points he scored.

Solution. We will use a loop operator with parameters in the program, since the number of repetitions of the actions performed is known (the applicant received exactly four marks)

(Program code fragment)

  • s:= 0;
  • for i:= 1 to 4 do
  • begin
  • readln(mark);
  • s:= s + mark;
  • writeln(s);

The for loop statement implements the algorithmic structure loop with parameter(or a loop with a counter). The for loop is used when in a program, before executing the loop instructions, the number of steps in this loop becomes known (or is predetermined). In a block diagram, the for statement is represented as follows:

Syntax:

For ( initialization; condition; modification) (Loop body instructions; )

If there is one instruction in the body of the loop, then ( ) can be omitted. The loop parameter variable (counter) can be of any numeric type. This makes the C++ for loop as versatile as a while loop. The modification section most often uses a postfix or prefix increment (or decrement) operation, but any assignment expression that changes the value of a loop parameter can be used. The cycle works like this:

  • At the beginning, the counter variable is described and initialized
  • Next, check the condition: if the expression has a value true, iteration will occur
  • After executing the instructions of the loop body, the counter value is modified

Note: In C++ it is a rule to make the declaration of the counter variable in the loop head. But this is not necessary, especially if you plan to initialize several variables in the initialization section as implemented in program 9.2. However, using a counter variable declaration in a loop header results in a local variable declaration that is destroyed automatically when the loop ends. Therefore, unless absolutely necessary, you should not define a counter variable outside a for loop.
While the for loop is running, it is not recommended to change the operands in the loop header expressions - this will lead to all sorts of errors! But the values ​​of variables (or constants), including changeable values ​​(counter), can be used. Let's look at a classic example.

Program 9.1 Given a natural number N. Print all divisors of this number.

#include << "N = "; cin >> N;< N / 2; i++) { if (N % i == 0) cout << i << " "; } return 0; } N = 16000 2 4 5 8 10 16 20 25 32 40 50 64 80 100 125 128 160 200 250 320 400 500 640 800 1000 1600 2000 3200 4000

for (int i = 2; i

Using the continue statement in a for loop

  • When using the continue statement in a for loop, you must take into account the peculiarities of how this loop works:
  • Statements following continue will be skipped
  • Move to the next iteration (otherwise, checking the condition)

Let's show this with an example: int main() ( for (int i = 1; i< 20; i++) { if (i % 2 == 0) continue; cout << i << " "; } 1 3 5 7 9 11 13 15 17 19

Note. Please note: although the output of numbers by condition is skipped, the counter is incremented. This example is for illustrative purposes only; this is not the way to program a loop! This problem is better solved as follows:

Int main() ( for (int i = 1; i< 20; i += 2) cout << i << " ";

Several expressions in the initialization and modification section

As we noted earlier, the head of the for statement must have three sections. Expressions in these sections can be omitted, but ";" cannot be omitted. . In the end, one can only leave; . Heading in the form:

For (;;) ( ... )

is the header of an “infinite” loop. (The exit from the loop must be programmed within the body of the loop.)
C++ supports several expressions in the initialization and modification sections of the head of a for statement. In this case, the condition for continuing the cycle must be one!
For example. Problem statement: Calculate the factorial of a number not exceeding 20.
Program 9.2

#include using namespace std; int main() ( unsigned long long n; int i, k; cout<< "k = "; cin >>k; // 0<= k <= 20 for(n = 1, i = 1; i <= k; n *= i, ++i); cout << k << "! = " << n << endl; return 0; } k = 20 20! = 2432902008176640000

Note: Note that the output stream on line 12 is not part of the loop body! (At the end of the title - ;). Thus, this loop has an empty instruction in the body, and all expressions are evaluated in the header. Program 9.2 correctly calculates the factorial of a number from 0 to 20.

range-based for loop

To iterate through the elements of an array or container, you have to perform the same type of actions and use cumbersome code. To simplify working with containers in C++, there is a special form of the for loop - range-based for (loop for range based or range for).
Syntax:

For ( announcement : sequence_name) loop_statement

Using range-based for using a C array as an example:
Program 9.3

#include using namespace std; int main() ( int x ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ); for (auto &s: x) ( cout<< s << " "; } return 0; }

In order for array elements to be changed, the variable s must be a reference variable (as in the example above). If the variable is not a reference, then the data will be copied. To automatically infer the type, this loop uses the auto specifier. range-based for has a limitation when working with dynamic arrays: it does not support changing the size of the array, since it contains a fixed pointer to the end of the array. When working with arrays that have a fixed size, range for is an excellent and safe alternative to regular for .

Nested for loops

Just like other loop statements, for supports a nested loop structure. Using nested for loops to organize the input and output of two-dimensional arrays is much more compact than using a while loop.
However, when solving problems of traversing such arrays, it is necessary to avoid using the conditional if statement. Often, the task can be implemented more rationally by manipulating the indices (loop variables i and j). That is, to make the change in one index dependent on the value of another. Let's look at two examples.
Program 9.4 Given a square matrix of size n, the elements of which are equal to 0. Fill the elements lying below and on the main diagonal with ones.

#include using namespace std; int main() ( int n; cout<< "n = "; cin >>n;< n; i++) for(int j = 0; j < n; j++) mas[i][j] = 0; // Реализация for(int i = 0; i < n; i++) for(int j = 0; j <= i; j++) mas[i][j] = 1; // Вывод for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cout.width(2); cout << mas[i][j]; } cout << "\n"; } return 0; } n = 10 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1

int mas[n][n];// Fill with zeros for(int i = 0; i


Program 9.5

#include using namespace std; int main() ( int n; cout<< "n = "; cin >Write a program to fill an array with numbers from Pascal's triangle and output this array. Pascal's triangle looks like:< n; i++) for (int j = 0; j < n; j++) pas[i][j] = 0; pas = 1; for (int i = 1; i < n; i++) { pas[i] = 1; for (int j = 1; j <= i; j++) { pas[i][j] = pas + pas[j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { cout.width(4); cout << pas[i][j]; } cout << "\n"; } return 0; } n = 12 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1

In this triangle, there are ones on the top and on the sides (in program 9.5 the triangle is “laid on its side” - the sides of the triangle are: the first column and the main diagonal). Each number is equal to the sum of the two numbers above it. The rows of the triangle are symmetrical about the vertical axis and contain binomial coefficients.
  1. >n;
  2. int pas[n][n];
  3. for (int i = 0; i
  4. Questions
Can a for loop instruction in a program be replaced by a while loop instruction? Can this always be done?
When is it more convenient to use the for statement to organize loops? while?
  1. Rear 29. Write a program that inputs natural numbers a And b, and the display shows all prime numbers in the range from a before b(algorithm idea Program 8.5)
  2. Rear 30. A number is called perfect if it is equal to the sum of all its divisors that are smaller than itself (for example, the number 6 = 1 + 2 + 3). Write a program that inputs a natural number N and determines whether N is a perfect number.
  3. Write a program that displays a square number table of size n x n, having the following form for n = 10: 1 * * * * * * * * * * 2 * * * * * * * * * * 3 * * * * * * * * * * 4 * * * * * * * * * * 5 * * * * * * * * * * 6 * * * * * * * * * * 7 * * * * * * * * * * 8 * * * * * * * * * * 9 * * * * * * * * * * 10
Literature
  1. Lafore R. Object-oriented programming in C++ (4th ed.). Peter: 2004
  2. Prata, Stephen. C++ programming language. Lectures and exercises, 6th ed.: Trans. from English - M.: LLC “I.D. William", 2012
  3. Lippman B. Stanley, Josie Lajoie, Barbara E. Mu. C++ programming language. Basic course. Ed. 5th. M: LLC “I. D. Williams”, 2014
  4. Elline A. C++. From lamer to programmer. St. Petersburg: Peter, 2015
  5. Shildt G. C++: Basic course, 3rd ed. M.: Williams, 2010



Hello, dear readers! Here we come to the study of cycles. Cycles in Pascal. What it is? How to use it? What are they needed for? These are the questions I will answer today.
If you have read, then you know that there are three types of algorithms: linear, branching and cyclic. You and I already know how to implement algorithms in Pascal. Let's start studying the last type of algorithms.
In Pascal, as in most programming languages, there are three types of looping constructs.

Any loop consists of a body and a header. The body of the loop is a set of repeated statements, and the condition is a logical expression, depending on the result of which the loop is repeated.

Let's take one problem that we will solve using different types of loops.

Task 1. Print all numbers from 1 to the number entered from the keyboard.

While, or loop with precondition

As you probably already understood from the title, while is a cycle in which the condition comes before the body. Moreover, the body of the loop is executed if and only if the condition true; as soon as the condition becomes false

While has the format:

while < условие> do<оператор 1>; (Bye...do....)

This loop is suitable for only one statement, but if you want to use multiple statements in your code, you should enclose them in statement brackets − begin And end;.

The solution of the problem.

Program example_while; var i, N: integer; (declare variables) begin i:= 1; ( Set i to 1 ) readln(N); (Read the last number) while i<= N do {Как только i станет больше N, цикл прекратится (можно было бы написать просто <, но пришлось бы добавлять 1 к N) } begin {Открываем операторные скобки} write(i, " "); {Выводим i} Inc(i); {увеличиваем i на один.} end; { закрываем скобки } end.

Repeat, or a loop with a postcondition

Repeat- complete opposite while. Repeat is a loop in which the condition comes after the body. Moreover, it is fulfilled if and only if the result of the condition false;as soon as the logical expression becomes true, the loop execution stops.

Repeat has the format:

repeat( repeat … )
<оператор 1>;
< оператор 2>;

until(before…) <условие>

Begin And end not required.

The solution of the problem.

Program example_repeat; var i, N: integer;( declare variables ) begin i:= 1; ( Set i to 1 ) readln(N); ( Read the last number ) repeat (begin and end are not required after repeat ) write(i, " "); (Output i) Inc(i); (increase i by one.) until i = N + 1; (For example, i = 11 and N = 10. The loop will stop, so the condition becomes true.) end.

For, or loop with a parameter

For is a loop in which the body is executed a specified number of times.

There are two forms of recording this cycle:

First form

for<счетчик1> := <значение1>to<конечное_значение>do<оператор1>;

<счетчик1>will increase by 1.

<значение1>is the initial value of the counter. It can be a variable or a number.
<конечное_значение>: as soon as value<счетчик1>there will be more<конечное_значение>

If you need to write several statements in the body of the loop, use begin And end.

AND<счетчик1>, And<конечное_значение>, And<значение1>- variables the whole type.

Most often, the variable i is used as a counter.

Second form

for<счетчик2> := <значение2>downto<конечное_значение>do<оператор1>;

After each iteration the value<счетчик2>will decrease by 1.

<значение2>is the initial value of the counter.
<конечное_значение>: as soon as value<счетчик2>will become smaller<конечное_значение>, the loop execution will stop.

Two important notes:

  1. The cycle is repeated as long as the counter value lies in the interval [value; final_value].
  2. Change the counter value inside the body it is forbidden! This is what the compiler outputs:

The solution of the problem:

Program example_for; var i, N: integer; begin read(N); (assuming we entered 10) for i:= 1 to N do write(i, " "); (number of iterations - 10 - 1 + 1 = 10) end.

Agree, this code is simpler and more concise than all the previous ones. And cycle for is not a very ordinary loop; it does not have a logical condition. That's why a loop with a parameter is called syntactic sugar in programming. Syntactic sugar is additions to the syntax of a programming language that do not add new features, but make the language more convenient for humans to use.

Let's solve a couple of problems.

For1. Given integers K and N (N > 0). Print the number K N times.

We organize a simple cycle from 1 to the required number.

Program for1; var K, N, i: integer; begin read(K, N);

for i:= 1 to N do write(K, " "); (We write K separated by a space) end.. < B). Вывести в порядке возрастания все целые числа, расположенные между A и B (включая сами числа A и B), а также количество N этих чисел.

For2< B, то цикл должен будет выводить все числа от А до B. Чтобы сосчитать количество чисел, используем формулу: <конечное_значение> — <начальное_значение> + 1.

Program for2; var A, B, i, count: integer; begin read(A, B);

for i:= A to B do write(i, " "); (we write down the numbers from smallest to largest) count:= B - A + 1; (count the number of numbers) writeln;. write("Number of numbers - ", count); end.< B). Найти сумму квадратов всех целых чисел от A до B включительно.

For9

Given two integers A and B (A

We organize the same cycle as in the previous problem, but at the same time we sum the squares of all numbers. To calculate the square, use the function.. Program for9; var A, B, i, S: integer; begin read(A, B);

S:= 0; (PascalABC does this automatically, but if you have a different compiler, we recommend that you reset the variables manually) for i:= A to B do S:= S + Sqr(i); (add all the squares) writeln;

write("Sum of squares - ", S); end.

For13°. An integer N (> 0) is given. Find the value of the expression 1.1 – 1.2 + 1.3 – … (N terms, signs alternate). Do not use conditional operator.

In order to change the sign, each iteration of the loop we change the value of the special variable to the opposite.

Program for13; var N, A, i: integer;

S: real; begin Write("N = ");.readln(N);

S:= 1.1;<>A:= 1; (Positive first) for i:= 2 to N do (we have already completed the first iteration of the loop, so we start counting from 2) begin A:= -A; (Now negative) S:= S + A * (1 + i / 10); (Add) end;

Writeln(S:5:1); (Let's give one place for the fractional part) end.

While1°