Hello World in Cobol: Complete Solution & Deep Dive Guide

Code Debug

The Ultimate Guide to Your First Cobol Program: Mastering "Hello, World!"

To write "Hello, World!" in Cobol, you must define the program's metadata in the IDENTIFICATION DIVISION and write the execution logic in the PROCEDURE DIVISION. The core of the program uses the DISPLAY "Hello, World!" statement to print the text, followed by STOP RUN to terminate execution.

Ever felt like you've stumbled upon a digital dinosaur? That's a common reaction when developers first encounter Cobol. In a world dominated by Python, JavaScript, and Rust, the rigid, verbose structure of Cobol can feel like a relic from a bygone era. You might be wondering, "Is this even worth learning? Is it just a programming history lesson?" This initial intimidation is a hurdle many face, but it's one built on misconceptions.

The truth is, Cobol is the silent giant of the programming world. It powers the global financial system, runs on mainframes processing billions of transactions daily, and offers a stable, high-demand career path that few are exploring. This guide is your first step into that world. We will demystify Cobol's structure, guide you through writing your very first program—the timeless "Hello, World!"—and show you that behind its vintage facade lies a powerful and logical language. By the end of this article, you won't just have code; you'll have a new perspective.


What Is the "Hello, World!" Program in Cobol?

The "Hello, World!" program is a fundamental rite of passage for anyone learning a new programming language. Its purpose is elegantly simple: to make the computer display the phrase "Hello, World!" on the screen. While trivial in function, its true value lies in serving as a first-contact point with a language's syntax, structure, and compilation process.

In the context of Cobol (COmmon Business-Oriented Language), this simple task immediately introduces you to the language's most defining characteristic: its rigid, hierarchical structure. Unlike more modern languages where you might write a single line of code to achieve this, Cobol requires a formal program structure, complete with named sections called DIVISIONS. This verbosity is not a flaw; it's a feature designed for clarity, readability, and long-term maintainability in critical business applications.

Executing this first program successfully confirms that your development environment, specifically your Cobol compiler like GnuCOBOL (cobc), is set up correctly. It's the foundational "smoke test" that proves you're ready to tackle more complex logic. This initial module from the kodikra learning path is designed to build that essential foundation.


Why Is Understanding Cobol's Structure So Important?

Learning Cobol is less about memorizing commands and more about understanding its philosophy. The language was designed in 1959 with a clear goal: to be as readable as plain English. This was crucial for business environments where program logic needed to be understood by managers and analysts, not just hardcore programmers. This design principle led to the creation of the four mandatory DIVISIONS, which act as a blueprint for every Cobol program.

The Four Divisions of a Cobol Program

Every Cobol program is structured like a formal document, divided into four distinct parts. While our "Hello, World!" example will only actively use two, understanding all four is critical for your journey.

  • IDENTIFICATION DIVISION: This is the metadata section. It contains information about the program itself, such as its name (PROGRAM-ID), the author (AUTHOR), the date it was written, and other documentary details. It's the title page of your code.
  • ENVIRONMENT DIVISION: This division describes the environment in which the program will run. It handles connections between the program and external resources, like files on the operating system (FILE-CONTROL) and the specific computer it will run on (CONFIGURATION SECTION). It's the bridge between your code and the outside world.
  • DATA DIVISION: Here is where you declare all the variables, constants, and data structures your program will use. Cobol is statically typed and requires explicit data definitions, including their type (numeric, alphanumeric) and size. This section is the program's memory map. For our simple "Hello, World!", we can bypass this by using a literal string directly.
  • PROCEDURE DIVISION: This is the heart of the program. It contains the executable statements, the logic, and the step-by-step instructions that the computer will follow. The commands here, written in paragraphs and sentences, are what actually perform the work, like displaying text or performing calculations.

