You get a bonus - 1 coin for daily activity. Now you have 1 coin

Algorithmic programming language COBOL

Lecture



Kobol (COBOL, COmmon Business Oriented Language) is one of the oldest programming languages ​​(first version in 1959), intended primarily for developing business applications.

Object-oriented programming and other modern language constructs have been added to the latest standard of the 2002 language in Cobol. This year, COBOL and its loyal programmers celebrated their jubilee. 50 years ago, a committee consisting of representatives of the six largest, at that time, computer manufacturers and three government agencies, chose the name COBOL for the new language, from Common Business-Oriented Language.

The language has experienced many of its creators, and even now it is used very widely. Fortunately, or unfortunately, in Russia it is almost unknown, but in the USA, judging by the statistics from Datamonitor, up to 5 million lines of code are still written in Cobol annually. The main scope of application - banking, telephone operators, government agencies.

Story

Algorithmic programming language COBOL

The Kobol project was led by a woman, Grace Hopper (Kobol's grandmother). Practically from its very birth, Kobol is an ANSI-standardized programming language.

Year 1959: The Pentagon meeting gives rise to computer language, which will later become known as “Kobol” (COBOL) and will be the main means of business computing for the next 40 years.

“Kobol”, abbreviated from Common Business-Oriented Language (Common Business-Oriented Programming Language), was one of the first computer languages. And, along with “Fortran”, it was one of the first programming languages ​​based on English vocabulary.

“Kobol” owes its existence to Grace Hopper, one of the first computer programmers. Grace made her first programmer steps in the US Navy reserve, typing machine code for a computer Harvard Mark I during the Second World War. In the late 1950s, she came to the conclusion that computer languages ​​could be made similar to human language, and thus more understandable than the assembler and machine code used then.

Scale of use

Kobol is usually criticized for verbosity and cumbersome, since one of the goals of the creators of the language was to bring the structure as close as possible to the English language. (Until now, Kobol is considered the programming language in which most lines of code were written). So is Dijkstra’s statement “The use of Kobol cripples the mind. His teaching, therefore, should be considered a criminal offense. ”

At the same time, Kobol had excellent tools for working with data structures and files, it became the first language in which the “record” data type appeared. [4] This provided him with a long life in business applications, at least in the USA.

Dr. The Dobb's Journal (with reference to The Gartner Group, Computerworld, Ovum and Micro Focus International) presents the following facts. By 1997, about 240 billion lines of code were actively used on Cobol. About 90% of financial transactions in the world are processed by a code on Cobol, and 75% of commercial data processing is written on Cobol. The total cost of the currently used Kobolov code is estimated at $ 2 trillion. Until now, billions of new lines of code are written on Cobol annually.

Hello world

IDENTIFICATION DIVISION.

PROGRAM-ID. HELLO-WORLD.

*

ENVIRONMENT DIVISION.

*

DATA DIVISION.

*

PROCEDURE DIVISION.

PARA-1.

DISPLAY "Hello, world.".

*

EXIT PROGRAM.

END PROGRAM HELLO-WORLD.

You should learn cobol

Novice programmers (and it is quite possible that their colleagues with experience) must often ask themselves whether they need to learn JAVA, or knowledge of JavaScript, Python or Ruby will be quite enough in the modern world. Given the demand for programmers in the current economy, many find a decent job while still studying at universities, and then why, one wonders, do a representative of this profession look into such a distant past as COBOL?

According to a 2001 Gartner study (in the case of this particular language, this may well be called “recently”), 85% of the global volume of business information was processed in COBOL, and by the current moment the amount of code written in this programming language is starting to increase again. Micro Focus, a company engaged in the development and sale of COBOL modernization tools, claims that 70% of global business still actively uses this tongue.

And although it is obvious that many of the applications originally written in COBOL will be rewritten, Micro Focus is sure that most of the original code will still be in operation, and the applications will be used for many more years. They are safe, stable, and companies using them are not ready to just give up on them. A Micro Focus program manager named Arunn Ramadoss (Arunn Ramadoss) says: “No other language is able to present business data as accurately as COBOL does.”

And even in the days of late retirement, there are fewer and fewer engineers able to work with this language. Someone stops working, others go to positions related to management, not development.

Ramados believes that the world's largest companies and agencies will soon be very interested in young programmers who understand COBOL, as well as new technologies, such as .NET or HTML5, believing that learning this programming language will do good work to all students of programming faculties. , and their graduates, as very soon a sufficient number of interesting vacancies associated with COBOL will appear on the market. Not to mention that this programming language is easy to learn.

In truth, such vacancies are already starting to appear, and most often with the note “urgently needed”.

“The days when you could be“ solely a Java programmer ”or“ only a C programmer ”are gone,” says Arunn: “Today you need to know several languages ​​and technologies, as well as how they can be integrated.”

Integration is perhaps the most important trifle for a person who has decided to take on COBOL. The nature of the language, and the nature of its systems are very tightly tied to the business logic and processes. Therefore, the greatest test for the developer and programmer will not be learning the language itself, but an understanding of how it can be used in a modern corporate environment.

As an example, Ramadoss talks about the business process of transferring funds from one bank account to another - this procedure has not changed at all since its inception. But the way people interact with their bank accounts and transactions has undergone significant, if not drastic, changes. Today, everyone wants to access the account using a PC or mobile phone.

In turn, for companies using the application written in COBOL, the most difficult moment will be the preservation and transfer of accumulated experience and knowledge of existing business processes to new developers. Those programmers who already know this language and understand how it integrates into modern technologies will favorably stand out against the background of their colleagues, despite the fact that, in principle, this is not the most difficult to learn, technology (which means many can relate to it is somewhat frivolous ).

So how do you start a person who is interested in learning this oldest programming language? The best start is cobol.com, where you can find a lot of information on how to approach this technology. As for the literature, the book “The 21st Century COBOL Programmer” by the authors Nancy Stern, Robert A. Stern and James P. Ley is considered to be a recognized benchmark.

Introducing COBOL

With this article I plan to start a whole cycle, which may eventually be collected in a book. Information about COBOL in Russian is presented in fact by an article on Wikipedia and by two Soviet GOSTs. You can ask me why I'm starting to “dig up the corpse” and other similar questions. The answer is simple - just like that . Because I love COBOL, because it is not at all dead, because it is interesting, because it is part of an important story and it will continue to be part of the future. Because COBOL is an event. And let him be scolded by Dijkstra and others, it doesn’t diminish his volumes and his influence on IT in business.

Enough introduction, go to the most studied. COBOL is one of the oldest programming languages, its name as COmmon Business-Oriented Language, which appeared in 1959, is explained by the “grandmother” Grace Hopper, and is mainly used in various financial and administrative systems. You can learn more about its history in the nearest Internet search engine or (well, for absolutely lazy people) - notes.sochi.org.ru/1333/ (Russian language) or en.wikipedia.org/wiki / COBOL (eng.) .

In order to begin the practical study of the language, we need two things - a text editor (1 pc.) And a compiler (1 pc.)

If everything is simple with editors, even Notepad and vi, emacs, nano, etc. will do. etc. The main requirement “classic” is to be a text editor, not a text processor (I don’t remember what else was written in fairly old books on this topic ;-)).

