Triangle in Cobol: Complete Solution & Deep Dive Guide

Tabs labeled

Mastering Triangle Logic: A Complete Guide to Classification in Cobol

Determining the type of a triangle—equilateral, isosceles, or scalene—is a classic programming challenge that tests fundamental logic and conditional handling. This guide provides a comprehensive, step-by-step solution in Cobol, explaining the mathematical principles, the complete code structure, and the robust logic required to build a reliable classification program from the ground up.


The Unexpected Challenge: Why Geometry Still Matters in Business Logic

Imagine you're a developer tasked with maintaining a critical logistics application, a system written decades ago in Cobol that has reliably powered the company for years. A new requirement comes in: the system needs to calculate optimal packing for triangular-shaped custom parts. Suddenly, that high school geometry you thought you'd left behind is front and center. You need to classify these shapes to determine how they fit together, and you need to do it within the existing, robust Cobol framework.

This scenario, while specific, highlights a universal truth in programming: fundamental logical problems are timeless. Whether you're working with legacy mainframe systems or modern microservices, the ability to translate mathematical rules into clean, efficient code is a core skill. This guide will walk you through solving the triangle classification problem, not just as an academic exercise, but as a practical lesson in structured programming, data validation, and logical evaluation using Cobol—a language renowned for its stability and precision.


What is Triangle Classification?

Triangle classification is the process of categorizing a triangle based on the lengths of its three sides. Before we can even classify a triangle, we must first determine if the given side lengths can form a valid triangle at all. This involves two critical rules.

The Foundational Rules of a Valid Triangle

For any three side lengths, let's call them A, B, and C, to form a valid triangle, they must satisfy two conditions:

  1. All sides must have positive lengths. A side length of zero or a negative number is geometrically impossible. Therefore, A > 0, B > 0, and C > 0.
  2. The Triangle Inequality Theorem. This theorem states that the sum of the lengths of any two sides of a triangle must be greater than the length of the third side. This ensures the three sides can connect to form a closed shape.
    • A + B > C
    • A + C > B
    • B + C > A

Only if both conditions are met can we proceed to classify the triangle.

The Three Primary Triangle Types

Once a triangle is validated, it can be classified into one of three categories based on its side lengths:

  • Equilateral: A triangle where all three sides are of equal length (e.g., 5, 5, 5).
  • Isosceles: A triangle where at least two sides are of equal length (e.g., 5, 5, 7 or 7, 5, 5). Note that for the purpose of this solution from the kodikra.com curriculum, an equilateral triangle is also considered a special case of an isosceles triangle.
  • Scalene: A triangle where all three sides have different lengths (e.g., 5, 6, 7).

Why Use Cobol for This Logic Problem?

While modern languages might seem like the obvious choice, tackling this problem in Cobol offers unique learning benefits and reinforces why the language is still a powerhouse in enterprise computing. Cobol's design philosophy forces a developer to be explicit, structured, and meticulous—qualities that are invaluable when dealing with business-critical logic.

The language's rigid structure, with its distinct IDENTIFICATION, ENVIRONMENT, DATA, and PROCEDURE divisions, compels you to think about program organization, data representation, and processing logic as separate but interconnected parts. For a problem like triangle classification, this means carefully defining your input data (the sides), your processing steps (validation and classification), and your output (the triangle type). This structured approach minimizes ambiguity and leads to highly readable and maintainable code, which is a cornerstone of enterprise software development.

Furthermore, this module from the kodikra learning path provides an excellent opportunity to master Cobol's powerful conditional statements, such as the nested IF and the elegant EVALUATE statement, which is a clean and readable alternative to complex `switch` or `case` structures in other languages.


How to Classify a Triangle in Cobol: The Complete Solution

We will now build a complete Cobol program to solve this challenge. The logic will first validate the inputs according to the rules discussed and then proceed with classification. We'll use the EVALUATE statement for its clarity and power in handling multiple conditions.

The Full Cobol Program