This structured approach forces a discipline that is often missing in modern scripting languages. It makes Cobol programs exceptionally self-documenting and easier to maintain over decades, which is precisely why they are still running in legacy systems today.

    ● Program Start
    │
    ▼
  ┌───────────────────────────┐
  │ IDENTIFICATION DIVISION   │
  │ (Metadata: Program Name)  │
  └────────────┬──────────────┘
               │
               ▼
  ┌───────────────────────────┐
  │ ENVIRONMENT DIVISION      │
  │ (Optional: File/Hardware) │
  └────────────┬──────────────┘
               │
               ▼
  ┌───────────────────────────┐
  │ DATA DIVISION             │
  │ (Optional: Variables)     │
  └────────────┬──────────────┘
               │
               ▼
  ┌───────────────────────────┐
  │ PROCEDURE DIVISION        │
  │ (Execution Logic)         │
  └────────────┬──────────────┘
               │
               ├─ 1. DISPLAY "Hello, World!"
               │
               └─ 2. STOP RUN
               │
               ▼
    ● Program End

How to Write and Run Your First Cobol Program

Now, let's translate theory into practice. We will write the code, compile it using the open-source GnuCOBOL compiler, and see our message appear on the screen. This process is the core skill you'll build upon throughout your Cobol journey.

The Complete "Hello, World!" Code

Create a file named hello-world.cob and enter the following code. We are using a modern, "free-format" syntax, which removes the archaic column restrictions of traditional Cobol, making it much easier to write.


*> =================================================================
*> Program:   Hello World
*> Author:    kodikra.com
*> Purpose:   A program to display "Hello, World!" to the console.
*>            This is the first module in the kodikra Cobol learning path.
*> =================================================================

       IDENTIFICATION DIVISION.
      ******************************************************************
      * This is the first and only mandatory division. It provides
      * metadata about the program.
      ******************************************************************
       PROGRAM-ID. HelloWorld.
       AUTHOR. Your Name.
       INSTALLATION. kodikra.com Learning Platform.
       DATE-WRITTEN. 2024-10-27.
       DATE-COMPILED.

       PROCEDURE DIVISION.
      ******************************************************************
      * This division contains the executable code. It's where the
      * program's logic resides.
      ******************************************************************
       DISPLAY "Hello, World!".
      * The DISPLAY verb is Cobol's primary way to output data to
      * the standard output (usually the terminal screen).

       STOP RUN.
      * The STOP RUN statement is crucial. It tells the operating
      * system that the program has finished its execution and can
      * be terminated.

Step-by-Step Code Walkthrough

Let's dissect this code line by line to understand every component.

  1. *> ...
    Lines starting with *> are modern, free-format comments. They are ignored by the compiler and are used to document the code for human readers. The traditional fixed-format comment uses an asterisk * in column 7.
  2. IDENTIFICATION DIVISION.
    This line marks the beginning of the metadata section. It's a required header for every Cobol program. The period at the end is crucial; in Cobol, periods act like semicolons or statement terminators in other languages.
  3. PROGRAM-ID. HelloWorld.
    This is the only mandatory line within the IDENTIFICATION DIVISION. It gives our program a name, HelloWorld. This name is used by the operating system and other programs to identify it.
  4. AUTHOR. Your Name.
    This and the following lines (INSTALLATION, DATE-WRITTEN) are optional but highly recommended for good documentation. They provide context about who wrote the code, where it's from, and when it was created.
  5. PROCEDURE DIVISION.
    This line marks the beginning of the executable logic. All the actions our program will take are defined within this division.
  6. DISPLAY "Hello, World!".
    This is the core instruction. The DISPLAY verb is Cobol's command for printing data. The string literal "Hello, World!" is the content we want to show. The entire line is a "sentence" in Cobol terminology, ending with a period.
  7. STOP RUN.
    This is the final command. STOP RUN terminates the program and returns control to the operating system. Forgetting this can lead to unpredictable behavior, as the program might continue trying to execute whatever is next in memory.

Compiling and Running the Program

To bring our code to life, we need a compiler. GnuCOBOL is the standard, free, and open-source compiler for modern systems. If you have it installed (e.g., on Linux, macOS via Homebrew, or Windows via WSL), you can compile and run the program from your terminal.

