Algol (Несколько текстов для зачёта), страница 3

2015-12-04СтудИзба

Описание файла

Файл "Algol" внутри архива находится в папке "3". Документ из архива "Несколько текстов для зачёта", который расположен в категории "". Всё это находится в предмете "английский язык" из 5 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "остальное", в предмете "английский язык" в общих файлах.

Онлайн просмотр документа "Algol"

Текст 3 страницы из документа "Algol"

Strings are either constants or stored in an array of character type. There are no predeclared identifiers for string types because there is no need to use them in a declaration.

Constant strings which consist solely of characters in the range 0X..0FFX and strings stored in an array of SHORTCHAR are of type Shortstring, all others are of type String.

 

7. Variable Declarations

Variable declarations introduce variables by defining an identifier and a data type for them.

VariableDeclaration

=

IdentList ":" Type.

Record and pointer variables have both a static type (the type with which they are declared - simply called their type) and a dynamic type (the type of their value at run-time). For pointers and variable parameters of record type the dynamic type may be an extension of their static type. The static type determines which fields of a record are accessible. The dynamic type is used to call methods (see 10.2).

Examples of variable declarations (refer to examples in Ch. 6):

i, j, k: INTEGER

x, y: REAL

p, q: BOOLEAN

s: SET

F: Function

a: ARRAY 100 OF REAL

w: ARRAY 16 OF

RECORD

name: ARRAY 32 OF CHAR;

count: INTEGER

END

t, c: Tree

 

8. Expressions

Expressions are constructs denoting rules of computation whereby constants and current values of variables are combined to compute other values by the application of operators and function procedures. Expressions consist of operands and operators. Parentheses may be used to express specific associations of operators and operands.

8.1 Operands

With the exception of set constructors and literal constants (numbers, character constants, or strings), operands are denoted by designators. A designator consists of an identifier referring to a constant, variable, or procedure. This identifier may possibly be qualified by a module identifier (see Ch. 4 and 11) and may be followed by selectors if the designated object is an element of a structure.

Designator

=

Qualident {"." ident | "[" ExpressionList "]" | "^" | "$" | "(" Qualident ")" | ActualParameters}.

ExpressionList

=

Expression {"," Expression}.

ActualParameters

=

"(" [ExpressionList] ")".

If a designates an array, then a[e] denotes that element of a whose index is the current value of the expression e. The type of e must be an integer type. A designator of the form a[e0, e1, ..., en] stands for a[e0][e1]...[en]. If r designates a record, then r.f denotes the field f of r or the method f of the dynamic type of r (Ch. 10.2). If a or r are read-only, then also a[e] and r.f are read-only.

If p designates a pointer, p^ denotes the variable which is referenced by p. The designators p^.f, p^[e], and p^$ may be abbreviated as p.f, p[e], and p$, i.e. record, array, and string selectors imply dereferencing. Dereferencing is also implied if a pointer is assigned to a variable of a record or array type (Ch. 9.1), if a pointer is used as actual parameter for a formal parameter of a record or array type (Ch. 10.1), or if a pointer is used as argument of the standard procedure LEN (Ch. 10.3).

A type guard v(T) asserts that the dynamic type of v is T (or an extension of T), i.e. program execution is aborted, if the dynamic type of v is not T (or an extension of T). Within the designator, v is then regarded as having the static type T. The guard is applicable, if

  1. v is an IN or VAR parameter of record type or v is a pointer to a record type, and if

  2. T is an extension of the static type of v

If the designated object is a constant or a variable, then the designator refers to its current value. If it is a procedure, the designator refers to that procedure unless it is followed by a (possibly empty) parameter list in which case it implies an activation of that procedure and stands for the value resulting from its execution. The actual parameters must correspond to the formal parameters as in proper procedure calls (see 10.1).

If a designates an array of character type, then a$ denotes the null terminated string contained in a. It leads to a run-time error if a does not contain a 0X character. The $ selector is applied implicitly if a is used as an operand of the concatenation (Ch. 8.2.4) or a relational operator (Ch. 8.2.5) or the standard functions LONG and SHORT (Ch. 10.3).

Examples of designators (refer to examples in Ch.7):

i (INTEGER)

a[i] (REAL)

w[3].name[i] (CHAR)

t.left.right (Tree)

t(CenterTree).subnode (Tree)

w[i].name$ (String)

 

8.2 Operators

Four classes of operators with different precedences (binding strengths) are syntactically distinguished in expressions. The operator ~ has the highest precedence, followed by multiplication operators, addition operators, and relations. Operators of the same precedence associate from left to right. For example, x-y-z stands for (x-y)-z.

Expression

=

SimpleExpression [Relation SimpleExpression].

SimpleExpression

=

["+" | "-"] Term {AddOperator Term}.

Term

=

Factor {MulOperator Factor}.

Factor

=

Designator | number | character | string | NIL | Set | "(" Expression ")" | "~" Factor.

Set

=

"{" [Element {"," Element}] "}".

Element

=

Expression [".." Expression].

Relation

=

"=" | "#" | "<" | "<=" | ">" | ">=" | IN | IS.

AddOperator

=

"+" | "-" | OR.

MulOperator

=

"*" | "/" | DIV | MOD | "&".