Compilers are a little more complicated, there are commercial ones that cost a lot of money, there are student versions of commercial ones, there are versions of old compilers, there are even a few open source compilers. The choice is left to the reader, I will only provide a list with my comments.

www.opencobol.org/ - OpenCOBOL (open-source, my personal recommendation, multiplatform)

http://tiny-cobol.sourceforge.net/ - TinyCobol (open-source, according to the author, stopped development on January 1, 2011, and was not very active before that)

http://sourceforge.net/projects/cobolforgcc/ - Cobol for GCC (open source, pre-alpha, last updated 2009.)

http://homepages.paradise.net.nz/jsoeberg/ - COBOL 12 (freeware, 16-bit compiler for DOS / Windows)

http://cev.cemotel.cz/cobol/cb_en/mx_all.htm - Cevela MX COBOL (freeware, Windows)

www.microfocus.com/promotions/wwemvctd0510/default.aspx?page=form - Micro Focus Visual COBOL R2 (trial, windows)

www.thekompany.com/products/kobol/ - KOBOL (trial, linux, windows)

There is also a rich selection of ancient DOS compilers.

I personally use OpenCOBOL, which is to some extent the only real option at the moment.

Now that you have installed everything and are ready to rush into battle - let's begin. Naturally, with Hello World.

Type the following code in the editor:

000100 IDENTIFICATION DIVISION.

000200 PROGRAM-ID. HELLOWORLD.

000300 * --- This is an empty line. ---

000400 ENVIRONMENT DIVISION.

000500 DATA DIVISION.