Here is the standard workflow illustrated:

  ┌───────────────────┐
  │ hello-world.cob   │
  │ (Source Code)     │
  └─────────┬─────────┘
            │
            ▼
  ┌───────────────────┐
  │ cobc Compiler     │◀─ Flags: -x -free
  │ (GnuCOBOL)        │
  └─────────┬─────────┘
            │
            ▼
  ┌───────────────────┐
  │ hello-world       │
  │ (Executable File) │
  └─────────┬─────────┘
            │
            ▼
  ┌───────────────────┐
  │ Terminal          │
  │ (./hello-world)   │
  └─────────┬─────────┘
            │
            ▼
    ● Output: "Hello, World!"

Follow these steps in your command line interface:

1. Compile the Code:

Open your terminal, navigate to the directory where you saved hello-world.cob, and run the following command:


cobc -x -free hello-world.cob
  • cobc: This invokes the GnuCOBOL compiler.
  • -x: This flag tells the compiler to create a standalone executable file.
  • -free: This specifies that we are using free-format source code, not the old fixed-format with its strict column rules.
  • hello-world.cob: This is our input source file.

If the command runs without any errors, you will see a new file in your directory named hello-world (or hello-world.exe on Windows).

2. Run the Executable:

Now, execute the compiled program:


./hello-world

3. See the Output:

The terminal will immediately display the result of your program's hard work:


Hello, World!

Congratulations! You have successfully written, compiled, and executed your first Cobol program. You've taken the first and most important step on the path to mastering this powerful language, a cornerstone of the complete kodikra Cobol curriculum.


Alternative Approach: Using the DATA DIVISION

While our first example was the most direct, a more common practice in larger Cobol programs is to declare data in the DATA DIVISION before using it. This promotes better organization and reusability. Let's refactor our "Hello, World!" to use a variable.

This approach introduces the WORKING-STORAGE SECTION, which is part of the DATA DIVISION and is used for declaring temporary variables that exist only for the duration of the program's execution.

Code with a Variable


       IDENTIFICATION DIVISION.
       PROGRAM-ID. HelloWorldWithVariable.
       AUTHOR. kodikra.com.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 GREETING-MESSAGE      PIC X(13) VALUE "Hello, World!".

       PROCEDURE DIVISION.
       DISPLAY GREETING-MESSAGE.
       STOP RUN.

Explanation of Changes

  • DATA DIVISION.: We've now included the third division to define our data.
  • WORKING-STORAGE SECTION.: This is a standard section within the DATA DIVISION for declaring variables.
  • 01 GREETING-MESSAGE: This declares a data item. 01 is a "level number," indicating a top-level record or standalone variable. GREETING-MESSAGE is our chosen variable name.
  • PIC X(13): This is the "PICTURE clause," a core concept in Cobol.
    • PIC is short for PICTURE.
    • X signifies that the variable is alphanumeric (it can hold letters, numbers, and symbols).
    • (13) specifies that the variable will hold exactly 13 characters.
  • VALUE "Hello, World!".: This initializes the variable with our desired string.
  • DISPLAY GREETING-MESSAGE.: In the PROCEDURE DIVISION, we now DISPLAY the variable instead of the hardcoded string literal.

This version is slightly longer but is considered better practice. It separates data from logic, making the program easier to modify. For instance, if you needed to display the message in multiple places, you would only need to change the VALUE in one location.


Pros and Cons of Cobol's Verbosity

Cobol's structure, often perceived as overly wordy, is a double-edged sword. It's essential to understand its advantages and disadvantages, especially when coming from more concise languages.

