COBOL - gregorymorrison/euler1 GitHub Wiki

COBOL is one of the oldest languages still in regular use. Introduced in 1959, it's an imperative language that has had some modernizations such as object-orientation. Even though it is used heavily in my office, I've never looked at the language before; I was always scared of its baroque syntax and ugly interface. Well, I just found a version of COBOL available for Windows, Linux, and OSX called OpenCOBOL, so I decided to give it a whirl.

My experience was not a pleasant one. This language has a dinosaur feel to it, much like Fortran. The language itself is very simplistic, but the compiler is super-cranky - everything is extremely explicit. Functions are actually written as separate programs. Integer datatypes of different lengths are actually considered different datatypes. And it actually requires the first seven positions of each line to be empty - a holdover from card readers. Really - you port over a version of the language to a PC and you keep that limitation? Okaaay...  It took me maybe a day and a half to write this version of Euler1 - available documentation for COBOL on the Internet is not that great.

       * Euler1 in COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. myTest.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  cnt     PIC 9(4) VALUE 999.
       01  result  PIC 9(9).
       PROCEDURE DIVISION.
           CALL "euler1" USING BY CONTENT cnt, 
                               BY REFERENCE result.
           DISPLAY result.
           STOP RUN.
       END PROGRAM myTest.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. euler1.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  quot PIC 9(3) VALUE 0.
       01  rem  PIC 9(3) VALUE 0.
       LINKAGE SECTION.
       01  cnt     PIC 9(4).
       01  result  PIC 9(9) VALUE 0.
       PROCEDURE DIVISION USING cnt, result.
           PERFORM UNTIL cnt <= 0
               DIVIDE 3 INTO cnt GIVING quot REMAINDER rem
               IF rem = 0 THEN
                   ADD cnt TO result
               ELSE
                   DIVIDE 5 INTO cnt GIVING quot REMAINDER rem
                   IF rem = 0 THEN
                       ADD cnt TO result 
                    END-IF 
                END-IF

               ADD -1 TO cnt
           END-PERFORM 
       EXIT PROGRAM.
       END PROGRAM euler1.

OpenCOBOL converts your program into C which it then hands off to gcc, so you'll also need that installed also. You can grab it with yum as open-cobol, along with additional dependencies libdb and libdb-devel if you don't already have those. To compile your code, run cobc, passing it your file as an argument. Then simply run the resulting object file. Notice the displayed result has the same size as the declared result variable:

$ cobc -x Euler1.cob
$ ./Euler1
000233168