Here is the complete, well-commented source code. We will break down each part in the following sections.


       IDENTIFICATION DIVISION.
       PROGRAM-ID. TRIANGLE-CLASSIFIER.
       AUTHOR. KODIKRA.
      *================================================================
      * This program determines if a triangle is equilateral,
      * isosceles, or scalene based on three input side lengths.
      * It first validates if the sides can form a triangle.
      *================================================================
       DATA DIVISION.
       WORKING-STORAGE SECTION.
      *-- Variables to hold the three side lengths of the triangle.
      *-- Using PIC S9(4)V99 for signed numbers with 2 decimal places.
       01 SIDE-A          PIC S9(4)V99.
       01 SIDE-B          PIC S9(4)V99.
       01 SIDE-C          PIC S9(4)V99.

      *-- Variable to store the result of the classification.
       01 TRIANGLE-TYPE   PIC X(20).

      *-- Helper variables for the inequality theorem check.
       01 SUM-A-B         PIC S9(5)V99.
       01 SUM-A-C         PIC S9(5)V99.
       01 SUM-B-C         PIC S9(5)V99.

       PROCEDURE DIVISION.
      *----------------------------------------------------------------
      * Main paragraph that controls the program flow.
      * For this example, we hardcode values. In a real application,
      * you would use ACCEPT statements to get user input.
      *----------------------------------------------------------------
       MAIN-LOGIC.
           PERFORM INITIALIZE-VARIABLES.
           
           MOVE 5 TO SIDE-A.
           MOVE 5 TO SIDE-B.
           MOVE 5 TO SIDE-C.
           PERFORM CLASSIFY-TRIANGLE.
           DISPLAY "Sides (5, 5, 5) -> Type: " TRIANGLE-TYPE.

           MOVE 5 TO SIDE-A.
           MOVE 5 TO SIDE-B.
           MOVE 7 TO SIDE-C.
           PERFORM CLASSIFY-TRIANGLE.
           DISPLAY "Sides (5, 5, 7) -> Type: " TRIANGLE-TYPE.

           MOVE 5 TO SIDE-A.
           MOVE 6 TO SIDE-B.
           MOVE 7 TO SIDE-C.
           PERFORM CLASSIFY-TRIANGLE.
           DISPLAY "Sides (5, 6, 7) -> Type: " TRIANGLE-TYPE.

           MOVE 1 TO SIDE-A.
           MOVE 2 TO SIDE-B.
           MOVE 4 TO SIDE-C.
           PERFORM CLASSIFY-TRIANGLE.
           DISPLAY "Sides (1, 2, 4) -> Type: " TRIANGLE-TYPE.

           MOVE 0 TO SIDE-A.
           MOVE 5 TO SIDE-B.
           MOVE 5 TO SIDE-C.
           PERFORM CLASSIFY-TRIANGLE.
           DISPLAY "Sides (0, 5, 5) -> Type: " TRIANGLE-TYPE.

           STOP RUN.

      *----------------------------------------------------------------
      * Paragraph to classify the triangle.
      * It contains the core validation and classification logic.
      *----------------------------------------------------------------
       CLASSIFY-TRIANGLE.
           PERFORM VALIDATE-TRIANGLE-SIDES
           
           IF TRIANGLE-TYPE = "VALID"
               PERFORM DETERMINE-TRIANGLE-TYPE
           END-IF.

      *----------------------------------------------------------------
      * Validates if the given side lengths can form a triangle.
      * Checks for positive side lengths and the triangle inequality theorem.
      *----------------------------------------------------------------
       VALIDATE-TRIANGLE-SIDES.
           MOVE "VALID" TO TRIANGLE-TYPE.

      *-- Rule 1: All sides must be greater than 0.
           IF SIDE-A <= 0 OR SIDE-B <= 0 OR SIDE-C <= 0
               MOVE "Not a triangle" TO TRIANGLE-TYPE
               EXIT PARAGRAPH
           END-IF.

      *-- Rule 2: Triangle Inequality Theorem.
           COMPUTE SUM-A-B = SIDE-A + SIDE-B.
           COMPUTE SUM-A-C = SIDE-A + SIDE-C.
           COMPUTE SUM-B-C = SIDE-B + SIDE-C.

           IF SUM-A-B <= SIDE-C OR
              SUM-A-C <= SIDE-B OR
              SUM-B-C <= SIDE-A
                   MOVE "Not a triangle" TO TRIANGLE-TYPE
           END-IF.

      *----------------------------------------------------------------
      * Determines the type (equilateral, isosceles, scalene)
      * of a validated triangle.
      *----------------------------------------------------------------
       DETERMINE-TRIANGLE-TYPE.
           EVALUATE TRUE
      *-- Check for equilateral: all three sides are equal.
               WHEN SIDE-A = SIDE-B AND SIDE-B = SIDE-C
                   MOVE "Equilateral" TO TRIANGLE-TYPE

      *-- Check for isosceles: at least two sides are equal.
               WHEN SIDE-A = SIDE-B OR
                    SIDE-A = SIDE-C OR
                    SIDE-B = SIDE-C
                   MOVE "Isosceles" TO TRIANGLE-TYPE

      *-- If neither of the above, it must be scalene.
               WHEN OTHER
                   MOVE "Scalene" TO TRIANGLE-TYPE
           END-EVALUATE.

      *----------------------------------------------------------------
      * Initializes variables to a known state.
      *----------------------------------------------------------------
       INITIALIZE-VARIABLES.
           INITIALIZE SIDE-A, SIDE-B, SIDE-C.
           INITIALIZE TRIANGLE-TYPE.
           INITIALIZE SUM-A-B, SUM-A-C, SUM-B-C.

