Writing program code using procedures. Conditional operator? Is the result of executing the statement

As the first operand - "expression1" - any expression can be used, the result of which is a value of type bool . If the result is true , then the operator specified by the second operand, that is, "expression2", is executed.

If the first operand is equal false , then the third operand is executed - "expression3". The second and third operands, i.e. "expr2" and "expr3", must return values ​​of the same type and must not be of type void . The result of the conditional statement is the result of "expression2" or the result of "expression3", depending on the result of "expression1".

Operator usage restrictions

The operator, based on the value "expression1", must return one of two values ​​- either "expression2" or "expression3". There are a number of restrictions on these expressions:

  1. You cannot mix a user-defined type with a simple type or an enum. It is legal to use NULL for a pointer.
  2. If the value types are simple, then the type of the operator will be the maximum type (see Casting).
  3. If one of the values ​​is of type enum and the other is of numeric type, then the enum is replaced with int and the second rule applies.
  4. If both values ​​are enum values, then their types must be the same, and the type of the operator will be an enum.

Restrictions for custom types (classes or structures):

  1. the types must be the same or one must inherit from the other.
  2. if the types are not the same (inheritance), then the child is implicitly cast to the parent, that is, the type of the operator will be the type of the parent.
  3. you cannot mix an object and a pointer - either both expressions are objects or pointers. It is legal to use NULL for a pointer.

Note

Be careful when using a conditional operator as an argument to an overloaded function, because the result type of the conditional operator is determined at compile time. And this type is defined as the larger type of the types "expression2" and "expression3".

Example:

void func(double d) ( Print ("double argument: " ,d); )
void func(string s) ( Print ("string argument: " ,s); )

bool Expression1=true;
double Expression2=M_PI;
string Expression3= "3.1415926" ;

void OnStart()
{
func(Expression2);
func(Expression3);

func(Expression1?Expression2:Expression3);
func(!Expression1?Expression2:Expression3);// get compiler warning about explicit cast to string type
}

// Result:
// double argument: 3.141592653589793

// string argument: 3.141592653589793
// string argument: 3.1415926

In the previous paragraph, we got acquainted with the structure of a Pascal program, learned how to describe data, and examined the assignment operator. This is enough to write a data conversion program. But the result of these transformations will not be visible to us.

To output data from random access memory on the monitor screen, the write output operator is used:

Here, in parentheses, the output list is placed - a list of expressions whose values ​​are printed. It can be numeric, symbolic and logical expressions, including variables and constants.

An arbitrary set of characters enclosed in apostrophes is considered a string constant. The string constant can contain any characters typed on the keyboard.

Example. The write ("s=" , s) statement is executed like this:

  1. characters enclosed in apostrophes are displayed on the screen: s=
  2. the value of the variable stored in the RAM cell named s is displayed on the screen.

If the value of the variable s is 15 and it has integer type, then the screen will display: s=15.

If the value of the variable s is 15, but it has a real type, then the screen will display: s=l.5E+01.

When an output statement is executed, all elements of the output list are printed directly one after the other. So, as a result of the operation of the write (1, 20, 300) operator, the sequence of digits 120300 will be displayed on the screen, which will be perceived by us as the number 120300, and not as three separate numerical constants. There are many ways to make the output data more accessible for perception:

Output Format is an integer specified after the colon, which determines how many positions on the screen the output value should occupy. If there are fewer digits in the number than the positions reserved for it on the screen, then the free positions are padded with spaces to the left of the number. If the number specified in the output format after the colon is less than necessary, then it will automatically be increased to the minimum required.

To output a real number in fixed-point format, two parameters are specified in the output list for each expression:

  1. the total number of positions allocated for the number;
  2. the number of positions in the fractional part of the number.

When a new write statement is executed, the output continues on the same line. To move to a new line, use the writeln statement. There are no other differences between the write and writeln statements.

4.2.2. The first Pascal program

Using the considered operators, we will compose a program that calculates the circumference and area of ​​a circle of radius 5.4 cm.

The initial data in this problem is the radius: r - 5.4 cm. The result of the program should be the values ​​C - the circumference and S - the area of ​​the circle. С, S and r are values ​​of real type.

The initial data and results are connected by the ratios known from the course of mathematics: С = 2πr, S = πr + . A program that implements calculations using these formulas will look like this:

This program is correct and solves the problem. Running it for execution, you will get the following result:

And yet, the program compiled by us has a significant drawback: it finds the circumference and area of ​​a circle for a single radius value (5.4 cm).

In order to calculate the circumference and area of ​​a circle for a different radius value, you will need to make changes directly to the program text, namely, change the assignment operator. Making changes to an existing program is at least not always convenient (for example, when the program is large and there are many assignment operators). Below you will get acquainted with the operator, which allows you to enter the initial data in the process of running the program, without resorting to changing the text of the program.

4.2.3. Keyboard entry

To enter the values ​​of variables into RAM, use the read input operator:

When a read statement is issued, the computer enters data-waiting mode: the user must enter data from the keyboard and press the Enter key. Several values ​​of variable numeric types can be entered separated by spaces or commas. When entering character variables, spaces and commas are treated as characters, so they cannot be set.

The first value of a variable entered by the user is placed in the memory location whose name is located first in the input list, and so on. Therefore, the types of input values ​​(input stream) must match the types of variables specified in the variable declaration section.

Example. Let

var i, j: integer; x:real; a: char;

Assign the variables i, j, x, and the values ​​1, 0, 2.5 and "A". To do this, we use the read (i, j, x, a) operator and organize the input stream in one of the following ways:

Here, we not only used different separators (space, comma), but also represented the input stream as one, two, and four lines.

To enter data from the keyboard, you can also use the readln statement, which differs from the read statement only in that after executing it, the cursor jumps to a new line.

Let's improve the program n_1 by organizing data input in it using the read statement. And so that the user knows what the program is intended for and understands exactly what action the computer expects from him, we will display the corresponding text messages using the writeln operator:

The result of the improved program:

Now our program can calculate the circumference and area of ​​a circle for any value of r. In other words, it solves not a single problem, but a whole class of problems. In addition, the program clearly and conveniently organizes the input of initial data and the output of the results. This provides a friendly user interface.

The most important

The read and readln input statements are used to enter variable values ​​into RAM.

The output operators write and writeln are used to output data from RAM to the monitor screen.

The input of initial data and the output of results should be organized clearly and conveniently; this provides a friendly user interface.

Questions and tasks

  1. Write a statement that provides the input of the value of the variable summa during program execution.
  2. The integer variables i, y, k should be assigned the values ​​10, 20, and 30, respectively. Write the input statement corresponding to the input stream:
      a) 20 10 30
      b) 30 20 10
      c) 10 30 20
  3. Describe the variables needed to calculate the area of ​​a triangle given its three sides, and write down an operator that provides the required input.
  4. What is the result of executing the statement?
      a) write (a)
      b) write (1 a ")
      c) write (1 a = 1, a)
  5. What type is the variable f if the following number was displayed after the write (f) statement was executed?
      a) 125
      b) 1.25E+2
  6. How can you display real number in fixed point format?
  7. Write down the statements for inputting two numbers and outputting them in reverse order.
  8. Given a fragment of the program:

    read(a); read(b); c:=a+b; write(a,b); write (s)

    Simplify it by reducing the number of input and output statements.

  9. Given a fragment of the program:

    a:=10; b:=a+l: a:=b-a; write (a, b)

    What numbers will be displayed on the computer screen?

  10. Write a program that calculates the area and perimeter of a rectangle given its two sides.

Operator is a language element that specifies a full description of the action to be performed. Each operator is a complete phrase of the programming language and defines some complete stage of data processing. Operators can include service words, data, expressions, and other operators. IN English language this concept is denoted by the word “statement”, which also means “proposal”.

Every operator in any programming language has a specific syntax And semantics. Under syntax operator is understood as a system of rules (grammar) that determines its record using the elements of the alphabet of a given language, which, along with various symbols, includes, for example, service words. Under semantics operator understand its meaning, i.e. those actions to which the record of this or that operator corresponds. For example, the entry i:= i + 1 is an example of a syntactically correct notation assignment operator in the Pascal language, the semantics of which in this case is as follows: extract the value of the memory cell corresponding to the variable i, add it to one, write the result to the same memory cell.

In most procedural programming languages, the set of operators is almost the same and consists of an assignment operator, selection operators, loop operators, a procedure call operator, jump operators. Sometimes there are also empty (no action) and compound operators. Many operators are a way of representing certain algorithmic constructs (see “ Algorithmic constructions”) in a programming language. Let's consider groups of operators in more detail, using the syntax of the Pascal language.

