BudiBadu Logo
Samplebadu

COBOL by Example: Data Types

COBOL 2002

Understanding COBOL data type definition using Picture (PIC) clauses instead of traditional type keywords, implementing numeric fields with 9 for digits, alphabetic fields with A for letters, and alphanumeric fields with X for any character, defining fixed-width variables with precise memory control, and using parenthetical notation for field length specification.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. DATATYPES.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  NUM-VAR     PIC 9(3) VALUE 123.
       01  ALPHA-VAR   PIC A(5) VALUE "HELLO".
       01  ALPHANUM    PIC X(5) VALUE "A1B2C".
       
       PROCEDURE DIVISION.
           DISPLAY "Numeric: " NUM-VAR.
           DISPLAY "Alphabetic: " ALPHA-VAR.
           DISPLAY "Alphanumeric: " ALPHANUM.
           STOP RUN.

Explanation

COBOL does not use standard types like int or string found in modern languages. Instead, it uses a Picture (PIC) string to define the exact layout of data in memory. This gives the programmer precise control over the size and format of every variable, which is essential for record-based processing and ensuring data compatibility across different systems.

The three main characters used in PIC strings are: 9 represents a numeric digit (0-9), A represents an alphabetic character (A-Z and space), and X represents an alphanumeric character (any valid character including digits, letters, and special symbols).

The size of the variable is determined by the number of characters in the PIC string. You can repeat the character (e.g., PIC 999) or use parentheses for brevity (e.g., PIC 9(3)). This example shows how COBOL variables are fixed-width; if you store a shorter string in a larger variable, it will be padded with spaces.

Code Breakdown

6
PIC 9(3). This defines a numeric variable capable of holding exactly 3 digits (000 to 999). If you try to store "1234", it will likely be truncated to "234" or cause an error depending on compiler options.
7
PIC A(5). This defines a variable for text only. It can hold 5 letters. It cannot hold numbers or special symbols (except space).
8
PIC X(5). This is the most versatile type. It can hold letters, numbers, and symbols. It is equivalent to a string in other languages but with a fixed length of 5 bytes.
11
DISPLAY "Numeric: " NUM-VAR. This concatenates the literal string "Numeric: " with the value of NUM-VAR and prints it.