Logic Flow Diagram

This diagram illustrates the high-level decision-making process within our Cobol program. It shows the flow from input validation to the final classification.

    ● Start
    │
    ▼
  ┌──────────────────┐
  │  Get Side Lengths  │
  │  (A, B, C)         │
  └─────────┬──────────┘
            │
            ▼
    ◆ Are all sides > 0?
   ╱                    ╲
 Yes (Continue)          No (Invalid)
  │                      │
  ▼                      │
  ◆ Does it satisfy      │
  │ Triangle Inequality? │
   ╲                    ╱
    No (Invalid)       Yes (Valid)
      │                  │
      │                  ▼
      │             ┌────────────────┐
      │             │ Classify Shape │
      │             └───────┬────────┘
      │                     │
      │         ┌───────────┴───────────┐
      │         │                       │
      ▼         ▼                       ▼
┌───────────────┐  ◆ A=B & B=C?     ◆ A=B or A=C or B=C?
│ Set "Invalid" │     Yes → [Equilateral]    Yes → [Isosceles]
└───────────────┘         No ─────────────── No → [Scalene]
      │                                     │
      └───────────────────┬─────────────────┘
                          ▼
                    ┌──────────────┐
                    │ Display Result │
                    └──────────────┘
                          │
                          ▼
                       ● End

Code Walkthrough: A Deep Dive

Let's break down the program into its constituent parts to understand how it works.

IDENTIFICATION DIVISION

This is the simplest division. It serves as the program's header, providing metadata like the PROGRAM-ID. It's mandatory and is always the first part of a Cobol program.


       IDENTIFICATION DIVISION.
       PROGRAM-ID. TRIANGLE-CLASSIFIER.
       AUTHOR. KODIKRA.

DATA DIVISION