assignment operator

Assignment is a computer action, as a result of which the variable receives the value of the evaluated expression (it is placed in the memory cell corresponding to the variable). To describe such an action in programming languages, there is assignment operator.

In general, the assignment operator is written as follows:

<переменная> <знак присваивания> <выражение>

For example, in the Pascal language, the combination of characters: = is used as an assignment sign. In a number of other languages, the equals sign.

The result of executing the assignment operator is a change in the state of the data: all variables other than variable, standing on the left side of the assignment operator, do not change their value, and the specified variable gets value expressions, standing on the right side of the assignment operator. In most cases it is required that the type expressions matched the type variable. If this is not the case, then the operator is either considered syntactically incorrect, or the expression type is converted to the variable type (see “ Data types” ).

Selection operators

In another way, these operators are called conditional statements. Conditional statements are used to program algorithms containing the branching algorithmic construct.

There are several kinds of conditional statements in programming languages. The full conditional statement corresponds to the full branching algorithmic structure:

In a programming language, the corresponding conditional operator is:

if B then S1 else S2

If the expression B, which is evaluated at the beginning of the execution of the conditional statement, is true, then the statement will be executed S1, otherwise - the operator S2. Operators S1 And S2 may be composite.

The algorithmic structure of incomplete branching is implemented using an incomplete conditional operator, which has the form:

if B then S

Here B is a boolean expression, and S is an arbitrary operator. Operator S will be executed if expression B evaluates to true.

If the conditional operator implements only two choice branches (“yes” and “no”), then using variant operator (case-operator) you can program a multi-branch structure. The variant operator looks like:

case E of

Performed given operator like this: expression value E is searched among the values ​​listed in the operator record V1, V2, …, Vn, and if such a value is found, then the corresponding statement is executed S1, S2, …, Sn.

In different programming languages, the syntax and even the semantics of the listed operators may differ, but the opportunities provided to the programmer by such constructions are approximately the same.

Example 1 In the article " Algorithmic constructions”2, an example of writing an algorithm for solving a generalized quadratic equation using branching constructions was given. Here is a Pascal program fragment that implements the same algorithm:

if a = 0 then

if b = 0 then

if c = 0 then writeln("x - any")

else writeln("no roots")

else writeln(-c/b)

else begin

D:= b*b - 4*a*c;

if D< 0 then writeln("no roots")

else begin

x1:= -b + sqrt(D);

x2:= -b - sqrt(D);