000600 PROCEDURE DIVISION.

000700 BEGIN.

000800 DISPLAY “Hello World!”.

000900 STOP RUN.

Safely save it to a file with a .cob (or .cbl) extension - these are the most popular, historical and logical extensions.

Next, in the terminal or command line, type cobc -x and get the executable file. Run it and ooooop!

Hello World!

Now let's break this code down.

Let's start with the look. This is the “classic” code. With all the requirements that were 50 years ago. Why I use it:

1. Code in this format will suit any compiler.

2. This is “old school”, “Krutatenyushka” and I just like it.

3. It is always better to start with standard requirements, and then look at the capabilities of the compiler and your own taste.

The COBOL program string consists of 80 characters.

Character 1-6: line number (optional)

Symbol 7: “indicator”

* - comment line

- - the line “continuation”,

D line debug.

Symbol 8 - 11: Zone A. DIVISIONS, SECTIONS, names and headings of paragraphs, as well as indicators and numbers of “levels” should begin in it (all this will be discussed later).

Symbol 12-72: Zone B. Actually, the “code” expressions should begin by themselves.

Symbol 73-80: Comment Zone. It is not processed by the compiler and fully provided to the programmer.

With the horizontal plane figured out, let's go to the vertical.

Each COBOL program contains 4 sections - DIVISION, they go in a strict order and contain certain elements.

DIVISION FIRST. Inspiring

IDENTIFICATION DIVISION. - describes the program and contains paragraphs such as

PROGRAM-ID. Helloworld.

AUTHOR. Beginner.

INSTALLATION. MyLocalCobolComputer.

DATE-WRITTEN. 03/19/2011.

DATE-COMPILED. 03/19/2011.

SECURITY. Iwillnottellanybodythiscode.

The content of these paragraphs is an ordinary commentary and, in principle, you can even write “the year 2011 from the birth of Christ” there.

DIVISION SECOND. Mystical.

ENVIRONMENT DIVISION. - Describes the environment, as the name implies, in which the program is written. Consists of two sections.

CONFIG URATION SECTION. Which includes paragraphs SOURCE-COMPUTER. and OBJECT-COMPUTER. and SPECIAL-NAMES. The first two bear a purely commenting function and describe on which computer, for which computer the program is written.

SPECIAL-NAMES. It is a rather deep thing, which will be considered later (or you can search for information on this topic for now).

INPUT-OUTPUT SECTION. Describes, as the name implies, input-output is very necessary, very important and very soon we will meet with it. Includes paragraphs FILE-CONTROL. and IO-CONTROL.

DIVISION THIRD. Legislative.

DATA DIVISION. - Contains descriptions of all variables. Includes 4 sections:

FILE SECTION. - describes the structure of files.

WORKING-STORAGE SECTION. - describes the variables.

LOCAL-STORAGE SECTION. - describes the variables that are created and initialized each time it is executed (in more detail in the following times).

LINKAGE SECTION. - describes the data that we receive when calling other programs.

DIVISION FOURTH. Working.

PROCEDURE DIVISION. - Contains the “very” program, which is divided into user sections, paragraphs, which contain expressions. In our case

BEGIN. - custom paragraph.

DISPLAY “Hello World!”.

STOP RUN. Actually expressions themselves.

And finally. Each expression must end with a period.

Thanks for attention. I am waiting for questions in the comments, which will necessarily be answered and included either in the following or in the editing of this article.

V. Vorontsov, 2011.

2. Meet COBOL

Well, let's continue our acquaintance further, in the first article we learned what the COBOL program consists of, what rules exist for its writing and launched our first program. It's time to move on, this time we will start working with variables and perform the first meaningful actions with them.

So back to our program.

000100 IDENTIFICATION DIVISION.

000200 PROGRAM-ID. HELLOWORLD.

000300 * --- This is an empty line. ---

000400 ENVIRONMENT DIVISION.

000500 DATA DIVISION.

000600 PROCEDURE DIVISION.

000700 BEGIN.

000800 DISPLAY “Hello World!”.

000900 STOP RUN.

Add to DATA DIVISION. new lines, namely the WORKING-STORAGE SECTION section. and a couple of WS-A and WS-B variables.

It will look like this:

000500 DATA DIVISION.

000510 WORKING-STORAGE SECTION.

000520 01 WS-A PIC 999.

000530 01 WS-B PIC 9 (3).

000540 01 WS-RESULT PIC9 (6).