Here, we declare all the variables our program will use. This is a core feature of Cobol's structured nature—all data must be explicitly defined before use.


       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 SIDE-A          PIC S9(4)V99.
       01 SIDE-B          PIC S9(4)V99.
       01 SIDE-C          PIC S9(4)V99.

       01 TRIANGLE-TYPE   PIC X(20).

       01 SUM-A-B         PIC S9(5)V99.
       01 SUM-A-C         PIC S9(5)V99.
       01 SUM-B-C         PIC S9(5)V99.
  • WORKING-STORAGE SECTION: This is where we define variables that are not part of input or output files.
  • 01 SIDE-A PIC S9(4)V99: This defines a numeric variable. Let's decode the PIC clause:
    • S: Indicates the number is signed (can be positive or negative).
    • 9(4): Represents four digits before the decimal point.
    • V: An implied decimal point position. It doesn't take up storage space.
    • 99: Represents two digits after the decimal point.
    • This format allows us to handle side lengths like 1234.56 with precision.
  • 01 TRIANGLE-TYPE PIC X(20): Defines an alphanumeric variable (a string) that can hold up to 20 characters. This will store our results like "Equilateral" or "Not a triangle".
  • 01 SUM-A-B...: These are helper variables for our calculations. Notice their size is slightly larger (S9(5)V99) to prevent potential overflow when adding two sides together.

PROCEDURE DIVISION

This is where the action happens. It contains the executable logic of our program, organized into paragraphs (similar to functions or methods).

MAIN-LOGIC Paragraph:

This is the entry point of our program. For demonstration, we use hardcoded values and call the classification logic for several test cases. In a real-world scenario, you would replace the MOVE statements with ACCEPT SIDE-A FROM CONSOLE to get dynamic user input.


       MAIN-LOGIC.
           PERFORM INITIALIZE-VARIABLES.
           
           MOVE 5 TO SIDE-A.
           MOVE 5 TO SIDE-B.
           MOVE 5 TO SIDE-C.
           PERFORM CLASSIFY-TRIANGLE.
           DISPLAY "Sides (5, 5, 5) -> Type: " TRIANGLE-TYPE.
           
           ... other test cases ...

           STOP RUN.
  • PERFORM CLASSIFY-TRIANGLE: This is how you call another paragraph in Cobol. It's like a function call.
  • DISPLAY ...: Prints the output to the console.
  • STOP RUN: Terminates the program.

VALIDATE-TRIANGLE-SIDES Paragraph:

This paragraph contains the crucial validation logic. It's the gatekeeper that ensures we only try to classify valid triangles.


       VALIDATE-TRIANGLE-SIDES.
           MOVE "VALID" TO TRIANGLE-TYPE.

      *-- Rule 1: All sides must be greater than 0.
           IF SIDE-A <= 0 OR SIDE-B <= 0 OR SIDE-C <= 0
               MOVE "Not a triangle" TO TRIANGLE-TYPE
               EXIT PARAGRAPH
           END-IF.

      *-- Rule 2: Triangle Inequality Theorem.
           COMPUTE SUM-A-B = SIDE-A + SIDE-B.
           ...
           IF SUM-A-B <= SIDE-C OR ...
               MOVE "Not a triangle" TO TRIANGLE-TYPE
           END-IF.
  • First, we optimistically set the type to "VALID".
  • The first IF statement checks if any side is non-positive. If so, it sets the result to "Not a triangle" and uses EXIT PARAGRAPH to immediately stop processing this paragraph and return control to the caller.
  • The second part calculates the sums of side pairs and checks them against the third side. If any check fails, it marks the shape as invalid.

Triangle Validation Logic Flow

This diagram focuses specifically on the validation steps within the VALIDATE-TRIANGLE-SIDES paragraph.

    ● Start Validation
    │
    ▼
  ┌─────────────────┐
  │ Assume "VALID"  │
  └────────┬────────┘
           │
           ▼
    ◆ Side A > 0?
   ╱             ╲
 Yes              No ───┐
  │                     │
  ▼                     │
  ◆ Side B > 0?         │
 ╱             ╲        │
Yes              No ───┤
 │                     │
 ▼                     │
 ◆ Side C > 0?         ├─→ ┌──────────────────┐
╱             ╲        │   │ Set "Invalid"    │
Yes              No ───┘   └────────┬─────────┘
 │                                   │
 ▼                                   ▼
┌───────────────────┐             ● End Validation
│ Check Inequality: │
│ (A+B > C, etc.)   │
└─────────┬─────────┘
          │
          ▼
    ◆ Is theorem met?
   ╱                 ╲
 Yes (Remains "VALID")  No ──→ ┌──────────────────┐
  │                            │ Set "Invalid"    │
  │                            └────────┬─────────┘
  ▼                                     ▼
 ● End Validation                ● End Validation

