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 language 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 logical expression, depending on the result of which the loop is repeated.

Let's take one problem that we will solve using different kinds cycles.

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.

For2. < B). Вывести в порядке возрастания все целые числа, расположенные между A и B (включая сами числа A и B), а также количество N этих чисел.

Since A< 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.

For9. Given two integers A and B (A< B). Найти сумму квадратов всех целых чисел от A до B включительно.

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). Conditional operator do not use.

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); (We'll give it away fractional part one familiar place) end.

While1°. Given positive numbers A and B (A > B). A segment of length A contains the maximum possible number of segments of length B (without overlaps). Without using the operations of multiplication and division, find the length of the unoccupied part of the segment A.

Each time we subtract B from A as long as A - B >= 0.

Program while1; var A, B: integer; begin readln(A, B); while (A - B) >= 0 do A:= A - B; (As long as the difference is positive, we subtract. It is necessary to provide an option with a multiple of A and B, therefore >=) write(A); end.

While4°.An integer N (> 0) is given. If it is a power of 3, then print True; if it is not, print False.

We proceed as follows: while N is divisible by three, divide N by a whole. Then, if N = 1, the number is a power of three; if N<>1, then the number is not a power of three. In order to solve this problem, you need to know what it is and how it works.

Program while4; var N: integer; begin readln(N); while N mod 3 = 0 do N:= N div 3; (As long as the remainder of division by three is zero, divide N by a whole) writeln(N = 1); (boolean expression) end.

That's all for today! Don’t forget to visit our website often and click on the buttons located before the comments.

In general terms, today we will learn about each of the cycles in Pascal in more detail and see how they are defined. We'll sort it out while loop with precondition, for loop with parameter And repeat - until loop with postcondition.

1. Loop with a parameter in Pascal - FOR

The FOR loop sets a certain condition under which the program will work before it is executed. Let’s say we need to loop the program 5 (or n) times, then this can be easily done using this loop. U FOR loop There is a characteristic feature - a counter, which is usually designated by the letter i or j.

Appearance loop with a parameter in pascal:

for i:= 1 to n do // assign i first to one, then to two, three, ..., n

After the 1st pass, we assign 1 to the variable i, after the second we assign 2, and so on until we reach n. to - this is up to.. in ascending order, there is also downto - up to.. in descending order.

Block - cycle diagram with parameter:

2. Loop with precondition in Pascal - WHILE

A loop operator with a precondition performs actions an unknown number of times. The loop exits if some logical expression or its result turns out to be false. Since the validity of the logical expression is checked at the beginning, the body of the loop may not be executed even once.

Loop structure with precondition:

WHILE DO begin end;

A logical expression whose truth is checked at the beginning of the execution of the cyclic operator;

Any executable language statements.

Loop execution order:

While the condition is true, the body of the loop is executed. As soon as the condition becomes false, execution of the loop stops.

Block - diagram of a cycle with a precondition:


Note: rectangular blocks show any action that is performed in a loop or after it (loop step), while oval blocks show the beginning or end of the entire program or part of it. Main role in this block diagram its central part plays.

Example:

Task: calculate the sum of the series 1+1.5+2+2.5+3+3.5+ .. + 30

program example-while;

Var sum:real; n:real; BEGIN sum:=0; n:=1; while n

3. Loop with postcondition - Repeat - until.

This operator is similar to the loop operator with a precondition, but differs from it in that the condition is checked after the body (actions) of the loop are executed. This ensures that it is executed at least once, unlike previously parsed loops.

Please note that this operator loop implies the presence of several operators in the body of the loop, that is, several actions can be performed, so the service words Begin and End are not needed.

The sequence of operators included in the body of the loop is executed once, after which the condition written after the service word Until is checked. If the condition is not met, the loop ends. Otherwise, the body of the loop is repeated again, after which the condition is checked again.

Block diagram of a cycle with a postcondition:

Recording format, cycle structure:
REPEAT UNTIL;

Example:

Program test2; Var b:Real; Begin b:=100; Repeat b:=b/2; Until b

Conclusions:

1. A loop with a parameter uses a variable called a loop parameter or counter. Before the loop is executed, the parameter (counter) is set to its initial value. After completing a loop step, the parameter value is increased by one. The loop continues until the parameter reaches its final value, which is indicated after to (downto).

2. The precondition loop runs until the execution condition becomes false and continues if the condition is true.

3. The loop with a postcondition is executed until the condition becomes true, if the condition is false, the loop continues.

Probably every schoolchild knows a programming language called “Pascal”. What is it? This language has long been dead, because it is used only in schools to teach students and is considered a base language. It refers to a simplified version of the Algol language. But, unlike the latter, "Pascal" can be used to write real programs and even games. Previously, it was quite popular, but now it has been preserved only, essentially, for educational purposes. The first thing that attracts potential programmers to Pascal is the ability to write while preserving properties in English, and not rack your brains over the use of special schemes that are common in languages ​​like C.

Pascal was created by Niklaus Wirth in 1970. The language is named after the scientist Blaise Pascal, who became the father of the world's first machine. She could add two different numbers. A direct descendant of the Pascal language is Modula-2. The latter is an improved version.

Programming system

Pascal ABC is a programming language already introduced existing system. However, the one described is a new generation version.

Why was Pascal ABS created? There were two significant reasons for this:

  • outdated original language systems;
  • desire to create a more modern and integrated programming environment.

The language includes the classic Pascal system, Delphi elements and its own extensions. It appeared in 2002.

There is also a compiler of the same name, which is powerful and modern. It is capable of running on both Linux, macOS and Windows.

The .NET platform allows you to use some additional features, as well as programming in structural, object-oriented, and functional styles. By of this language became Mihalkovich. He was influenced not only by Pascal and Delphi, but also by C# and Python.

General characteristics of operators

Operators in a programming language are necessary in order to write a program. They make it possible to perform certain functions and algorithms. How do commands in Pascal differ from other elements? Because they imply the performance of some action. "Pascal" is designed in such a way that all operators consist of special function words. Commands are separated from each other and from other elements using the semicolon (;). All operators are conditionally divided into groups:

  • Simple. Such commands do not contain other elements. These are: (colon and equals), unconditional jump procedures (used for labels).
  • Structured. These operators consist of other elements: compound conditions, loops, append.

Both groups will be discussed in detail later in the article.

Procedure operator

This operator is required to call a procedure. In order to create a line in the programming environment, you must specify an identifier, followed by the call parameters. However, there are procedures in the language that do not have last element. In Pascal they are divided into two types:

  • standard (specified in the language itself);
  • custom (created by the programmer).

When specifying a certain set of elements in a line, one or another procedure is used.

Operators (“Pascal”), which are responsible for standard actions, are quite easy to remember. You must write the word uses in the descriptions section and enter a description of the procedure. There are some standard elements that do not need to be included in the first block. These are the tasks read, write and others.

User procedures must be created before running the program and placed in the description section or in a module. If the latter option is used, it should be written to the USES or PROCEDURE section.

Unconditional jump operator

Simple operators are quite easy to use, including GOTO. Pascal has a tags section that allows you to place a specific operator needed by the developer, and later refer to it using an unconditional jump. The label must be a set of numbers and letters without signs or spaces. It is separated from the line by a colon (:). Before you create a label, you must specify the names of this element in the descriptions section of LABEL.

Before creating a department, you need to know about some nuances:

  • all described tags must be used;
  • if elements have names made of numbers, then they can not be declared.

Unfortunately or fortunately, the GOTO operator is not used in modern programming languages. This is due to the fact that such systems, when operating, create the principle of a conveyor belt. And operators ("Pascal") such as GOTO disrupt the computational process.

Conditional operators

The conditional statement, represented by IF-THEN-ELSE constructs, is used to show branches in which one of the options is necessarily false. The computational process will continue according to one of the presented options. Conventionally, the process is divided into two types:

  • fork structure (when there are two options for action, and each leads to its own result);
  • traversal structure (when the second option is false, in which case the program traverses the result intended to be true).

The IF-THEN-ELSE construct represents structured statements. These words are service words. However, the latter is not subject to mandatory use.

How does the design work? From English it is translated as “if-then-else”. If the condition specified by the program is true, then what is written after the word then is executed. And if it is incorrect, then what is written after else or after the line with then is considered valid.

Compound operator

In order to understand this phrase, you need to know the definition. Compound statements ("Pascal") are a set of operations in a written program that are enclosed in BEGIN-END brackets. Due to this, the group of commands is presented as the only complete one.

Selection operator

Because the IF statement can only handle two branches, the CASE select command was created. This system has service words - case, of, end, else. However, the latter may also be absent. Before the statement can be executed, the parameter and its value must be declared. If the selection key matches the selection constants, then the statement that comes after the last one is executed. If it is not correct, then all commands are ignored. The option that comes after the word ELSE or after the CASE statement is executed.

This selection operator in Pascal does not use a system such as IF. There is no explicit condition checking here. If we look at its work in more detail, we can see that CASE introduces a slight dissonance into the program, since the statement ends with the word END, which does not have a paired BEGIN. It is much more convenient to use, especially if there are 5 or more options to choose from. Registration of IF-THEN will take a long time, and this is not a convenient process.

Operators ("Pascal"): loops

What are cycles? They involve repeating certain command systems several times until the condition is completely satisfied. There are two known in Pascal:

  • loop with parameter;
  • iterative.

What does each one represent? The first one always has known parameters. Sometimes it is also called regular. Its main difference is that the number of repetitions of the cycle is known before it begins.

In iterative, such a nuance is unknown. The loop continues until the condition is met.

You can distinguish between types and types of cycles using some structures:

  • REPEAT: repeat with postcondition.
  • WHILE: repeat with precondition.
  • FOR - count operator. It is used in a loop with a parameter.

The first two options are used for iterative repetition. The main difference between them and the last operator is that they can be used in a loop with a parameter, but FOR cannot be used for repetitions without a parameter.

I/O Operators

For the interaction of the programming environment with environment I/O operators are responsible. They allow you to enter information and display the result on the screen or in print. The read command will allow the user to running program indicate your details. How does this happen? The program stops for a while, and a blinking cursor appears on the screen, waiting for data input from a person. There is little difference in the operation of the two operators read and readln. The latter simply moves the cursor to the next line.

The output operator ("Pascal") is write(ln). The LN particle allows you to continue outputting data on the next line. If you specify a simple operator in the program, an empty term will be displayed on the screen. Use in this sense this command not necessary.

There are also operators var, close. They do not need to be used unless the program itself requires it.

Basic operators ("Pascal") are described in the article. They will help you write a better program, but they themselves work quite quickly and without failures. Without them, nothing will work out for the future programmer when working with the Pascal language. Unfortunately, it is impossible to imagine programs without operators. This means that they need to be able to operate. Loop operators may seem complicated, but with practice, the problems will all disappear. Good luck with your work!

When an algorithm needs to perform some action several times, loops are used. In programming, a loop is the repeated repetition of certain instructions. Loops consist of a header and a body. The header contains the conditions that determine the operation of the loop, and the body contains the repeating actions. IN YAP Pascal There are three types of cycles:

loop with parameter;

loop with precondition;

loop with postcondition.

Their execution algorithms are different, but they also have something in common: after executing the body of the loop, the condition is checked, and depending on it, the loop ends, or the body is executed again.

For - loop with parameter

A parameter loop, also known as a counter loop, is used for a known number of iterations. It has two notation forms:

  1. For<счетчик>:=< начальное значение>To<конечное значение>Do<тело цикла>;
  2. For<счетчик>:=<начальное значение>Downto<конечное значение>Do<тело цикла>;

Counter is an ordinal type variable. The start and end values ​​must be the same type as the counter. The body is executed as long as the condition is true.

The recording forms presented above differ in words To And Downto. If you use a loop with To, then the counter value will increase by one with each step, and if with Downto, it will decrease. It follows from this that in the first option the initial value should not exceed the final value, while in the second the opposite is true. In the program below, the number of times specified by the user will be displayed.

1
2
3
4
5
6
7
8
9
10

program for_primer;
uses crt;
var i, x: integer ;
begin
write ('X=' ) ;
readln(x);
for i:= 1 to x do
write (#3 , #6 ) ;
readkey;
end.

Here the body of the loop is not enclosed in Begin-End, since there is only one statement. But if there are more of them, then operator brackets are required. It is also worth noting that the counter upon exiting the loop will not have certain value, but if the cycle ends earlier than expected, the counter will save the last value written to it.

While – loop with precondition

Operator While– begins the description of the cycle with a precondition. This type of loop is needed in those algorithms where the number of repetitions is unknown in advance. In general it looks like this:

While<выражение>Do<тело цикла>;

If the expression is true, then the body is executed, otherwise the loop ends. Therefore, you need to write code such that at some iteration the expression becomes false and the loop does not run endlessly.

An example program written using the While loop:

In this code, the compound Begin-End operator was used, since there are several operators in the loop body.

Repeat – loop with postcondition

The main feature of a loop with a postcondition (often called DO loop) is that its body is executed at least once. This is due to the fact that the condition is written at the end and, accordingly, the body will be executed first, and then the condition will be checked. Formally, it looks like this:

<тело цикла>

Until<условие>

In contrast to the two loops discussed earlier, this one stops executing when the condition becomes true, i.e., for iterations to continue, the condition must be false. Let's look at the operation of a loop with a postcondition using an example:

1
2
3
4
5
6
7
8
9
10
11
12

Loop statements force the statements within them to be executed multiple times.

There are three types of loop operators in Pascal: loop operator with parameter, loop operator with precondition, loop operator with postcondition.

Loop statement with parameter

Format of a loop operator with a parameter:

for V:=E1 to E2 do S

where V is a variable of ordinal type, E1, E2 are expressions of the same type, S is an operator called the body of the loop. Expressions E1 and E2 are evaluated once when entering the loop. The V parameter first takes on the value E1, then the value immediately following it (SUCC (V)), etc. until reaching E2. For each value of V, the operator S is executed. If several operators need to be executed in the body of the loop, they are combined into one using compound operator. If the final value of E2 is less than the initial E1, then the operator S is not executed even once.

The loop operator with a parameter is also used in the following form:

for V:=E1 downto E2 do S

Unlike the first case, V changes from E1 to E2, moving from V to pred (V).

Note that if V, E1, E2 are of type INTEGER, then in the first case it is a cycle with step +1, and in the second with step -1.

Loop operator with precondition

Format of a loop statement with a precondition:

where B is a logical expression, S is an operator. Statement S will be executed as long as condition B is true. The loop statement will end when expression B evaluates to false for the first time.

Loop operator with postcondition

Format of loop statement with postcondition:

repeat S until B

where B is a logical expression, S is an operator. Statement S is executed until B evaluates to true. The REPEAT statement is executed at least once because the test for the truth of condition B occurs after the execution of statement S.

Function words REPEAT and UNTIL already act as parentheses, so the BEGIN and END parentheses are optional.

Example programs

As an example of using loop operators, consider a program for calculating factorial.

Program 2.1.1. Cycle with parameter (step +1)

PROGRAM FACTORIAL1;

VAR I,N:INTEGER;

WRITE("ENTER N");

READLN(N); F:=1;

FOR I:=1 TO N DO F:=F*I;

Program 2.1.2. Loop with parameter (step -1)

PROGRAM FACTORIAL2;

VAR I,N:INTEGER;

WRITE("ENTER N");

READLN(N); F:=1;

FOR I:=N DOWNTO 1 DO F:=F*I;

WRITELN("FACTORIAL OF ",N," EQUAL TO ",F)

Program 2.2. Loop with precondition

PROGRAM FACTORIAL3;

VAR I,N:INTEGER;

WRITE("ENTER N");

READLN(N); F:=1; I:=1;

WHILE I<=N DO

WRITELN("FACTORIAL OF ",N," EQUAL TO ",F)