Learn COBOL programming language – Part 2: Data types and syntax “just like human language”

Tram Ho

Previously we had an overview of the COBOL language concept, this time we continue to go through the most basic data types and syntax to build a COBOL program.


1. The data type of COBOL
COBOL actually has only 2 data types: NUMBER and STRING .
The variables in COBOL are created based on these two types, often declared as Elementary Items and Group Items.
You can refer to the example variable declaration below:

In the above example, you can see that the WS-NAME variable is declared as a string of 25 characters, and that WS-CLASS is declared as a two-digit number.
When declared, the value can always be assigned with the keyword VALUE as above: WS-CLASS has the value of ’10’, WS-COUNTRY has the value of ‘INDIA’.
Instead of writing PIC X (n) or PIC 9 (n) with n as the number of characters, you can declare it as follows:

The two ways to declare WS-CLASSA and WS-CLASSB are the same.
When you want to perform a field declaration for both alphanumeric characters (such as Zip Code), we can declare a mix of letters and numbers as follows:


2. The basic syntax in COBOL programming:
Here I will list some basic commands commonly used in COBOL program and examples for your reference.

COMPUTE: command used to calculate the value. For example:

means NUMC is assigned a value by multiplying NUM1 and NUM2.

DIVIDE-BY-GIVING: 2-digit split command. For example:

means that REST-DIV is assigned a value equal to the result of dividing NUMA by NUMB.
The same goes for the MULTIPLY (multiply), SUBTRACT (minus), ADD (plus) statements.

MOVE: command used to assign values.
For example:

means assigning the RES-MOV value equal to the value of NUMA.
The MOVE command can be assigned to multiple variables as follows:

This means assigning the value 25 to both variables WS-NUM1 and WS-NUM3.

DISPLAY: command to print on screen (print the value of a variable or a string)
For example:

IF statement: conditional statement, almost identical to other languages. For example:

The output will look like this:
IN LOOP 1 – IF BLOCK
IN LOOP 2 – IF BLOCK
We can use negative conditions with the keyword IF NOT instead of IF.

EVALUATE command: this is the equivalent of the Switch command in C.
For example:

The result will be: WS-A GREATER THAN 2

Above are some basic syntax of COBOL, next time we will try to apply these commands to write a small program.


Reference links:
https://medium.com/@yvanscher/7-cobol-examples-with-explanations-ae1784b4d576

Share the news now

Source : Viblo