The available operators are listed in the following tables. Some operators are applicable to operands of various types, denoting different operations. In these cases, the actual operation is identified by the type of the operands. The operands must be expression compatible with respect to the operator (see App. A).

 

8.2.1 Logical operators

OR

logical disjunction

p OR q

"if p then TRUE, else q"

&

logical conjunction

p & q

"if p then q, else FALSE"

~

negation

~ p

"not p"

These operators apply to BOOLEAN operands and yield a BOOLEAN result. The second operand of a disjunction is only evaluated if the result of the first is FALSE. The second oprand of a conjunction is only evaluated if the result of the first is TRUE.

 

8.2.2 Arithmetic operators

+

sum

-

difference

*

product

/

real quotient

DIV

integer quotient

MOD

modulus

The operators +, -, *, and / apply to operands of numeric types. The type of the result is REAL if the operation is a division (/) or one of the operand types is a real type. Otherwise the result type is LONGINT if one of the operand types is LONGINT, or INTEGER in any other case. If the result of a real operation is too large to be represented as a real number, it is changed to the predeclared value INF with the same sign as the original result. Note that this also applies to 1.0/0.0, but not to 0.0/0.0 which has no defined result at all and leads to a run-time error. When used as monadic operators, - denotes sign inversion and + denotes the identity operation. The operators DIV and MOD apply to integer operands only. They are related by the following formulas:

x = (x DIV y) * y + (x MOD y)

0 <= (x MOD y) < y or 0 >= (x MOD y) > y

Note: x DIV y = ENTIER(x / y)

Examples:

x y x DIV y x MOD y

5 3 1 2

-5 3 -2 1

5 -3 -2 -1

-5 -3 1 -2

Note:

(-5) DIV 3 = -2

but

-5 DIV 3 = -(5 DIV 3) = -1

 

8.2.3 Set operators

+

union

-

difference

(x - y = x * (-y))

*

intersection

/

symmetric set difference

(x / y = (x-y) + (y-x))

Set operators apply to operands of type SET and yield a result of type SET. The monadic minus sign denotes the complement of x, i.e. -x denotes the set of integers between 0 and MAX(SET) which are not elements of x. Set operators are not associative ((a+b)-c # a+(b-c)).

A set constructor defines the value of a set by listing its elements between curly brackets. The elements must be integers in the range 0..MAX(SET). A range a..b denotes all integers i with i >= a and i <= b.

 

8.2.4 String operators

+

string concatenation

The concatenation operator applies to operands of string types. The resulting string consists of the characters of the first operand followed by the characters of the second operand. If both operands are of type Shortstring the result is of type Shortstring, otherwise the result is of type String.

 

8.2.5 Relations

=

equal

#

unequal

<

less

<=

less or equal

>

greater

>=

greater or equal

IN

set membership

IS

type test

Relations yield a BOOLEAN result. The relations =, #, <, <=, >, and >= apply to the numeric types, character types, and string types. The relations = and # also apply to BOOLEAN and SET, as well as to pointer and procedure types (including the value NIL). x IN s stands for "x is an element of s". x must be an integer in the range 0..MAX(SET), and s of type SET. v IS T stands for "the dynamic type of v is T (or an extension of T)" and is called a type test. It is applicable if

  1. v is an IN or VAR parameter of record type or v is a pointer to a record type, and if

  2. T is an extension of the static type of v

Examples of expressions (refer to examples in Ch.7):

1991

INTEGER

i DIV 3

INTEGER

~p OR q

BOOLEAN

(i+j) * (i-j)

INTEGER

s - {8, 9, 13}

SET

i + x

REAL

a[i+j] * a[i-j]

REAL

(0<=i) & (i<100)

BOOLEAN

t.key = 0

BOOLEAN

k IN {i..j-1}

BOOLEAN

w[i].name$ <= "John"

BOOLEAN

t IS CenterTree

BOOLEAN

 

9. Statements

Statements denote actions. There are elementary and structured statements. Elementary statements are not composed of any parts that are themselves statements. They are the assignment, the procedure call, the return, and the exit statement. Structured statements are composed of parts that are themselves statements. They are used to express sequencing and conditional, selective, and repetitive execution. A statement may also be empty, in which case it denotes no action. The empty statement is included in order to relax punctuation rules in statement sequences.

Statement

=

[ Assignment | ProcedureCall | IfStatement | CaseStatement | WhileStatement | RepeatStatement | ForStatement | LoopStatement | WithStatement | EXIT | RETURN [Expression] ].

9.1 Assignments

Assignments replace the current value of a variable by a new value specified by an expression. The expression must be assignment compatible with the variable (see App. A). The assignment operator is written as ":=" and pronounced as becomes.

Assignment

=

Designator ":=" Expression.

If an expression e of type Te is assigned to a variable v of type Tv, the following happens:

  1. if Tv and Te are record types, the dynamic and static types of e and v are all equal and all fields of that type are assigned.

  2. if Tv and Te are pointer types, the dynamic type of v becomes the dynamic type of e;

  3. if Tv is an array of character type and e is a string of length m < LEN(v), v[i] becomes ei for i = 0..m-1 and v[m] becomes 0X. It leads to a run-time error if m >= LEN(v).

Examples of assignments (refer to examples in Ch.7):

i := 0

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
5224
Авторов
на СтудИзбе
428
Средний доход
с одного платного файла
Обучение Подробнее