An operator is used to enter data on the screen. Data input and output in Pascal language. Data Output Operators

Program structure

The structure of a Turbo Pascal 7.0 program contains sections:

Let's consider the structure of the program using a specific example.

Let's create a new file in the editor window, the "Hello, World!" Program, which contains a greeting for the user:

Example 1

program Hello_World;

var Name: string;

Write (‘Enter your name:‘);

WriteLn (‘Hi,’, Name, ‘!’);

The first line of the program contains the name - "Hello_World", the program service statement indicates the name of the program, which is not a mandatory construction. Then we connect additional modules, this is indicated by the utility word uses. In the given listing of the program, the CRT module is connected, which performs the function of working with the screen in text mode.

The listing then uses the begin statement, which points to the beginning of the program body.

The next five lines contain the meaning of the entire program, which performs the sequence of actions:

  1. The screen is cleared of previous information (ClrScr;).
  2. The user is then prompted for a name (Write (‘Enter your name:’);).
  3. The user is expected to enter information into the variable Name (ReadLn (Name);).
  4. A greeting is displayed on the monitor (WriteLn (‘Hello,’, Name, ’!’);).
  5. The program waits for action from the user by pressing the Enter key to terminate the program (ReadLn;).

V last line the program contains an end statement with a dot at the end, which indicates the end of the program.

Comments can also be used in the listing. They refer to the non-executable part of the program that does not compile to machine code. Comments are made by the programmer to explain the operation of the program, its elements, operators, etc.

The comment can be formatted as follows:

  • as free text, bounded on both sides curly braces- (), (sometimes a comment can contain several lines);
  • as free text following the double "//" (in this case, the comment can contain only one line).

Here are some tips for beginner programmers:

  1. Before you start writing a program, clearly define what is the initial data and what result you want to get during the execution of the program.
  2. The type of variables should be chosen taking into account the range and required precision of data representation.
  3. It is recommended that you name your variables so that they reflect their purpose.
  4. When using keyboard input in your program, insert a line containing a prompt into the program code, and accompany the output with an explanation.
  5. Before starting the program, it is recommended to prepare test cases that will contain the initial data and the expected results. You can check the reaction of the program by entering incorrect initial data.
  6. When writing expressions, you need to pay attention to the priority of the operations.

Language Operators

Definition 1

An operator is the simplest structural unit of a program, which is designed to fix algorithmic actions by means of which data will be transformed, and to determine the order of performing these actions.

Operators work in the mode of automatic sequential execution in the program and are separated from each other by the symbol ";".

Operators are:

  • simple, i.e. not containing other operators;
  • composite, i.e. including additional operators.

Assignment operator (: =)

It is used to assign a new value to the variable. Format:

The value to be assigned or the expression must be compatible with the type of the variable.