In PROCEDURE DIVISION. accordingly there will be the following lines:

000700 BEGIN.

000800 DISPLAY “Hello I'm your new calculator!”.

000900 DISPLAY “Please Enter first number from 0 to 999”.

001000 ACCEPT WS-A.

001100 DISPLAY “Please Enter second number from 0 to 999”.

001200 ACCEPT WS-B.

001300 DISPLAY “------------------------------------".

001400 DISPLAY ““.

001500 DISPLAY “Your results are:”.

001600 ADD WS-A TO WS-B GIVING WS-RESULT.

001700 DISPLAY “Summ is:”, WS-RESULT.

001800 SUBTRACT WS-A FROM WS-B GIVING WS-RESULT.

001900 DISPLAY “Subtract is:”, WS-RESULT.

002000 MULTIPLY WS-A BY WS-B GIVING WS-RESULT.

002100 DISPLAY “Multiplication is:”, WS-RESULT.

002200 DIVIDE WS-A BY WS-B GIVING WS-RESULT.

002300 DISPLAY “Divide is:”, WS-RESULT.

002400 STOP RUN.

We traditionally save it to a file with the .cob extension and run the compiler. (We did not forget to add the missing parts of the program, right? ;-))

We launch successfully assembled executable file and see, for example:

Hello I'm your new calculator!

Please enter first number from 0 to 999

300

Please enter second number from 0 to 999

100

------------------------------------

Your results are:

Summ is: 000400

Subtract is: 000200

Multiplication is: 030000

Divide is: 000003

300 and 100, I entered, the rest was displayed by the program. The results speak for themselves, and now we will consider new lines of code that we have introduced more closely.

Let's start with new products in DATA DIVISION.

000510 WOR KING-STORAGE SECTION. - informs the compiler about the beginning of the section describing ordinary variables.

000520 01 WS-A PIC 999.

000530 01 WS-B PIC 9 (3).

000540 01 WS-RESULT PIC 9 (6).

From the point of view of the semantic load, these three lines are identical, they define three variables with level 01, followed by the variable name (WS-A, WS-B and WS-RESULT), then comes the PIC operator (which can also be written in its older form like PICTURE IS), which sets the format and size of a variable. And here begins the main surprise for those who are familiar with other languages. The size and format is not indicated by the number of bits to be allocated, but by the number of maximum characters.

In our case, we have described two variables that will contain 3 SIGNIFICANT numbers and one variable that will contain 6 SIGNIFICANT numbers.

More on the description of the format. 9 - tells the compiler that the variable will be numeric, the number of characters indicates the number of digits, it is natural that for large numbers it is inconvenient to write and read something a la 999999999999999 and the record form 9 (15) was made, that is, the number of times is indicated in brackets which repeats the character in front of the brackets.

Let's go to PROCEDURE DIVISION

DISPLAY - as you can understand from the program and its output deals with one of the most useful functions in the world. Displays the specified variable or text on the screen. Custom text must be enclosed in double quotes “”. You can display several variables or texts, as seen in the case of

001700 DISPLAY “Summ is:”, WS-RESULT.

The main thing is not to forget the comma between them.

Also in the program were noted 4 mathematical functions:

Addition ADD WS-A to WS-B GIVING WS-RESULT.

Subtraction SUBTRACT WS-A FROM WS-B GIVING WS-RESULT.

Multiplication MULTIPLY WS-A BY WS-B GIVING WS-RESULT.

Division DIVIDE WS-B BY WS-A GIVING WS-RESULT.

They are built on the same principle.

value1 TO / FROM / BY value2 GIVING variable.

Values ​​can be either variables or numbers directly, for example,

ADD 10 TO 20 GIVING WS-RESULT.

Add 10 to 20 and record the result (30) in the WS-RESULT.

If GIVING and the subsequent variable name are omitted, the result will be written into the variable going AFTER TO, FROM, BY - in our case it will be WS-B (but WS-A in the case of DIVIDE).

A small but important note, there are some other forms of recording, for example:

ADD 1 2 3 TO WS-B – соответственно вначале сложит 1+2+3, а потом приплюсует это к значению WS-B и запишет результат в WS-B.

Можно опустить и TO – ADD 1 WS-A 2 WS-B сложит все эти значения и запишет результат в WS-B. Несколько переменных можно указать и после TO (к каждой из переменных после TO будут прибавлены значения до TO и результат записан в соответствующую переменную) и после GIVING, тогда в каждую из них будет записан результат. Аналогично можно оперировать и с SUBTRAC T.