DETERMINE-TRIANGLE-TYPE Paragraph:

This is the heart of the classification. We use an EVALUATE statement, which is one of Cobol's most readable and powerful control structures.


       DETERMINE-TRIANGLE-TYPE.
           EVALUATE TRUE
               WHEN SIDE-A = SIDE-B AND SIDE-B = SIDE-C
                   MOVE "Equilateral" TO TRIANGLE-TYPE

               WHEN SIDE-A = SIDE-B OR
                    SIDE-A = SIDE-C OR
                    SIDE-B = SIDE-C
                   MOVE "Isosceles" TO TRIANGLE-TYPE

               WHEN OTHER
                   MOVE "Scalene" TO TRIANGLE-TYPE
           END-EVALUATE.
  • EVALUATE TRUE: This structure checks each WHEN condition sequentially. The first one that evaluates to true has its code block executed, and then the EVALUATE block is exited.
  • The order is important here. We check for equilateral first because an equilateral triangle also meets the condition for being isosceles. By checking for the most specific case first, we ensure correct classification.
  • WHEN OTHER: This is a catch-all case. If none of the preceding conditions are met, this block is executed. In our logic, if a triangle is not equilateral and not isosceles, it must be scalene.

Compiling and Running the Program

To compile and run this Cobol code, you'll need a Cobol compiler. A popular open-source option is GnuCOBOL (formerly OpenCOBOL). Once installed, you can use the following commands in your terminal.

1. Save the code in a file named triangle.cbl.

2. Compile the code using the cobc command:


$ cobc -x -free triangle.cbl
  • -x: Creates an executable file.
  • -free: Specifies free-format source code, which is more modern and easier to write than the old fixed-format.

3. Run the generated executable:


$ ./triangle

You should see the following output, showing the results for all our test cases:


Sides (5, 5, 5) -> Type: Equilateral
Sides (5, 5, 7) -> Type: Isosceles
Sides (5, 6, 7) -> Type: Scalene
Sides (1, 2, 4) -> Type: Not a triangle
Sides (0, 5, 5) -> Type: Not a triangle

Alternative Approaches and Considerations

While the EVALUATE statement is clean and efficient, the same logic can be implemented using nested IF statements. This is a more traditional approach but can become harder to read as the logic gets more complex.

Using Nested IF Statements

Here's how the DETERMINE-TRIANGLE-TYPE paragraph would look using nested IFs:


       DETERMINE-TRIANGLE-TYPE-IF.
           IF SIDE-A = SIDE-B AND SIDE-B = SIDE-C
               MOVE "Equilateral" TO TRIANGLE-TYPE
           ELSE
               IF SIDE-A = SIDE-B OR
                  SIDE-A = SIDE-C OR
                  SIDE-B = SIDE-C
                   MOVE "Isosceles" TO TRIANGLE-TYPE
               ELSE
                   MOVE "Scalene" TO TRIANGLE-TYPE
               END-IF
           END-IF.

Comparison: EVALUATE vs. Nested IF

Both approaches are logically sound, but they have different implications for code readability and maintainability.

Aspect EVALUATE Statement Nested IF Statements
Readability Excellent. The "when... then" structure is flat and easy to follow, resembling a checklist. Good for simple cases, but can become deeply nested and hard to read (the "arrowhead" anti-pattern).
Maintainability Easier to add new conditions. You just add another WHEN clause without re-nesting logic. Adding new conditions might require restructuring the IF/ELSE blocks, increasing the risk of errors.
Performance Generally comparable to a well-structured IF block. Modern compilers often optimize them similarly. Can be highly performant, but complex nesting might have a slight overhead depending on the compiler.
Best For Multiple, mutually exclusive conditions, similar to a switch or case statement. Simple binary (true/false) decisions or a small number of chained conditions.

