Imperative programming languages and tools
Информатика, кибернетика и программирование
Impertive progrmming lnguges nd tools. Progrmming lnguges bsed on the impertive prdigm hve the following chrcteristics: 1 The bsic unit of bstrction is the PROCEDURE whose bsic structure is sequence of sttements tht re executed in succession bstrcting the wy tht the progrm counter is incremented so s to proceed through series of mchine instructions residing in sequentil hrdwre memory cells. Typiclly given vrible my ssume mny different vlues of the course of the execution of progrm just s hrdwre memory cell my contin mny different vlues.1...
Lecture 4. Imperative programming languages and tools. Part 1.
Programming languages based on the imperative paradigm have the following characteristics:
1) The basic unit of abstraction is the PROCEDURE, whose basic structure is a sequence of statements that are executed in succession, abstracting the way that the program counter is incremented so as to proceed through a series of machine instructions residing in sequential hardware memory cells.
2) The sequential flow of execution can be modified by conditional and looping statements (as well as by the very low-level goto statement found in many imperative languages), which abstract the conditional and unconditional branch instructions found in the underlying machine instruction set.
3) Variables play a key role, and serve as abstractions of hardware memory cells. Typically, a given variable may assume many different values of the course of the execution of a program, just as a hardware memory cell may contain many different values. Thus, the assignment statement is a very important and frequently used statement.
Examples of imperative languages: FORTRAN, Algol, COBOL, Pascal, C (and to some extent C++), BASIC, Ada - and many more.
In 1957, the first of the major high level programming languages appeared in the form of FORTRAN. Its name stands for FORmula TRANslating system. The language was invented by John Backus for IBM in 1954, and released commercially in 1957. The language was developed for scientific and engineering applications. The components were very simple, and provided the programmer with low-level access to the computers innards. Fortran began as a digital code interpreter for the IBM 701 and was originally named Speedcoding. John Backus wanted a programming language that was closer in appearance to human language, which is the definition of a high level language.
Today, this language would be considered restrictive as it only included IF, DO, and GOTO statements, but at the time, these commands were a big step forward. The basic types of data in use today got their start in FORTRAN, these included logical variables (TRUE or FALSE), and integer, real, and double-precision numbers. Fortran is still used today for programming scientific and mathematical applications.
Fortran is a general-purpose, imperative programming language that is especially suited to numeric computation and scientific computing. Fortran came to dominate this area of programming early on and has been in continuous use for over half a century in computationally intensive areas such as numerical weather prediction, finite element analysis, computational fluid dynamics, computational physics and computational chemistry.
Fortran encompasses a lineage of versions, each of which evolved to add extensions to the language while usually retaining compatibility with previous versions. Successive versions have added support for structured programming and processing of character-based data (FORTRAN 77), array programming, modular programming and generic programming (Fortran 90), high performance Fortran (Fortran 95), object-oriented programming (Fortran 2003) and concurrent programming (Fortran 2008). The next revision of the language (Fortran 2015) is intended to be a minor revision. It is currently planned to include further interoperability between Fortran and C, additional parallel features, and "the removal of simple deficiencies in and discrepancies between existing facilities.
Programming examples in Fortran.
Here is the simplest Fortran program (Fortran 90):
print *, 'Hello!'
end program hello
Program structure. The program starts with the word program simply because F90 programs must do so. The program must also be given a name, so it is called hello. It must also end with the words end program, hence the last line. The use of the program name in the last line is optional in most F90 dialects, but it is good practice to include it. A program which consisted just of the first and last lines would be a syntactically acceptable program, i.e. it could be compiled and run as described below.
print *, 'Hello!'
What this does is to print on the computer screen the text:
This instruction is formally called a procedure call. It causes something to be done; what it does is predefined by the word print which the language recognizes as meaning print or otherwise display some information.
What is printed is determined by the programmer-supplied text included between the two quote symbols. Any text (except for another single quote!) which appears there will be printed out. A piece of text in quotes is referred to as a text string or character string or sometimes just a string.
Here is a simple program to do a calculation:
real :: x, y ! defines variables
y = sqrt(23.6) ! calculate y
x = 23.6*log(1.0+y)/(3.0+y)
print *, 'The value of x is ', x
print *, 'The value of y is ', y
Any instruction or sequence of instructions will be repeated definitely, say, 10 times, with the do times command. In the following example all the instructions will be repeated counting from 1 to 10. Times is a variable, used as the counter.
integer :: times
do times = 1, 10
print *, 'ZAP!!'
This is an example of condition:
if ( a >=0.0 ) then
print *, 'a is zero or positive'
print *, 'a is negative'
If only a single instruction is to depend on:
if (a /= 0.0 ) x = 1 / a
Subroutine procedure calls. Procedure calls have two main characteristics. Firstly the procedure invoked by the call has a name, e.g. print. Secondly there are usually one or more arguments which specify with what the procedure is to perform whatever it is meant to do. The name of the procedure is fixed, but the programmer chooses the arguments.
Print is a rather special procedure which is built into the language. Another type of procedure is the subroutine procedure or simply a subroutine. These are not built into the language but are available in special libraries or can be defined by the programmer.
call atomic ('K', Kno, Kwt)
end program atom_stuff
subroutine atomic (element, number, value)
end subroutine atomic
Interacting with the program. Whenever the computer encounters an instruction like the following:
read *, x
it does two things.
First it stops and waits for the user to type something on the keyboard. Secondly it interprets whatever has been typed in the context of what kind of variable x has been declared to be, and if it can, assigns whatever has been typed in to x. This should be clear from the following complete program:
real :: x
print *, 'Type in a valid real number:'
read *, x
print *, 'The number you typed was ', x
COBOL was designed in 1959 by the Conference on Data Systems Languages (CODASYL). COBOL stands for COmmon Business Oriented Language. It was created as part of a US Department of Defense effort to create a portable programming language for data processing. Intended as a temporary stopgap, the Department of Defense promptly forced computer manufacturers to provide it, resulting in its widespread adoption. It was standardized in 1968 and has since been revised four times. Expansions include support for structured and object-oriented programming. Thus, COBOL is imperative, procedural and, since 2002, object-oriented.
COBOL is primarily used in business, finance, and administrative systems for companies and governments. In 1997, Gartner Group estimated that there were a total of 200 billion lines of COBOL in existence which ran 80% of all business programs.
Business computing started to take off in 1959. COBOL was designed from the ground up as the language for businessmen, for developing business, typically file-oriented, applications. It is not designed for writing systems programs. Its only data types were numbers and strings of text. It also allowed for these to be grouped into arrays and records, so that data could be tracked and organized better. It is interesting to note that a COBOL program is built in a way similar to an essay, with four or five major sections that build into an elegant whole. COBOL statements also have a very English-like grammar, making it quite easy to learn. All of these features were designed to make it easier for the average business to learn and adopt it.
The language was updated in 1968, 1977, 1985, and 2002. In 1968 COBOL was standardized to overcome incompatibilities between versions. This version was known as American National Standard (ANS) COBOL and was adopted by ISO in 1972. In 1974, ANSI published a revised version of (ANS) COBOL, containing new features such as file organizations, the DELETE statement and the segmentation module. ISO later adopted the updated standard in 1978. In late 1985, ANSI published the revised standard. 60 features were changed or deprecated and many were added, such as:
The standard was adopted by ISO the same year. Two amendments followed in 1989 and 1993, the first introducing intrinsic functions and the other providing corrections. ISO adopted the amendments in 1991 and 1994, respectively, before subsequently taking primary ownership and development of the standard.
In the early 1990s it was decided to add object-orientation in the next full revision of COBOL. Object-orientated features were taken from C++ and Smalltalk. The initial estimate was to have this revision completed by 1997 and an ISO Committee Draft (CD) was available by 1997. Some vendors (including Micro Focus, Fujitsu, and IBM) introduced object-oriented syntax based on drafts of the full revision. The final approved ISO standard was approved and published in late 2002. Fujitsu/GTSoftware, Micro Focus and RainCode introduced object-oriented COBOL compilers targeting the .NET Framework. Three corrigenda were published for the standard: two in 2006 and one in 2009.
COBOL 2014. COBOL 2002 suffered from poor support: no compilers completely supported the standard. Micro Focus found that it was due to a lack of user demand for the new features and due to the abolition of the NIST test suite which had been used to test compiler conformance. The standardization process was also found to be slow and under-resourced. COBOL 2014 includes the following changes:
Criticism and defense.
In the 1970s, programmers began moving away from unstructured “spaghetti code” to the structured programming paradigm. One cause of spaghetti code was the GO TO statement. Attempts to remove GO TOs from COBOL code, however, resulted in convoluted programs and reduced code quality. GO TOs were largely replaced by the PERFORM statement and procedures, which promoted modular programming and gave easy access to powerful looping facilities.
COBOL programs were infamous for being monolithic and lacking modularization. COBOL code could only be modularized through procedures, which were found to be inadequate for large systems. It was impossible to hide data, meaning a procedure could access and modify any data item. Furthermore, there was no way to pass parameters to a procedure. Another complication was the ability to PERFORM a range of procedures. This meant that control could jump to and return from any procedure, creating convoluted control flow and permitting a programmer to break the “single entry, single exit” rule.
This situation improved as COBOL adopted more features. COBOL-74 added subprograms, giving programmers the ability to control the data each part of the program could access. COBOL-85 then added nested subprograms, allowing programmers to hide subprograms. Further control over data and code came in 2002 when object-oriented programming, user-defined functions and user-defined data types were included.
COBOL has an English-like syntax which is used to describe nearly everything in a program. For example, a condition can be expressed as x IS GREATER THAN y or more concisely as x GREATER y or x > y. More complex conditions can be “abbreviated” by removing repeated conditions and variables. For example, a > b AND a > c OR a = d can be shortened to a > b AND c OR = d. As a consequence of this English-like syntax, COBOL has over 300 keywords. However, compiler extensions allow many implementations to have far more. Some of the keywords are simple alternative or pluralized spellings of the same word, which provides for more English-like statements and clauses; e.g., the IN and OF keywords can be used interchangeably, as can IS and ARE, and VALUE and VALUES.
The syntactical elements of a COBOL program are “words”, “literals”, and “punctuation”. Word elements include reserved keywords, user-defined identifiers, and labels, and must be separated from other words by spaces, newlines, or punctuation elements. Identifiers (for data items and files, as well as paragraph and section labels) are case-insensitive and may contain dashes for readability, and can be up to 30 characters long. Literal elements include numeric constants and quoted character (string) constants.
A COBOL program is split into four divisions: the identification division, the environment division, the data division and the procedure division. The identification division specifies the name and type of the source element and is where classes and interfaces are specified. The environment division specifies any program features that depend on the system running it, such as files and character sets. The data division is used to declare variables and parameters. The procedure division contains the program's statements. Each division is sub-divided into sections which are made up of paragraphs.
COBOL can be written in two formats: fixed (the default) or free. In fixed-format, code must be aligned to fit in certain areas. Until COBOL 2002, these were:
Sequence number area
Originally used for card/line numbers, this area is ignored by the compiler
The following characters are allowed here:
This contains: DIVISION, SECTION and procedure headers; 01 and 77 level numbers and file/report descriptors
Any other code not allowed in Area A
Program name area
Historically up to column 80 for punched cards, it is used to identify the program or sequence the card belongs to
In COBOL 2002, Areas A and B were merged and extended to column 255. Also, the program name area was removed. COBOL 2002 also introduced free-format code. Free-format code can be placed in any column of the file, like in newer languages such as C and Pascal. Comments are specified using *> which can be placed anywhere and can also can be used in fixed-format source code. Continuation lines are not present and the >>PAGE directive replaces the / indicator.
At the top of the COBOL hierarchy are the four divisions. These divide the program into distinct structural elements. Although some of the divisions may be omitted, the sequence in which they are specified is fixed, and must follow the order below.
1) Identification division.
The Identification division supplies information about the program to the programmer and the compiler: the name of the program, the programs author, when it was written, when it was compiled, who it is intended for...etc. The compiler treats them as comments. In fact, only the program name is required by the compiler. Every COBOL program must have a PROGRAM-ID because the name specified after this clause is used by the linker when linking a number of subprograms into one run unit, and by the CALL statement when transferring control to a subprogram.
Here's a typical program fragment:
000100 INDENTIFICATION DIVISION.
000110 PROGRAM-ID. Example-1-prog.
000120 AUTHOR. John Smith.
000130 INSTALLATION. ABC GROUP.
000140 DATE-WRITTEN. 17/5/00.
000160 SECURITY. LOCAL GROUP.
2) Environment division.
The Environment division is used to describe the environment in which the program will run. The purpose of the Environment division is to isolate in one place all aspects of the program that are dependent upon a specific computer, device or encoding sequence. The idea behind this is to make it easy to change the program when it has to run on a different computer or one with different peripheral devices.
The Environment division contains the configuration section and the input-output section. The configuration section defines the source and object computer. The input-output section contains file-related information, defines printers, files that may be used and assigns identifier names to these external features.
000260 ENVIRONMENT DIVISION.
000270 CONFIGURATION SECTION.
000280 SOURCE-COMPUTER. IBM PC.
000290 OBJECT-COMPUTER. IBM PC.
000300 INPUT-OUTPUT SECTION.
000320 SELECT INPUT-FILE ASSIGN TO 'input.dat'
000330 ORGANIZATION IS LINE SEQUENTIAL.
000340 SELECT PRINT-FILE ASSIGN TO PRINTER.
3) Data division.
The data division is where memory space in the computer is allocated to data and identifiers that are to be used by the program. Two important sections of this division are the FILE SECTION and the WORKING-STORAGE SECTION. The file section is used to define the structure, size and type of the data that will be read from or written to a file.
Standard COBOL provides the following data types.
May only contain letters or spaces
May contain any characters
PIC 1 USAGE BIT
Data stored in the form of 0s and 1s, as a binary number
Used to reference table elements
Similar to alphanumeric, but using an extended character set, e.g. UTF-8
May contain only numbers
USAGE OBJECT REFERENCE
May reference either an object or be NULL
PICTURE clause. A PICTURE (or PIC) clause is a string of characters, each of which represents a portion of the data item. Some picture characters specify the type of the item and how many characters or digits it occupies in memory. For example, a 9 indicates a decimal digit, and an S indicates that the item is signed. Other picture characters (called insertion and editing characters) specify how an item should be formatted. For example, a series of + characters define character positions as well as how a leading sign character is to be positioned within the final character data; the rightmost non-numeric character will contain the item's sign, while other character positions corresponding to a + to the left of this position will contain a space. Repeated characters can be specified more concisely by specifying a number in parentheses after a picture character; for example, 9(7) is equivalent to 9999999. Picture specifications containing only digit (9) and sign (S) characters define purely numeric data items, while picture specifications containing alphabetic (A) or alphanumeric (X) characters define alphanumeric data items. The presence of other formatting characters define edited numeric or edited alphanumeric data items.
USAGE clause. The USAGE clause declares the format data is stored in. Depending on the data type, it can either complement or be used instead of a PICTURE clause. While it can be used to declare pointers and object references, it is mostly geared towards specifying numeric types. These numeric formats are:
Files. COBOL supports three file formats, or organizations: sequential, indexed and relative. In sequential files, records are contiguous and must be traversed sequentially, similarly to a linked list. Indexed files have one or more indexes which allow records to be randomly accessed and which can be sorted on them. Each record must have a unique key, but alternate record keys need not be unique. Relative files, like indexed files, have a unique record key, but they do not have alternate keys. A relative records key is its ordinal position; for example, the 10th record has a key of 10. This means that creating a record with a key of 5 may require the creation of (empty) preceding records. Relative files also allow for both sequential and random access.
A common non-standard extension is the line sequential organization, used to process text files. Records in a file are terminated by a newline and may be of varying length
Suppose the “input.dat” file contains a series of records about a companys customers, giving details of name, address, and customer number. If you were to open 'input.dat' with a text editor you would see each record on a new line like this:
Joe Bloggs 20Shelly Road Bigtown 023320
John Dow 15Keats Avenue Nowheresville042101
Jock MacDoon05Elliot Drive Midwich 100230
The different pieces of data need to be defined so that the program can read a record at a time, placing each piece of information into the right area of memory (which will be labelled by an identifier).
The file section for this may look like this:
000400 DATA DIVISION.
000410 FILE SECTION.
000430 FD INPUT-FILE.
000440 01 CUSTOMER-DATA.
000450 03 NAME PIC X(12).
000460 03 ADDRESS.
000470 05 HOUSE-NUMBER PIC 99.
000480 05 STREET PIC X(19).
000490 05 CITY PIC X(13).
000500 03 CUST-NUMBER PIC 9(6).
The WORKING-STORAGE SECTION of the data division is for defining data that is to be stored in temporary memory, i.e. during program run-time. Effectively, this is where, for example, an identifier is defined that will hold the result of a calculation.
000500 DATA DIVISION.
000510 WORKING-STORAGE SECTION.
000530 01 RECORD-COUNTER PIC 9(5).
4) Procedure Division.
The Procedure division is where the logic of the program actually found. Here is where the various commands are written. COBOL is a modular language, in that a program is usually broken up into units described as paragraphs.
Procedures. The sections and paragraphs in the procedure division (collectively called procedures) can be used as labels and as simple subroutines. Unlike in other divisions, paragraphs do not need to be in sections. Execution goes down through the procedures of a program until it is terminated. To use procedures as subroutines, the PERFORM verb is used. This transfers control to the specified range of procedures and returns upon reaching the end.
Statements. COBOL (as for COBOL 2014) statements are called verbs, and can be grouped into the following broad categories: control flow, I/O, data manipulation and the report writer.
000900 PROCEDURE DIVISION.
000920 PERFORM READ-DATA-FILE
000930 PERFORM CALULATE-PRICES
000940 PERFORM PRINT-PRICE-REPORT
000950 STOP RUN.
In the above example, the program would consist of four paragraphs: the CONTROL-PARAGRAPH and the three called from within it. All of the paragraph names are user-defined. Even if a program only has one paragraph, it must still have a name. The 'Hello World' program shown below has a paragraph name MAIN-PARAGRAPH. Regarding punctuation, as a rule there should only be two full stops in any paragraph; one after the paragraph name and the other at the end of the paragraph.
The “Hello world” program
000010 IDENTIFICATION DIVISION.
000020 PROGRAM-ID. HELLO-WORLD-PROG.
000030 AUTHOR. TIMOTHY R P BROWN.
000040*The standard Hello world program
000060 ENVIRONMENT DIVISION.
000080 DATA DIVISION.
000090 WORKING-STORAGE SECTION.
000100 01 TEXT-OUT PIC X(12) VALUE 'Hello World!'.
000120 PROCEDURE DIVISION.
000140 DISPLAY TEXT-OUT
000150 STOP RUN.
2 http://cobol.404i.com/index.php and http://www.csis.ul.ie/cobol/course/COBOLIntro.htm
А также другие работы, которые могут Вас заинтересовать
|34341.||Фосфорные минеральные удобрения||24 KB|
|Фосфорные минеральные удобрения Фосф. К фосфорным удобрениям относятся простой и двойной суперфосфат принадлежащие к классу водорастворимых удобрений и комплексные удобрения. Фосфор вносят в почву и с помощью сложного удобрения аммофоса. Фосфорные удобрения получают как физическими так и химическими методами.|
|34342.||Технология производства и экономическая эффективность выпуска и использования пластмасс||30.5 KB|
|Технология производства и экономическая эффективность выпуска и использования пластмасс. Изделия из пластмасс наиболее часто получают методами горячего прессования литья под давлением экструзии выдувания обработки резанием. Прессование применяется главным образом для переработки термореактивных пластмасс. термореактивная смола переводится в плавкое состояние при котором и происходит вторая стадия процесса формование; затем происходит реакция поликонденсации и пластмасса отверждается становясь неплавкой и нерастворимой.|
|34343.||Сырьевые материалы и основы производства резины||28 KB|
|Резину изготавливают с помощью вулканизации. В результате вулканизации каучук превращается в прочную эластичную упругую массу резину. В результате вулканизации молекулы каучука сливаются между собой дисульфидными мостиками в одну трехмерную макромолекулу. Большую роль играют так называемые ускорители вулканизации органические соединения содержащие серу или азот меркаптобензтиазол дифенилгуанидин и др.|
|34344.||Основные свойства и назначения природных и искусственных строительных материалов||21 KB|
|Основные свойства и назначения природных и искусственных строительных материалов. Основные свойства строительных материалов можно разделить на несколько групп. К 1ой группе относятся физические свойства материалов: плотность и пористость. Ко 2й свойства характеризующие устойчивость материала к воздействию воды и низких температур: водопоглощение влажность влагоотдача гигроскопичность водопроницаемость водо морозостойкость.|
|34345.||Классификация и свойства керамических материалов||21.5 KB|
|Классификация и свойства керамических материалов Керамические строительные материалы это искусственные каменные изделия получаемые из глиняных масс с добавками или без добавок других материалов путем формования и последующего обжига. Керамические материалы и изделия классифицируются по различным признакам. В зависимости от структуры керамические материалы разделяют на две основные группы: Плотные спекшиеся имеющие блестящий раковистый излом не пропускающие воду с водопоглощением менее 5 клинкерный кирпич для мощения дорог плитки для...|
|34346.||Технология производства керамического кирпича||23 KB|
|Технология производства керамического кирпича Несмотря на обширный ассортимент разнообразие форм и свойств керамических изделий основные этапы их производства являются общими и включают следующие стадии: Карьерные работы добыча транспортирование и хранение запаса глин подготовку глиняной массы формование изделий сушку отформованных изделий обжиг высушенных изделий обработку изделий глазурование ангобирование и прочее и упаковку. Формование изделий осуществляется преимущественно на прессах: при первом способе подготовке глиняной...|
|34347.||Основные свойства, классификация и назначение стеклянных изделий||22 KB|
|Материалы и изделия из стекла применяемые в строительстве в зависимости от назначения разделяются на следующие группы: Материалы для заполнения проемов зданий и сооружений наиболее обширная группа строительных материалов из стекла включающая листовые стекла различных видов и стеклопакеты; в свою очередь листовое стекло подразделяется на листовое оконное витринное полированное и неполированное армированное узорчатое увиолевое трехслойное закаленное и др.; Материалы для строительных конструкций профильное стекло стеклоблоки;...|
|34348.||Производство листового стекла, труб||24 KB|
|Производство листового стекла труб. Это изделие из стекла в виде плоских листов отношение толщины которых к длине сравнительно невелико и составляет приблизительно 015 15. Стекольной промышленностью вырабатывается широкий ассортимент листового стекла: обычное оконное витринное полированное и неполированное армированное узорчатое увиолевое трехслойное и др. Производство строительного стекла включает следующие основные операции: подготовку сырьевых материалов приготовление стекольной шихты варку стекла формование изделий отжиг...|
|34349.||Технология производства сортового и тарного стекла||21 KB|
|Сфе изделия поступают на отжиг вырабатывают изделия бригадным способом. При механическом сплавах для формирования машины производятся изделия прем.|