НО в случае с MULTIPLY и DIVIDE указание нескольких переменных возможно только после GIVING (и то это нужно уточнять для каждого компилятора отдельно).

Помимо этого у DIVIDE есть и вторая форма записи.

DIVIDE WS-A INTO WS-B GIVING WS-C со сменой BY на INTO меняется и порядок переменных, какую именно форму использовать остается выбор за пользователем. Укажу лишь, что:

DIVIDE WS-A INTO WS-B это WS-B / WS-A = WS-B

DIVIDE WS-B BY WS-A GIVING WS-RESULT

это WS-B / WS-A = WS-RESULT

ЭТО ВАЖНО! Вариант с BY НЕ БУДЕТ работать без GIVING. Программа просто не скомпилируется из-за ошибки.

Ну и напоследок маленький “подарок” — наверняка читатель уже задался вопросом “а как же присвоить значение переменной?”. С помощью MOVE

MOVE 10 TO WS-A

или MOVE WS-A TO WS-B

или даже MOVE 10 TO WS-A WS-B

ЭТО ВАЖНО! MOVE принимает несколько переменных только на “выходе”, т.е. после TO.

В. Воронцов, 2011.

3. Знакомимся с COBOL

В предышущей лекции мы не указали несколько важных ключевых слов для DIVIDE.

DIVIDE WS-B BY WS-A GIVING WS-RESULT REMAINDER <переменная>.

Используя REMAINDER мы указываем переменную в которую запишется ОСТАТОК от деления.

Для любых математических операций:

Также, добавляя ROUNDED после операции мы достигаем того, что результат будет округляться, а не просто “отбрасываться” лишний хвост.

ADD WS-A TO WS-B GIVING WS-RESULT ROUNDED.

А теперь продолжим познавать новое. Исполняя обещание развеять удивление о странном выводе значений переменных мы разберем в этот раз PICTURE IS (он же PIC) и форматы переменных.

И снова мы возвращаемся в DATA DIVISION.

Рассмотрим еще разок строчку с описанием переменной:

01 – уровень переменной;

WS-B – имя переменной;

PIC – ключевое слово, указывающее, что далее идет описание формата переменной, старой формой является PICTURE IS.

9(3) – тип символов в переменной “9” и их количество “3”.

УРОВЕНЬ ПЕРЕМЕННОЙ.

Пользователю для обычных переменных доступны уровни с 01 по 49 включительно и 77. Уровень переменной описывает ее иерархию в группе переменных, чем выше номер, тем ниже переменная в “лестнице”. Например

01 CUSTOMER-RECORD.

05 CUSTOMER-NAME PIC X(10).

05 CUSTOMER-ADDRESS PIC X(30).

Уровень 77 объявляет переменную, как ЭЛЕМЕНТАРНУЮ, то есть у нее не может быть под-переменных.

Уровень 88 объявляет переменную, как conditional, причем в достаточно изощренной и богатой функционально форме, о них подробнее в следующий раз.

Есть и некоторые другие уровни, которые введены либо производителями компиляторов, либо сейчас нам не нужны.

ИМЯ ПЕРЕМЕННОЙ.

Имя переменной может состоять из цифр, букв и “-”, но не должно с “-” начинаться.

Имя переменной должно содержать не больше 30 символов.

ОПИСАНИЕ ФОРМАТА ПЕРЕМЕННОЙ.

Рассмотрим какие описательные символы существуют для переменных в COBOL.

Они делятся на две группы: “обычные” и “редактирующие”.

В обычные входят

9 – одна цифра;

V – знак, отделяющий целую часть от десятичной (может применяться только ОДИН раз в каждой переменной).

S – знак “±”, должен быть самым первым символом в формате переменной (может применяться только ОДИН раз в каждой переменной).

X – один буквенно-цифровой знак, т.е. цифра, буква, пробел, спец. символы.

A – один буквенный знак или пробел.

Редактирующие символы – благодаря им описываются переменные, которые не будут участвовать в расчетах, но позволяют тонко настроить вид, в котором переменная будет выведена на экран/печать:

Z – заменяет 9'ки с той разницей, что все начальные нули убираются.

$ — “валютный знак”, указанный для компилятора, по умолчанию, в основном знак доллара, используется ТОЛЬКО как ПЕРВЫЙ символ в описании. Может использоваться только один раз. Его значение устанавливается в ENVIRONMENT DIVISION. с помощью