writeln(x1:0:2,""", x2:0:2)

Loop statements

Loop operators implement cyclic algorithmic constructions, they are used for actions that are repeated many times. In many programming languages, there are three types of loop statements: “with precondition”, “with postcondition”, “with parameter”.

A necessary and sufficient algorithmic structure for programming loops is a “precondition” loop, so it can be called the main type of loop. The loop operator with a precondition has the form:

while B do S

Operator S, for the repeated execution of which a loop is created, is called loop body. The execution of the loop operator is reduced to the repeated execution of the loop body until the value of the logical expression B true (until it becomes false). In fact, such loop statements implement the repeated execution of conditional statements if B then S while condition is true B.

Example 2. Consider the use of such a loop operator to calculate the sum of digits of a natural number N:

while N > 0 do begin

S:= S + N mod 10;

N:= N div 10

In a loop with a postcondition, the body of the loop precedes condition B. In contrast to a loop with a precondition, here B is the end condition of the loop. The loop operator with a postcondition in Pascal has the form:

repeat S until B

With this organization of the cycle, the body of the cycle S must be executed at least once.

Almost all procedural languages ​​have loop operator with parameter. Schematically, it can be represented as follows:

for< variable > E1 to E2 step E3 do S

Here the value variable(cycle parameter) changes from the value of the expression E1 to E2 with step E3. For each such value of the loop parameter, the operator S is executed. In the Pascal language, the concept of a step in the description of this operator is absent, and the step itself for an integer loop parameter can be equal to either 1 or -1. The "loop with parameter" operator is used to program loops with a given number of repetitions. It is not suitable for programming iterative loops (the number of repetitions of which is not known in advance).

procedure call statement

In the article " subroutines” describes in detail about this kind of subroutines, as procedures. Standard subroutines of the programming language that are included in one of the libraries of subroutines, as well as user-defined subroutines described within this block, are called using the operator procedure call:

<имя процедуры>(E1,E2,…,En)

Here E1,E2,…,En are variables or expressions representing actual parameters referring to the procedure. The most commonly used standard procedures are the data input and output procedures (read and write in Pascal).

Calling a procedure is semantically equivalent to executing the block described as the body of the procedure after passing the initial values ​​of some variables (value parameters) into it or replacing the names of some variables (variable parameters) with the names of the actual variables specified when the procedure was called.

Example 3 Let us describe the procedure abc:

procedure abc(a,b:integer; var c: integer);

Calling this procedure abc(2,3,x) is equivalent to an action block:

Jump statements

The most famous in this group of operators is the unconditional jump operator goto. If we add to all or some of the already existing program statements labels, then in the program it becomes possible to use the transition operator of the form:

goto<метка>

The label in this case corresponds to the beginning of the statement from which the program execution should continue. Such an operator allows one to write algorithms in a programming language that have arbitrarily complex structure. But often the use of an unconditional transition is unjustified, because leads to a confusing, hard to read program. Almost the only meaningful use of the operator goto is the exit from several nested loops at once, for example, when processing two-dimensional arrays.

Example 4 Suppose we need to determine if there is an element equal to 0 in the two-dimensional array a:

for i:= 1 to N do

for j:= 1 to N do

if a = 0 then begin

1: if b then write("is") else write("no");

A program developed according to the rules of structured programming should not contain unconditional branch operators. The above program without using the statement goto can be rewritten like this:

while not b and(i< N) do begin

while not b and(j< N) do begin

if a = 0 then b:=true;

if b then write("is") else write("no");

In this case, the structural program is less visual than the program with goto.

Other jump operators may be defined in programming languages. For example, in Pascal: break(early interruption of the loop, transition to the statement that must be executed after the end of the loop), continue(early termination of the current loop iteration and transition to the next one), exit(early interruption of the subroutine, exit from it), halt(premature interruption of the program, transition to its end). Similar operators exist in C, C++, and Java.

Compound statement

A compound statement is a group of statements enclosed in brackets (in Pascal, beginend; in C, C++ - (…)).

The compound operator was introduced into programming languages ​​to facilitate the description of language constructs. For example, in Pascal, the executable part of each block (program, procedure, function) is a single compound statement. In exactly the same way, the body of any loop operator consists of only one operator, perhaps a compound one. An alternative to a compound statement can be a function word denoting the end of one or another statement, for example, END IF in the Basic language.

The topic “Programming Language Operators” is usually studied only in the context of a particular programming language. When considering it, it is important to show the connection between basic algorithmic constructions and operators: algorithmic constructions are written in a programming language using the corresponding operators. The exception in a certain sense is the sequential construction, it defines the linear order in which actions are performed. Actions in a strictly linear program are implemented only by assignment operators and procedure call operators.

On initial stage There are many problems in teaching programming to students. The first psychological barrier they have to overcome when learning the assignment operator. One of the main tasks that needs to be solved together with the students is the exchange of values ​​of two variables. You can invite students to mentally solve the problem of how to swap the contents of two drawers, for example, a desk. Usually, at this stage of the discussion, students guess that a third box (variable) is needed to solve the problem. However, when recording this algorithm they often confuse in which part of the assignment statement (left or right) this or that variable should be.

Errors in writing arithmetic and boolean expressions arise due to ignorance of the precedence of the operators that are used in the expression. At the same time, operations are understood not only as arithmetic, but also as comparison operations and logical connectives, and in the C language, as an assignment operation, which is very unusual for schoolchildren. The situation is complicated by the fact that in different programming languages ​​the same operations have different relative priorities. You should also pay attention to the correspondence between the types of the variable and the expression in the left and right parts of the assignment operator (see “ Data types”).

When mastering selection operators, it is useful to offer schoolchildren to program an algorithm containing a multi-branching structure, both using a combination of conditional operators and using a selection operator.

Example. into an integer variable N Enter the person's age in years. Type the phrase " I am K years old”, replacing the word years on year or of the year depending on number K. Here are two solutions to this problem:

if(k mod 100) in

then writeln("I am ",k," years old")

case k mod 10 of

0,5..9:writeln("I am ",k," years old");

1:writeln("I am ",k," year");

2..4:writeln("I am ",k," years old");

var k, n: integer;

readln(k); n:= k mod 10;

if(k mod 100) in

then writeln("I am ",k," years old") else

if n=1 then writeln("I am ",k," year")

if(n>=) and(n<= 4)

then writeln("I am ",k," years old")

else writeln("I am ",k," years old")

When considering loop operators, it is useful to propose the same task to be programmed in three different ways using three loop operators, and vice versa, by the condition of the problem, learn to determine which loop operator is most appropriate in a particular case.

The procedure call operator is only at first glance simple. Here it is important to explain the rules for passing parameters to procedures and functions, the difference between variable parameters and value parameters (in the latter case, we can pass not only a variable name, but also a constant or even an expression of the corresponding type). Formal and actual parameters must match in type but not in name, which is far from obvious to students.

Learning the conditional and especially the compound operator is a good opportunity to talk to students about programming style. There are several common ways to write structured programs in Pascal, but they all contain indentation to accommodate nested structures. Important for recording programs and comments.

Data output
Outputting data from RAM to the monitor screen:
write
(<выражение 1> ,< выражение 2> , ...,< выражение N>)
output list
Expressions - symbolic, numeric, logical,
including variables and constants
Example:
write("s=", s).
For s=15 the screen will show: s=15.
The information in quotation marks is displayed on the screen.
without changes

Output organization options
Option
withdrawal organization
No separators
Output operator
write(1, 20, 300).
Result
120300
Add delimiters write (1, ',' , 20,
- commas
’, ’, 300)
1, 20, 300
Add delimiters write (1, ‘ ‘, 2, ‘ ‘, 3)
- spaces
1 20 300

Output Format
The output format allows you to set the number of positions
on the screen occupied by the displayed value.
write (s:x:y)
x - the total number of positions allocated for the number;
y - the number of positions in the fractional part of the number.
Output operator
Execution result
operator
write('s=', s:2:0);
s=15
write('s=', s:3:1);
s=15.0
write('s=', s:5:1);
s=
writeln
15.0
- output from a new line!

First program
program n_1;
const pi=3.14;
var r, c, s: real;
begin
r:=5.4;
c:=2*pi*r;
The result of the program:
s:=pi*r*r;
writeln("c=", c:6:4);
writeln("s=", s:6:4)
TurboPascal
Version 7.0
end.
c=33.9120
s=91.5624

Keyboard entry
Entering variable values ​​into RAM:
read
(<имя переменной1>, …, <имя переменной N>)
input list
Executing the read statement:
1) The computer enters data standby mode:
2) the user enters data from the keyboard:
multiple variable values
numeric types can be introduced
separated by spaces or commas;
when entering symbolic variables
spaces and commas cannot be placed;
3) the user presses the Enter key.

Keyboard entry
!
Types of input values ​​must match
the types of variables specified in the declaration section
variables.
var i, j: integer; x: real; a: char;
read(i, j, x, a);
options for organizing the input stream:
1 0 2.5 A 1,0 1
2.5, A 0
2.5
A
After executing the readln statement, the cursor jumps to
new line.

Improved Program
program n_1;
const pi=3.14;
var r, c, s: real;
begin
writeln("Calculate the circumference and area of ​​a circle");
write("Enter r>>");
readln(r);
c:=2*pi*r;
The result of the program:
s:=pi*r*r;
writeln("c=", c:6:4);
Pascal Version 7.0
writeln("s=", s:6:4) Turbo
Calculating the circumference and area of ​​a circle
Enter r>> 8.5
end.
c=53.3800
s=226.8650

The most important
To enter variable values ​​into RAM
the read and readln input statements are used.
To output data from RAM to the screen
monitor, the write and writeln output statements are used.
The input of initial data and the output of results should
be organized clearly and conveniently; it provides
friendliness of the user interface.

Questions and tasks
1) Given a fragment of the program:
a:=10; b:=a+1: a:=b–a; write(a,b)
What numbers will be displayed on the computer screen?
2) Describe the variables needed for the calculation
the area of ​​a triangle along its three sides, and
write an operator providing input
necessary input data.
3) What is the result of executing the statement?
a) write(a)
b) write("a")
c) write("a=", a)
4) Integer variables i, j, k must be assigned
the values ​​are 10, 20 and 30 respectively.
Write an input statement corresponding to the input
flow:
a) 20 10 30
b) 30 20 10
c) 10,30,20