Example 2

  • $ X: = Pi; $
  • $ Y: = Sqr (Z * Z + T * T) $;
  • $ Bool: = (I> 1) or (I

Data entry operators

These operators are used by the user to enter initial data into the program and have the form:

Read (x, y, z, ...);

Readln (x, y, z, ...);

where: x, y, z, ... are variable names.

The above operators allow the user to enter values ​​from the keyboard and assign them to the variables x, y, z, ....

The Readln (x, y, z, ...) operator differs from Read (x, y, z, ...) in that after entering the last variable, the cursor moves to the beginning of a new line.

Remark 1

You can use the input statement without parameters: Readln, which is placed before the last statement, end., To stop the program and show the result to the user.

Data Output Operators

The following operators can be used to display data on the screen:

  • Write (x, y, z, ...);
  • Writeln (x, y, z, ...);
  • Writeln.

Where: x, y, z, ... are the names of variables entered from the keyboard.

The Write (x, y, z, ...) statement displays the values variables x, y, z, ... in one line.

Using the Writeln (x, y, z, ...) statement in addition to displaying values ​​x, y, z, ... moves the cursor to the beginning of a new line after displaying the last value.

The Writeln statement skips the line containing the cursor to the beginning of a new line.

In the output statements, you can specify the width of the field, which is reserved for writing the value explicitly:

  • Write (y: m: n, x: k: l, ...);
  • Writeln (y: m: n:, x: k: l, ...).

m and k are the number of positions that are reserved for recording the integer part of the value of the variables y and x;

n and l is the number of positions that are reserved for recording the fractional part of the numbers y and x.

For example:

Example 3

Write ("Sum =", Sum); (displaying the text "Sum =", then the value of the sum, which is stored in the variable Sum) Writeln ("Enter", I, "- th element:").

To enter data in the Turbo Pascal language, there are standard operators (procedures) - READ and READLN, which are designed to read data both from the keyboard and from a file. This section deals with keyboard input only. Adding LN characters to the READ statement ensures that the cursor automatically jumps to a new line after entering data.

Operator format:

READ (a1, a2, a3, ..., an);

Here a1, a2, a3, ..., an are variables that are sequentially assigned values. If a READ statement is encountered in the program text, the computer pauses and waits for variable values ​​to be entered from the keyboard. When all the values ​​of the variables listed in the input statement have been entered, the program continues.

READLN;

which performs a line break as you enter data.

When entering data using the READ statement, the following basic rules should be kept in mind:

  • logical data in Turbo Pascal is not allowed;
  • when entering numerical data, the numbers are separated by a space or the end character (ENTER key). Input always ends by pressing the enter key - ENTER;
  • spaces before and between numbers are ignored, so they can be used in any amount;
  • if the variable is declared as Integer, its value is entered as an integer, i.e. it is not allowed to use a dot after a number;
  • if the variable is described as a real (Real), and its value is an integer, then you can enter the number as an integer (i.e. without a dot) and as a real number - with a dot. The conversion of an integer to a real number will be done automatically;
  • input of character data has some peculiarities. Since the space is a character, like any other character of the Turbo Pascal language, the character data must be entered as a continuous line;
  • one symbolic variable can be assigned the value of only one symbol;
  • pressing the ENTER key is interpreted as a character, therefore, for correct input of character data, it is recommended to put a newline READLN statement before each character data input statement so that they are entered on a new line.

TASK. Data input.

Program a4; Var a, b, c: integer; (Integer variables) x, y, z: real; (Variables of real type) s1, s2, s3: char; (Character variables) Begin Write (‘Enter a, b, c:’); Readln (a, b, c); (Entering integers: a period is not allowed when entering, but any number of spaces is allowed. Pressing Enter after entering the value of the variable c will download the READLN statement.) Write (‘Enter x, y, z:’); Readln (x, y, z); (Entering real numbers) Writeln (‘Enter s1, s2, s3:’); Readln (s1, s2, s3); (Enter the values ​​of symbolic variables. Input must be a continuous line.) End.

Let's enter the following initial data into the program:

x = 44.4, y = 47.5, z = 76

s1 = 'A', s2 = 'B', s3 = 'C'

Let us denote a space as you type. When entering numbers, we will separate them with a space. Any number of spaces are allowed between numbers. Then the monitor screen when entering data may look like this:

Enter a, b, c: 23 (between numbers)

Enter x, y, z: 44.447.576 (any number of spaces allowed)

Enter s1, s2, s3: A B C

Data output

The Write statement is used to output data from the computer memory to the monitor screen.

Operator format:

Write (a1, a2, a3, ..., an);

Here a1, a2, a3, ..., an can be either variables or a string of characters enclosed in apostrophes. All elements are listed separated by commas. Adding LN characters to the WRITE statement ensures that the cursor automatically jumps to a new line after data is output.

It is allowed to use an input operator without parameters

WRITELN;

which performs a line break, so the subsequent output statement with parameters will output the data on a new line. The parameterless output operator is often used to generate empty strings.

Parameters of the WRITE operator can be data of integer, real, logical, character, and also of the string type.

The location of the data on the monitor screen can be specified by the parameters of the WRITE statement, then the output is called output with data formats. If no formats are used in the WRITE statement, the output is called unformatted output or standard output.

Formatless output ... The presentation of the output data depends on the data type:

  • meaning logical type are displayed as logical values ​​TRUE and FALSE;
  • the values ​​of symbolic variables are displayed as corresponding symbols;
  • a character constant is displayed as it is written, but without apostrophes;
  • integer values ​​are displayed as integers;
  • real values ​​are displayed in floating point format.

In case of unformatted output, the allocated number of positions is equal to the size of the data. When displaying a character, one position is allocated; when displaying an integer, the number of positions is equal to the number of significant digits plus one position under the sign, if the number is negative. This must be taken into account when sequentially outputting data, for example numbers, so that the values ​​of different variables do not merge with each other.

EXAMPLE. Let's consider a fragment of the program:

var m, n: integer; begin n: = 1234; m: = 7890; write (n, m); end.

The write (n, m) operator; integers are displayed on the monitor screen: n = 1234 and m = 7890. Since output without data formats is used, the result will be:

The two numbers have merged. In order for the numbers not to merge, it is necessary to use separating spaces or spreading information on different lines.

write (n, '', m); (space between numbers)

Result:

1234 7890

or

Result:

1234

Formatted output ... To display real numbers, you must specify the format of the number representation in the WRITE operator, which looks like this:

WRITE (<переменная>: m: n);

where: m is an integer indicating the total number of positions allocated for the value of the variable, including the position under the sign of the number, the point and the number of digits of the fractional part; n is an integer specifying the number of digits in the fractional part.

The displayed information is aligned to the left. This suppresses the printing of leading zeros, i.e. if four positions were selected for displaying a number, then, for example, 6, and not 0006, will be displayed on the monitor screen.

Example. Let's print the value of the variable A, equal to 401.3 using the write operator (A: 8: 2). The monitor screen will display:

401,30
8 positions

The symbol indicates a space.

The output of real numbers is performed according to the following rules:

  1. If the number is shorter than m, then it will be padded on the left with spaces.
  2. If the number is longer than m, then the m parameter is ignored and the entire number will be displayed.
  3. If the fractional part is greater than the n parameter, then the number is rounded. Rounding does not change the value of the variable itself, only the representation of the number on the monitor changes.
  4. If the n parameter is not specified, then neither the fractional part of the number, nor the decimal point are displayed. The output is in floating point format.

As an example, consider printing real number in various formats.

program write; var x: real; begin x: = - 12345.12345; writeln ("Printing a real number": 50); writeln ("Fixed format printing"); writeln (x: 3: 0); writeln (x: 3: 1); writeln (x: 12: 5); writeln (x: 20: 5); writeln; writeln ("Printing in floating format"); writeln (x); writeln (x: 3); writeln (x: 5); writeln (x: 15); writeln (x: 16); end.

The result of the program:

Real number printing

Fixed format printing

Floating format printing

1.2345123450E + 04

1.234512345E + 04

To display integers, you must specify in the WRITE statement the format for representing the number, which looks like:

WRITE (<переменная>: k);

where:

k is an integer indicating the total number of positions allocated for the value of the variable.

The whole numbers do not have a fractional part, so there is no need to specify the number of positions of the fractional part in the format.

The interaction of the program with the external environment (user, other programs, stored data) is absolutely necessary. For such an interface in programming languages ​​are responsible input-output statements information. These instructions allow you to enter data into the program during the execution of the program (and not at the stage of its writing) and to output the calculated data in a human-readable form.

These commands allow you to enter data into single variables or into several variables at once during program execution from the keyboard. Input list items can be variable names that must be populated with values ​​entered from the keyboard.

The execution of input statements occurs as follows: the program is suspended, the cursor is displayed on the screen, the computer expects from the user a set of data for the variables whose names are indicated in the input list. The user from the keyboard enters the necessary signs in the order in which they are required by the input list, presses Enter. After that, the typed data gets into the corresponding variables and the program execution continues. Input data is separated by spaces.

When you enter the initial data, a conversion takes place from external form representation to the internal one, determined by the type of the variables. The variables that make up the input list can be of either integer, real, or character types. Reading raw data of a boolean type is not allowed.

The difference between the work of the Read and Readln statements in Pascal is as follows: after Read is executed, the value of the next data is read from the same line, and after Readln is executed, from a new line.

These operators allow you to display data from the output list on the monitor screen. The elements of the output list can be names of variables, expressions, constants. Before displaying the values ​​of the expressions, the computer calculates them first. The elements of the list, as well as in the input statements, are separated by commas.

The difference between the two operators of output in Pascal is as follows: after the execution of the operator Writeln (from the Write line), a transition to a new line occurs, and after the execution of the Write instruction, the transition to a new line does not occur and printing on subsequent output commands Write or Writeln will occur on the same line ... When you call the operator Writeln without parameters, you simply jump to a new line.

In BASIC, each new PRINT operator writes values ​​to a new line.

The variables that make up the output list can be of integer, real, character, or boolean types. In addition to variable names, expressions and strings can be used as an element of the output list.

Each value is output to a screen line in accordance with the width of the output field, which is determined by a specific implementation of the language.

The form of representation of values ​​in the output field corresponds to the type of variables and expressions: values ​​of an integer type are output as integer decimal numbers, of a real type - as real decimal numbers with decimal order, of a character type and strings - as symbols, a boolean type - as logical constants TRUE and FALSE.

Consider the procedure for reading information from a file in Pascal.

First, you need to declare a file variable. File variables have specific uses. You cannot perform any operations on them (assign a value, compare, etc.). They can only be used to perform file operations (reading, writing, etc.).

Before performing I / O, a file variable must be associated with a specific external file using the Assign procedure.

Assign (<Имя файловой переменной>,<Имя файла>);

The file name can be specified either as a string constant or through a variable of the type String. The file name must comply with the rules of the currently running operating system... If the name string is empty, then the file variable is associated with the standard input-output device (usually with the console).

After that, the file should be opened by one of the procedures:

Reset (<Имя файловой переменной>);

An existing file is opened for reading, the pointer of the current file component is set to the beginning of the file. If physical file that corresponds to the file variable does not exist, an I / O error occurs.

Rewrite (<Имя файловой переменной>);

A new empty file is opened for writing, it is given the name specified by the Assign procedure. If a file with the same name already exists, it is destroyed. After working with a file, it should, as a rule, be closed by the Close procedure.

Close (<Имя файловой переменной>);

This requirement must be met for the file that was written to.

Data input is the transfer of information from external devices into RAM. As a rule, the initial data of the problem being solved are entered. Output- reverse process when data is transferred from random access memory to external media (printer, display, magnetic devices, etc.). The results of solving any problem should be displayed on one of these carriers.

The main input-output devices at personal computer are the keyboard and the display (monitor screen). It is through these devices that the dialogue between the person and the PC is mainly carried out.

Read input statement

The keyboard input procedure (referring to the standard input procedure) has the following format:

Read (<список ввода>)

where<список ввода>is a sequence of variable names separated by commas. When inputting the initial data, there is a transformation from the external form of representation to the internal one, determined by the type of variables. The variables that make up the input list can be of either integer, real, or character types. Reading the original data of a boolean type in Pascal is not allowed. Source data values ​​can be separated from each other by spaces and by pressing the tab and Enter.

If the program has several operators read, then the data for them is entered by the stream, i.e. after reading the values ​​of variables for one operator read data for the next operator is read from the same line on the screen as for the previous one until the end of the line, then the next line is moved.

Another variant of the keyboard input operator is:

Readln (<список ввода>)

This operator is different from read only by the fact that after reading the last value in the list for one operator readln data for the next statement will be read from the beginning of a new line.

Write statement

The display statement (call to the standard output procedure) has the following format:

Write (<список вывода>)

The variables that make up the output list can be of integer, real, character, or boolean types. In addition to variable names, expressions and strings can be used as an element of the output list. When displaying several numbers on a line, they are not separated from each other by spaces. It is up to the programmer to take care of this separation.

The second variant of the display procedure:

Writeln (<список вывода>)

Its action is different from the operator write the fact that after displaying the last value in the list, the cursor moves to the beginning of the next line. Operator writeln written without parameters causes a line feed.

Each value is output to a screen line in accordance with the width of the output field, which is determined by a specific implementation of the language. The form of representation of values ​​in the output field corresponds to the type of variables and expressions: values ​​of an integer type are displayed as integer decimal numbers, of a real type - as real decimal numbers with decimal order, symbolic type and strings - as symbols, and a boolean type - as boolean constants TRUE and FALSE.

The output statement allows you to set the width of the output box for each item in the output list. In this case, the output list item has the form A: K, where A is an expression or a string, K is an expression or an integer constant. If the displayed value occupies fewer positions in the output field than K, then this value is preceded by spaces. If the displayed value does not fit into the width of the K field, then this value will be assigned required amount positions. For values ​​of a real type, an element of the output list can have the form A: K: M, where A is a variable or expression of a real type, K is the width of the output field, M is the number of digits of the fractional part of the displayed value. K and M are expressions or constants of integer type. In this case, the actual values ​​are displayed in fixed-point decimal form.

If you remember, when considering an example of the assignment operator, we were faced with the need to find out the result of the program execution. We figured out how to store information (in variables), how to process it (using expressions), but two fundamental information process remained out of our attention: receiving information and transmitting it to the world external to the computer. So far, our programs can only use information that is directly in the program text. It was also impossible to find out what values ​​the variables have at the moment. Programming in such conditions makes no sense.

The interaction of devices for processing and storing information with the external environment (at least with the user) is absolutely necessary. Operators of information input-output are responsible for such an interface in the Pascal language. These instructions allow you to enter arguments, calculation parameters during program execution (and not at the stage of writing it), to output the calculated data in a human-readable form.

First the input statements (statement formats):

Read (<Список ввода>);

Readln (<Список ввода>);

In this format, these commands allow you to enter data into variables during program execution from the keyboard. Input list items can be variable names that must be populated with values ​​entered from the keyboard.

The execution of input statements is as follows: the program is suspended, the cursor is displayed on the screen, the computer expects from the user a set of data for the variables whose names are indicated in the input list. The user enters the required values ​​from the keyboard in the order in which they are required by the input list, presses Enter. After that, the typed data gets into the corresponding variables and the program execution continues.

Note: data is separated by spaces when entering.

The difference between the work of the Read and Readln procedures (from the Read line) is as follows: after Read execution, the value of the next data is read from the same line, and after Readln execution - from a new line.

There are also two commands for displaying information in Pascal:

Write (<Список вывода>);

Writeln (<Список вывода>);

This format of using Write and Writeln allows you to display data from the output list on the monitor screen. The elements of the output list can be variable names, expressions, constants. The computer will first calculate the values ​​of the expressions before displaying them on the screen. The elements of the list, as well as in the input statements, are separated by commas.

The difference between the two output operators is as follows: after the execution of the Writeln statement (from the Write line), a transition to a new line occurs, and after the execution of the Write instruction, the transition to a new line does not occur and printing on subsequent Write or Writeln output commands will occur on the same line. When you call the operator Writeln without parameters, you simply jump to a new line.

Here is an example of using input and output operators:

Program Inteface;

Write ("Enter the radius of the circle"); (Print on screen asking for input)

Readln (R); (Entering a value into the R variable from the keyboard)

S: = 4 * ARCTAN (1) * SQR (R); (Calculating the area of ​​a circle (pR2))

Writeln ("Area of ​​a circle with radius", R, "equal to", S)

This program asks the user for the value of the radius of the circle, provides an opportunity to enter its value, calculates and displays the size of the area of ​​the circle with this radius. Thus, it becomes possible, without making changes to the text of the program, to enter different values ​​of the radius and obtain the corresponding values ​​of the area of ​​the circle. To do this, it is enough to run the program several times. This program also demonstrates the following rule: the output of the results should be commented so that the meaning of the printed numbers is clear. Indeed, we could have limited ourselves to Writeln (S), but the value of the number displayed by the program in this case would be clear only to the person who wrote this program.

INPUT AND OUTPUT OPERATORS

Let's consider the organization of data input and output from a terminal device. A terminal device is a device that a user operates with, usually a screen (display) and a keyboard. For data input and output, the standard input and output procedures Read and Write are used, operating with the standard serial files INPUT and OUTPUT.

These files are split into variable-length lines, separated from each other by a line terminator. The end of the line is set by pressing the ENTER key.

To enter the initial data, the operators of the input procedures are used:

Read (A1, A2, ... AK);

ReadLn (A1, A2, ... AK);

The first of them implements the reading of K values ​​of the initial data and the assignment of these values ​​to the variables A1, A2, ..., AK. The second operator implements reading K values ​​of the initial data, skipping the rest of the values ​​until the beginning of the next line, assigning the read values ​​to the variables A1, A2, ..., AK. The third operator implements the skipping of the input data line.

When inputting the initial data, there is a transformation from the external form of representation to the internal one, determined by the type of variables. Variables that make up the input list can be of either integer, real, or character types. Reading the initial data of a boolean type in the PASKAL language is not allowed.

Input statements skip leading spaces when reading values ​​of integer and real variables. At the same time, these operators do not skip spaces preceding the values ​​of character variables, since spaces are equal characters in strings. An example of writing input statements:

var rV, rS: Real;

iW, iJ: Integer;

................

Read (rV, rS, iW, iJ);

Source data values ​​can be separated from each other by spaces and by pressing the Tab and Enter keys.

To display the results of the program on the screen, the following operators are used:

Write (A1, A2, ... AK);

WriteLn (A1, A2, ... AK);

The first of these operators implements the output of the values ​​of the variables A1, A2, ..., AK to the screen line. The second operator implements the output of the values ​​of the variables A1, A2, ..., AK and the transition to the beginning of the next line. The third operator skips a line and moves to the beginning of the next line.

The variables that make up the output list can be of integer, real, character, or boolean types. In addition to variable names, expressions and strings can be used as an element of the output list.

Each value is output to a line of the screen in accordance with the width of the output field, which is determined by a specific implementation of the language.

The form of representation of values ​​in the output field corresponds to the type of variables and expressions: values ​​of an integer type are displayed as whole decimal numbers, of a real type - as real decimal numbers with decimal order, of a character type and strings - as symbols, and a boolean type - as logical constants TRUE and FALSE.

The output statement allows you to set the width of the output box for each item in the output list. In this case, the output list item has the form A: K, where A is an expression or a string, K is an expression or an integer constant. If the displayed value occupies fewer positions in the output field than K, then this value is preceded by spaces. If the displayed value does not fit into the width of the K field, then the required number of positions will be allocated for this value. For values ​​of a real type, an element of the output list can have the form A: K: M, where A is a variable or expression of a real type, K is the width of the output field, and M is the number of digits of the fractional part of the output value. K and M are expressions or constants of integer type. In this case, the actual values ​​are displayed in fixed-point decimal form. An example of writing output statements:

. . . . . . . . . . . .

var rA, rB: Real; iP, iQ: Integer;

bR, bS: Boolean; chT, chV, chU, chW: Char;

. . . . . . . . . . . .

WriteLn (rA, rB: 10: 2);

WriteLn (iP, iQ: 8);

WriteLn (bR, bS: 8);

WriteLn (chT, chV, chU, chW);

Tags. Unconditional Jump Operator.

Every house on the street has its own number, all people have their own names, even computer memory cells have their own address. All this is accepted in order to be able to unambiguously indicate the object being defined. Likewise, labels are used to indicate statements in programs.

A label in the Pascal standard is a non-negative integer. All labels used in the program must be listed in the label description section starting with service word Label, for example:

Only one operator can be marked with one label. The label is separated from the marked operator by a colon.

6: Writeln (14/2);

In all the programs given earlier, the statements were executed one after the other in the order in which they were written in the text. This algorithmic structure is called direct succession. However, in the Pascal language initially there is an operator that violates the straight-line execution of the program, transferring control to its arbitrary point. Such an instruction is called an unconditional jump and has the following format:

Goto<метка>;

The operator to which the transition occurs must be marked with this label.

Use the unconditional branch operator with extreme caution to avoid erroneous results or complete looping of the program. In general, the use of this command among programmers is considered bad form. As you will see, there is always a way to do without it.

ELEMENTS OF STRUCTURAL PROGRAMMING

A structured program (or subroutine) is a program composed of a fixed set of basic constructs. Let us consider the basic definitions and methods of forming these constructions in the schemes of algorithms.

Basic constructions are built from operations, forks and merges: follow, branch, cycle. Using only these three constructions, you can implement an algorithm for solving any problem.

The construction, which is the sequential execution of two or more operations, is called following.

A construction consisting of a fork, two operations, and a merge is called a branch. One of the operations may be missing.

A structure that has control lines leading to previous operations or forks is called a cycle.

The following, branching, and looping constructs can be thought of as operations, since they have a single input and a single output. An arbitrary sequence of operations can be thought of as a single operation.

The operation can be implemented by any PASKAL operator (simple or compound), or by a group of operators, with the exception of the GOTO operator.

In the PASKAL language, the number of basic constructions has been increased to six, these are:

Following;

Branching;

Loop with precondition;

Loop with postcondition;

Loop with parameter;

Conditional operator

One of the main algorithmic structures is branching (alternative).

If the condition is met, then instruction "1" will be executed, if not, then instruction "2". Although there are two actions in the schema, only one will be executed because the condition is either false or true. There is no third. Such a scheme allows solving problems in which, depending on the prevailing circumstances, it is required to perform one or another action. There is no doubt that the number of tasks of this kind is enormous. Moreover, it is very difficult to come up with real significant task, the execution algorithm of which would contain a simple direct following of commands. Even a primitive example taken from a mathematics course, as you will see, cannot be solved without using branching. So, you need to calculate the value of the expression y = 1 / x. You know that this function does not always matter, that is, not all argument values ​​have a result value. Our task is to compose an algorithm so that the executor does not get stuck in any case, even when receiving zero as an argument. It is not difficult to formulate this in natural language:

1. Get the value of x.

2. If x = 0, then report that the expression does not matter, otherwise - calculate y as 1 / x.

Thus, the above algorithmic structure is used. It can be expressed in simple words:

If<усл.>(If the condition is met)

then<действие 1>(then perform action No. 1)

otherwise<действие 2>(otherwise - perform action No. 2)

How to write this in Pascal? Yes, exactly the same, only in English.

Format conditional operator in Pascal:

If<условие>

Then<оператор 1>

Else<оператор 2>;

Note that there is only one statement in the Then and Else parts. But what to do in order to solve a problem in which, upon fulfillment or non-fulfillment of a condition, it is necessary to perform not one, but several actions? This is where the compound operator you already know comes to the rescue. Any number of operators can be enclosed in statement brackets.

A variant of the conditional operator in this case:

If<условие>

Then Begin<группа операторов 1>end

Else Begin< группа операторов 2>end;

The semicolon sign is not placed before the Else service word, but operators in groups are naturally separated from each other by this sign.

Now let's talk about the conditions. In Pascal programs, conditions are expressions whose value is a Boolean value. It can be either just a variable of the specified type, or a complex sequence of statements connected by logical operations.

V simple terms comparison signs can be used:> (greater than),<(меньше), =(равно), <>(not equal),> = (greater than or equal),<=(меньше или равно).

Examples of simple conditions: A = 5 (The value of variable A is 5)

(C + D3)> = (D1 * (45-2)) (The value of the expression on the left is greater than or equal to the value of the expression on the right)

S<>"ABC" (The value of the variable S is not equal to the string constant "ABC")

Let's give an example of solving one more problem: "Choose the largest of two numbers."

At first glance, the solution is obvious, but it is not as trivial as it seems.

Program Example;

Var A, B, C: Real; (A, B - for storing arguments, C - result)

Writeln ("Enter two numbers");

Readln (A, B); (Entering arguments from the keyboard)

If A> B Then C: = A Else C: = B; (If A> B, then the result is A, otherwise the result is B)

Writeln (C); (We display the result on the screen)

Another classic example: "Solve a quadratic equation using the given coefficients." This task is more complicated, so before writing the program, let's compose an algorithm by writing it in the form of a flowchart. First, we enter the coefficients, then we calculate the discriminant. Now two possibilities arise: either the absence of real roots in the case of a negative discriminant, or these roots can still be calculated and displayed in the case of a non-negative discriminant (the case of equality of the discriminant to zero is included here, there are two roots, only they are the same J).

When writing an algorithm in a programming language, one should take into account that there are not one action in the "no" branch, but three, therefore, a compound operator should be used. Do not forget to write arithmetic expressions in accordance with the rules of the Pascal language. Otherwise, this program is not more complicated than the previous one.

Var A, B, C, D, X1, X2: Real;

Writeln ("Enter the coefficients of the quadratic equation");

If D<0 Then Writeln ("Корней нет! ")

X1: = (- B + SQRT (D)) / 2 / A;

X2: = (- B-SQRT (D)) / 2 / A;

It is interesting that the conditional operator can act as an operator that is executed upon fulfillment or non-fulfillment of a condition. In this case, one speaks of nesting conditional statements. When solving this kind of problem, I highly recommend drawing up a flowchart in a notebook. Only then, when composing the program, you just have to carefully write the entire Then-part first, and then move on to the Else-part. Usually, when writing conditional statements in Pascal language (especially with multiple branches), commands are written with a ledge to the right and down. This improves clarity and, believe me, reduces debugging time.

To illustrate, let's solve one more problem: "Solve an equation of the form A * x ^ 2 + B * x + C = 0". Please do not confuse it with the quadratic equation, for which we knew that the coefficient A is not equal to zero. Here, the coefficients can be any numbers. Based on elementary mathematical reasoning, we get the following algorithm:

Var A, B, C, D, X, X1, X2: Real;

Writeln ("Enter the coefficients of the equation (A, B, C)");

If C = 0 Then Writeln ("X is any number")

Else Writeln ("No roots!")

Else Begin X: = - C / B; Writeln ("X =", X: 8: 3) End

If D<0 Then Writeln ("Корней нет! ")

X1: = (- B + SQRT (D)) / 2 / A;

X2: = (- B-SQRT (D)) / 2 / A;

Writeln ("X1 =", X1: 8: 3, "X2 =", X2: 8: 3)

Cycle. Types of Cycles.

A cycle is a multiple repetition of the same type of actions. We will call the body of the cycle the very actions that need to be repeated many times.

As you can imagine, you can repeat the same actions using the unconditional jump operator. If you write these actions in the program one by one, and at the end you put a jump operator to the beginning of this block. However, this way you can only get a program that runs forever (loops). This can be avoided by using a conditional operator in conjunction with the jump operator, making the execution of the jump dependent on the fulfillment of a certain condition. Thus, we get the structure of a conditional jump and the ability to organize the final loop. Generally speaking, this is how we can solve almost any problem that requires the implementation of a cyclic algorithm. Of course, you can build a house with just an ax. Let us ask ourselves the questions: "Will this house be beautiful? How much time and effort can be saved by using all kinds of special tools?" For what? - For convenience, brevity, ease of reading the program and, I'm not afraid of this word, beauty. So, there are three types of loop that have their own Pascal operators for writing them. These views have their own conventional names: "Bye", "Before", "With a parameter". They are somewhat different from each other and are used each for its own class of problems.

Cycle "BYE"

A group of operators called the "loop body", judging by this scheme, will be executed as long as the loop condition is true. The loop will exit when the condition is no longer met.

If the condition is false initially, then the body of the loop will not be executed even once. If the condition is initially true and there are no actions in the body of the loop that affect the truth of this condition, then the body of the loop will be executed an infinite number of times. This situation is called "looping". A looped program can be interrupted either by an operator (by pressing Ctrl + C), or by an emergency stop of the program itself, in case of overflow of a variable, division by zero, etc. come to an end.

In Pascal, the structure of the "Bye" loop is written as follows:

While<условие>Do<оператор>;

Isn't it laconic? In Russian, you can read it like this: "While the condition is true, execute the operator." Here, as in the conditional statement format, only one statement is meant to be executed. If more than one action is required, a compound statement can be used. Then the format of the operator takes the following form:

While<условие>Do

<оператор #1>;

<оператор #2>;

<оператор #3>;

Cycle "TO"

This type of loop differs from the previous one mainly in that the check for the repetition condition of the loop body is not in front of it, but after it. Therefore, the "Before" cycle is called a "postcondition" cycle, and "Bye" is called a "precondition" cycle.

Note also that a new iteration (re-executing the body of the loop) does not occur when the condition is true, but just when it is false. Therefore, the cycle got its name (execute the body of the cycle until the corresponding condition is met).