* — аналог Z, но начальные нули заменяются на *.

— (минус) – может указываться как первым, так и самым последним символом, но только один раз. Если число отрицательное, то будет выведен минус, иначе пустое место.

+ (плюс) – аналог “-” (минуса), НО в случае с положительным числом будет выведен “+”, а в случае с отрицательным выводится “-”.

. (точка) – знак “десятичной точки”. На ее месте будет выведена именно “точка”.

, (запятая) – знак “запятой”. Может быть несколько в переменной.

/ (слэш) – знак “слэш”. Может быть несколько. Выводит “слэш”, популярен в датах.

0 (ноль) — “ноль”. Просто на этом месте будет выведен 0.

B (от blank, пустой) — “пробел”.

Но главное, как вы можете понять все эти символы комбинируются и позволяют получать очень гибкие формы и виды. Правило здесь фактически только одно – числовые переменные не должны превышать 18 символов, буквенно-цифровые – 160 символов. Но тут опять же многое зависит от компилятора и его параметров.

ВКУСНЫЕ ДОПОЛНЕНИЯ или ЕСТЬ ЖИЗНЬ ПОСЛЕ PIC'а!

Помимо этого, при описании переменной после ее формата могут быть добавлены дополнительные “опции”:

BLANK WHEN ZERO – если переменная равно 0, то вместо нее будет выведено пустое место, а не нули.

VALUE “значение” — сразу присваивает переменной определенное значение.

Существуют и другие, но упоминать о них сейчас было бы бесполезно.

Итак, теперь давайте просто пощупаем все их в разных видах.

000100 IDENTIFICATION DIVISION.

000200 PROGRAM-ID. VARIABLES-TEST.

000300 AUTHOR. ME

000400 ENVIRONMENT DIVISION.

000500 DATA DIVISION.

000600 WORKING-STORAGE SECTION.

000700 01 HUMAN-CONTAINER.

000800 05 HUMAN-NAME PIC A (30).

000900 05 HUMAN-ADDRESS PIC X (160).

001000 77 SQUARE-METERS PIC 9 (18).

001100 77 SQUARE-PRICE PIC 9 (15) V9 (2).

001150 77 FLAT-PRICE PIC 9 (15) V9 (2).

001200 77 TAX-PERCENT PIC 9 (2).

001300 77 TAX-SUMM PIC 9 (15) V9 (2).

001350 77 NEGATIVE-VALUE PIC S9 (10) V9 (6).

001400 * --- OOOOMG! ---

001500 77 SQUARE-METERS-OUT PIC Z (17) 9.

001600 77 SQUARE-PRICE-OUT PIC Z (14) 9.Z (2).

001650 77 FLAT-PRICE-OUT-1 PIC Z (3), Z (3), Z (3), Z (3) .9 (2).

001660 77 FLAT-PRICE-OUT-2 PIC Z (3) BZ (3) BZ (3) BZ (3) .9 (2).

001700 77 TAX-PERCENT-OUT PIC Z (2).

001800 77 TAX-SUMM-OUT PIC Z (14) 9.9 (2).

001900 77 NEGATIVE-VALUE-OUT-1 PIC + Z (10) .9 (6).

002000 77 NEGATIVE-VALUE-OUT-2 PIC -Z (10). * (6).

002100 * --------------------------------

002200 PROCEDURE DIVISION.

002300 BEGIN.

002400 DISPLAY "Please enter Name:".

002500 ACCEPT HUMAN-NAME.

002550 DISPLAY "Please enter Address:".

002600 ACCEPT HUMAN-ADDRESS.

002700 DISPLAY "Please enter square meters of flat:".

002800 ACCEPT SQUARE-METERS.

002900 DISPLAY "Please enter square meter's price:".

003000 ACCEPT SQUARE-PRICE.

003100 DISPLAY "Please enter percent of tax:".

003200 ACCEPT TAX-PERCENT.

003300 DISPLAY "Enter any really big NEGATIVE value:".

003400 ACCEPT NEGATIVE-VALUE.

003500 DISPLAY "---------------------------------------".

003600 DISPLAY "".

003700 DISPLAY HUMAN-NAME.

003800 DISPLAY HUMAN-ADDRESS.

003900 DISPLAY "SQUARE-METERS:", SQUARE-METERS.