Pros (Advantages) Cons (Disadvantages)
Extreme Readability: The English-like syntax and rigid structure make Cobol code self-documenting. A non-programmer can often get the gist of what a program is doing. Steep Initial Learning Curve: The boilerplate of divisions and sections can be intimidating for beginners who are used to a simple print() function.
High Maintainability: Code written 40 years ago can be understood and modified today because the structure enforces clarity. This is vital for long-living enterprise systems. Code Volume: Simple tasks require significantly more lines of code compared to languages like Python or Ruby, which can slow down initial development.
Forced Discipline: The requirement to pre-define all data in the DATA DIVISION forces developers to think about their data structures upfront, reducing runtime errors. Perceived as "Outdated": The verbose style can feel archaic and less "elegant" to developers accustomed to modern functional or object-oriented paradigms.
Clear Separation of Concerns: The division structure naturally separates metadata, environment configuration, data definitions, and logic, leading to well-organized programs. Less Flexibility for Quick Scripts: Cobol is poorly suited for small, one-off scripts or rapid prototyping where conciseness is key. It's designed for large, robust applications.

Frequently Asked Questions (FAQ)

Is Cobol still relevant today?

Absolutely. While it's not used for web or mobile app development, Cobol is the backbone of the global financial industry. It runs on mainframe systems in banks, insurance companies, government agencies, and airlines, processing trillions of dollars in transactions daily. The demand for Cobol programmers to maintain and modernize these critical systems is high and growing.

Why does Cobol code look so different from other languages?

Cobol was designed in 1959 with a primary goal of being readable by non-technical business managers. Its syntax mimics natural English (e.g., ADD A TO B GIVING C, PERFORM, DISPLAY). This design philosophy, along with the rigid four-division structure, makes it verbose but also highly explicit and self-documenting, which was a critical feature for long-term business applications.

What is the difference between fixed-format and free-format Cobol?

Traditional Cobol used a "fixed-format" layout tied to 80-column punch cards. Certain parts of the code had to be in specific columns (e.g., division headers in Area A, statements in Area B). Modern Cobol, especially with compilers like GnuCOBOL, supports "free-format" code. This eliminates the column restrictions, allowing for indentation and a layout similar to modern languages, making it much easier to write and read.

What does `PIC X(13)` actually mean?

PIC is short for the PICTURE clause, which defines the type and size of a data item. X indicates the data type is alphanumeric (can contain any character). (13) indicates the fixed length of the data item is 13 bytes/characters. Cobol requires precise data definitions, which helps prevent buffer overflows and ensures data integrity.

Do I need a mainframe to learn or run Cobol?

No, you do not. Thanks to modern open-source compilers like GnuCOBOL, you can write, compile, and run Cobol programs on any standard operating system, including Windows (with WSL), macOS, and Linux. This allows you to learn the language and its logic without needing access to expensive mainframe hardware.

What is the purpose of the period `.` in Cobol?

The period in Cobol serves as a full stop or statement terminator. It marks the end of a "sentence" (a single statement) or a "paragraph" (a block of code under a label). Forgetting a period, or putting one in the wrong place, is one of the most common syntax errors for beginners.

Where do I go after "Hello, World!"?

Your next steps involve exploring the DATA DIVISION in more depth by learning about different data types (numeric, alphabetic), performing basic arithmetic operations (ADD, SUBTRACT, MULTIPLY, DIVIDE), and understanding program flow control with IF statements and PERFORM loops. The kodikra Cobol learning roadmap is structured to guide you through these concepts sequentially.


Conclusion: Your First Step into a Larger World

You have successfully navigated the foundational syntax and structure of Cobol to create a working program. While "Hello, World!" is a simple achievement, the process has revealed the core philosophy of Cobol: a language built for clarity, structure, and long-term stability. You've configured a compiler, understood the roles of the IDENTIFICATION and PROCEDURE divisions, and executed code that bridges a gap of over 60 years of computing history.

This is not just an academic exercise. The skills you've started building today are directly applicable to maintaining and enhancing the systems that form the bedrock of our modern economy. As you continue your journey through the exclusive kodikra.com curriculum, you will build upon this foundation, exploring data manipulation, file handling, and complex business logic—the very tasks that Cobol excels at.

Technology Disclaimer: The code and commands in this article have been validated using GnuCOBOL 3.1.2 on a Linux-based system. While Cobol standards are highly stable, compiler flags and system behavior may vary slightly on different platforms.


Published by Kodikra — Your trusted Cobol learning resource.