For this specific problem, the EVALUATE statement is arguably superior due to its clarity and flat structure, which makes the classification logic immediately obvious to anyone reading the code.


Frequently Asked Questions (FAQ)

Why is the order of checks important in the EVALUATE statement?

The order is crucial because an equilateral triangle (all sides equal) also satisfies the condition for an isosceles triangle (at least two sides equal). If we checked for isosceles first, an equilateral triangle would be incorrectly classified as isosceles. By checking for the most specific case (equilateral) first, we ensure the correct classification is assigned before the more general case is considered.

What does PIC S9(4)V99 mean and why is it used?

PIC stands for Picture Clause, which defines the type and format of a data item. S9(4)V99 defines a signed (S) numeric field with a total of 6 digits: four digits (9(4)) before an implied decimal point (V) and two digits (99) after it. This is Cobol's way of handling fixed-point decimal arithmetic, which avoids the potential floating-point rounding errors common in other languages and is critical for financial and scientific calculations where precision is paramount.

Can this program handle negative side lengths?

Yes. The VALIDATE-TRIANGLE-SIDES paragraph explicitly checks if any side is less than or equal to zero (IF SIDE-A <= 0 ...). If this condition is met, it immediately classifies the shape as "Not a triangle" and stops further processing. The use of S in the PIC clause allows the variable to hold a negative value, which is then caught by our validation logic.

What is the purpose of the WORKING-STORAGE SECTION?

The WORKING-STORAGE SECTION within the DATA DIVISION is used to declare variables and data structures that are local to the program. These are variables used for temporary storage, calculations, flags, and holding intermediate results, as opposed to data being read from or written to files (which would be defined in the FILE SECTION). In our program, all variables—SIDE-A, TRIANGLE-TYPE, etc.—are defined here.

Is Cobol still relevant for new developers to learn?

Absolutely. While not typically used for web or mobile app development, Cobol underpins a vast portion of the global economy, running on mainframes in banking, finance, insurance, and government systems. There is a high demand for developers who can maintain and modernize these critical systems. Learning Cobol through resources like the kodikra Cobol curriculum provides a unique and valuable skill set that can lead to stable, high-paying careers.

What does the EXIT PARAGRAPH statement do?

The EXIT PARAGRAPH statement provides an immediate exit from the current paragraph being executed. It's a control flow statement that returns execution to the statement following the PERFORM that called the paragraph. In our validation logic, we use it to stop checking as soon as we find a rule violation (e.g., a side length of zero), making the code more efficient.

How can I get user input instead of using hardcoded values?

You can use the ACCEPT verb to get input from the console. You would first DISPLAY a prompt to the user and then ACCEPT the value into your variable. For example:

DISPLAY "Enter length of side A: ".
ACCEPT SIDE-A.
DISPLAY "Enter length of side B: ".
ACCEPT SIDE-B.
DISPLAY "Enter length of side C: ".
ACCEPT SIDE-C.

This would make the program interactive.


Conclusion: From Geometric Theory to Robust Code

We have successfully translated a fundamental geometric problem into a robust, readable, and efficient Cobol program. This journey has reinforced several key principles of quality software development: the importance of rigorous data validation, the power of structured programming, and the elegance of choosing the right control structure for the task at hand. The use of the EVALUATE statement demonstrates how Cobol, despite its age, provides clean and powerful tools for implementing complex business logic.

By mastering concepts like the triangle inequality theorem and implementing them in a structured language, you are building a foundation that transcends any single programming language. The skills of careful planning, precise data definition, and logical clarity are universally applicable. This module from the kodikra.com curriculum is more than just a coding exercise; it's a lesson in building software that is correct, maintainable, and reliable.

To continue your journey and explore more advanced topics, check out the full Cobol 3 learning path or dive deeper into the language with our complete Cobol guide.

Disclaimer: The code in this article is written for modern Cobol compilers like GnuCOBOL. Syntax and features may vary slightly with other compilers, such as those on IBM z/OS. Always consult your specific compiler's documentation.


Published by Kodikra — Your trusted Cobol learning resource.