004000 MOVE SQUARE-METERS TO SQUARE-METERS-OUT.

004100 DISPLAY "SQUARE-METERS-OUT:", SQUARE-METERS-OUT.

004200 DISPLAY "SQUARE-PRICE:", SQUARE-PRICE.

004300 MOVE SQUARE-PRICE TO SQUARE-PRICE-OUT.

004400 DISPLAY "SQUARE-PRICE-OUT:", SQUARE-PRICE-OUT.

004500 MULTIPLY SQUARE-METERS BY SQUARE-PRICE GIVING FLAT-PRICE.

004600 DISPLAY "FLAT-PRICE:", FLAT-PRICE.

004700 MOVE FLAT-PRICE TO FLAT-PRICE-OUT-1 FLAT-PRICE-OUT-2.

004800 DISPLAY "FLAT-PRICE-OUT-1:", FLAT-PRICE-OUT-1.

004850 DISPLAY "FLAT-PRICE-OUT-2:", FLAT-PRICE-OUT-2.

004900 DISPLAY "TAX-PERCENT:", TAX-PERCENT.

005000 MOVE TAX-PERCENT TO TAX-PERCENT-OUT.

005100 DISPLAY "TAX-PERCENT-OUT:", TAX-PERCENT-OUT.

005200 DISPLAY "TAX-SUMM:", TAX-SUMM.

005300 MOVE TAX-SUMM TO TAX-SUMM-OUT.

005400 DISPLAY "TAX-SUMM-OUT:", TAX-SUMM-OUT.

005500 DISPLAY "NEGATIVE-VALUE:", NEGATIVE-VALUE.

005600 MOVE NEGATIVE-VALUE TO NEGATIVE-VALUE-OUT-1 NEGATIVE-VALUE-OUT-2.

005700 DISPLAY "NEGATIVE-VALUE-OUT-1:", NEGATIVE-VALUE-OUT-1.

005800 DISPLAY "NEGATIVE-VALUE-OUT-2:", NEGATIVE-VALUE-OUT-2.

005900 STOP RUN.

And what we get in the end.

Please enter Name:

Slava

Please enter Address:

Moscow 15

Please enter square meters of flat:

44

Please enter square meter's price:

1234123

Please enter percent of tax:

20

Enter any really big NEGATIVE value:

-123123213213

---------------------------------------

Slava

Moscow 15

SQUARE-METERS: 000000000000000044

SQUARE-METERS-OUT: 44

SQUARE-PRICE: 000000001234123.00

SQUARE-PRICE-OUT: 1234123.00

FLAT-PRICE: 000000054301412.00

FLAT-PRICE-OUT-1: 54,301,412.00

FLAT-PRICE-OUT-2: 54 301 412.00

TAX-PERCENT: 20

TAX-PERCENT-OUT: 20

TAX-SUMM: 000000000000000.00

TAX-SUMM-OUT: 0.00

NEGATIVE-VALUE: -3123213213.000000

NEGATIVE-VALUE-OUT-1: -3123213213.000000

NEGATIVE-VALUE-OUT-2: -3123213213.000000

As you can see, the output of “formatted” and raw variables is different and customizable.

Naturally, this is not just your right, but the obligation to play around with variables, to see how they will behave.

And by the way, if you carefully watched the output of your program, you might have noticed a very unpleasant “trifle” - values ​​that did not fit into the variable, if you didn’t, try experimenting.

V. Vorontsov, 2011.

4. COBOL - IF and his friends

This time we will get acquainted with the goodies of the conditions (and also get an additional small gift for knowledge at the end).

So, I think everyone who is at least a little interested in programming will remember that there is probably almost all YP in such a statement - such as IF (If), there is of course in COBOL as well.

How is it recorded?

IF

(optional ELSE)

END-IF.

ATTENTION. It is important:

Each expression in COBOL ends with a “.” (Dot), you already know this, BUT IF is considered as one expression, so the dot here is put ONLY after END-IF.

Be careful!

Possible conditions:

1. Check for the data type in the variable:

numeric (IS NUMERIC) - verifies that the variable contains a number.

Letter (IS ALPHABETIC) - it is checked that the variable contains ONLY letters and spaces.

Alphabetic (capital letters) and alphabetic (capital letters) (IS ALPHABETIC-UPPER and ALPHABETIC-LOWER) - it is checked respectively that only capital or capital letters and spaces are contained.

It was used and is used to check the accuracy of the entered data and the corresponding processing of the detected errors.

