# Basic COBOL Calculator

Small Calculator I made for myself while trying to learn COBOL for fun. Compiler used is GNUCOBOL. Just asks for input and will either do multiplication, subtraction, or addition. Completes run after input is asked.

MATH
IDENTIFICATION DIVISION.
PROGRAM-ID. MATH.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 INP PIC A(14).
01 NUM1 PIC 9(7).
01 NUM2 PIC A(2).
88 PLU VALUE "+".
88 AIDS VALUE "-".
88 MULT VALUE "*".
01 NUM3 PIC 9(15).
01 ANS PIC 9(8).
PROCEDURE DIVISION.
DISPLAY "Input: "
ACCEPT INP.
UNSTRING INP DELIMITED BY SPACE
INTO NUM1, NUM2, NUM3
END-UNSTRING.
IF NUM2 = "+" THEN
ELSE
IF NUM2 = "-" THEN
SUBTRACT NUM1 FROM NUM3 GIVING ANS
ELSE
IF NUM2 = "*" THEN
MULTIPLY NUM1 BY NUM3 GIVING ANS
END-IF.
DISPLAY ANS.
STOP RUN.


COBOL documentation isn't as great compares to languages like C++ or Javascript, so I struggled a bit.

First off, you don't verify the data entered by the user. This is an absolute must, IMHO.

I'm no COBOL programmer, but do have some basic COBOL knowledge. Others may suggest better solutions. Anyway, here are my thoughts:

You define data item 01 INP PIC A(14) but the user needs to input numbers and operators. Picture character A means *letter of the Latin alphabet or a space", You should use X, because you cannot tell what the user will enter, and that is why you need to add code to verify.

You define the data items to hold the input numbers as PIC 9(7), and PIC 9(15), resp., and the data item to hold the operation result as PIC 9(8). How did you come up with these lengths? Make sure the result fits into the corresponding data item.

You define the data item to hold the math operator as PIC A(2), but the operators are only one character (and not of type A). Again PIC X would be appropriate.

You're defining condition names for the operators, which is a good idea.

   01 NUM2 PIC A(2).
88 PLU VALUE "+".
88 AIDS VALUE "-".
88 MULT VALUE "*".


However, you don't make user of them. You can use them in your IF statements, and in the (missing) logic to verify the input. So instead of

   IF NUM2 = "+" THEN
ELSE ...


you could code

   IF PLU THEN
ELSE ...


Instead of coding nested IF statements use other constructs the language of choice offers. In COBOL, you could make use of the EVALUATE statement as follows:

   EVALUATE TRUE
WHEN PLU

• the 2 in 01 NUM2 PIC A(2). i had no clue what it meant, and i thought it was some sort of identifier, but i was incorrect. just a dumb mistake. Commented Jan 11, 2021 at 18:19
• I see. PICTURE (or PIC) is followed by a sequence of picture characters that describe the data item. E.g. PIC AA (two bytes), or PIC AAAAA (fife bytes). The later may be abbreviated as PIC A(5). So the number in parenthesis is a repeat factor for the picture character. You can use it multiple times in a single data item, e.g. 01 DECNUM PIC 9(9)V9(4) Commented Jan 11, 2021 at 19:38