For example,

IF WS-A IS NUMERIC

MOVE WS-A TO WS-B

ELSE

DISPLAY “Error!”

END-IF.

2. Comparison:

Operator (full form of record), Short form of record, Meaning

IS GREATER THAN IS> More than

IS NOT GREATER THAN IS NOT> No more than

IS LESS THAN IS

IS NOT LESS THAN IS NOT

IS EQUAL TO IS = Equals

IS NOT EQUAL TO IS NOT = Not equal

IS GREATER THAN OR EQUAL TO IS> = Greater than or equal to

IS LESS THAN OR EQUAL TO IS <= Less than or equal to

And if with the comparison of numbers everything is clear, then the comparison of letter variables should be clarified. COBOL adjusts the compared values ​​to the same size with spaces added to the right end. After that, a character-by-character comparison starts from the leftmost character in accordance with ASCII, EBCDIC (on mainframe) or another encoding specified by the compiler.

IF TEXT-INPUT IS> “Orange”

DISPLAY “Orange”

DISPLAY TEXT-INPUT

ELSE

DISPLAY TEXT-INPUT

DISPLAY “Orange”

END-IF.

If you enter Apple, it will be “less” than Orange, but apple will be “more”.

3. Check on the sign of the number:

IS POSITIVE - the number is positive;

IS NEGATIVE - the number is negative;

IS ZERO - the number is zero;

IS NOT POSITIVE - the number is NOT positive (0 or negative);

IS NOT NEGATIVE - the number is NOT negative (0 or positive);

IS NOT ZERO - the number is NOT zero.

For example:

MOVE 100 TO WS-RESULT.

DISPLAY “WS-RESULT IS”, WS-RESULT.

IF WS-RESULT IS NOT ZERO

DISPLAY “WS-RESULT IS NOT ZERO!”

END-IF.

IF WS-RESULT IS ZERO

DISPLAY “WS-RESULT IS ZERO!”

END-IF.

IF WS-RESULT IS NOT POSITIVE

DISPLAY “WS-RESULT IS NOT POSITIVE!”

END-IF.

IF WS-RESULT IS NOT NEGATIVE

DISPLAY “WS-RESULT IS NOT NEGATIVE!”

END-IF.

IF WS-RESULT IS POSITIVE

DISPLAY “WS-RESULT IS POSITIVE!”

END-IF.

IF WS-RESULT IS NEGATIVE

DISPLAY “WS-RESULT IS NOT ZERO!”

END-IF.

The output in this case will look like:

WS-RESULT IS 000100

WS-RESULT IS NOT ZERO!

WS-RESULT IS NOT NEGATIVE!

WS-RESULT IS POSITIVE!

4. Using a variable with conditions:

In a previous lesson, we mentioned the level of variable 88. Now it's time to take a closer look at it. A variable of this type has no description, it is initialized immediately upon declaration and can only be a sub-level of another variable. It is used as an analogue of CASE from other programming languages ​​and stores the value with which the IF will be checked. For example:

We describe and initialize in DATA DIVISION.

01 NUMBER-CHECK PIC S9.

88 NC-ONE VALUE 1.

88 NC-ZERO VALUE 0.

88 NC-MINUS VALUE -1.

We use in PROCEDURE DIVISION.

ACCEPT NUMBER-CHECK.

IF NC-ONE

DISPLAY “NUMBER-CHECK IS ONE”

END-IF.

IF NC-MINUS

DISPLAY “NUMBER-CHECK IS MINUS”

END-IF.

IF NC-ZERO

DISPLAY “NUMBER-CHECK IS ZERO”

END-IF.

How it works:

NC-ONE, NC-MINUS and NC-ZERO are variables assigned to NUMBER-CHECK, when we use IF NC-ONE, the actual compiler “substitutes”

IF NUMBER-CHECK = 1.

In addition to VALUE, VALUES THRU can be used; in this case, at 88 NC-ONE VALUES 1 THRU 10, the value stored in NUMBER-CHECK in the range from 1 to 10 will be checked.

In addition to the above, IF supports NOT, AND, and OR, for example, IF NOT WS-A = WS-B or IF ((WS-A = WS-B) AND (WS-A = WS-RESULT)) OR (WS-RESULT = WS-B).

created: 2014-09-30
updated: 2021-10-06
132611



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Programming Languages and Methods / Translation Theory

Terms: Programming Languages and Methods / Translation Theory