Factorial in COBOL
Example for versions
OpenCOBOL 1.0,
TinyCOBOL 0.65.9
This example uses iterative factorial definition. Variable which stores factorial value has type 9(15), i.e., a number of 15 digits. Command MULTIPLY
multiplies first argument by second and (counter-intuitively) puts the result into the second argument. Command DISPLAY
puts a newline after the printed value, so one has to concatenate the parts of the string before printing them. Numerical values have to be cast to string by saving them into string-type variables. There is an exception handler at multiplication, though this is optional.
Program output depends on the compiler: the number are always printed fixed-width, padded with zeros — in TinyCOBOL to total width of 18 characters, in OpenCOBOL — 15.
IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
DATA DIVISION.
WORKING-STORAGE SECTION.
77 fact pic 9(15) comp.
77 n pic 99.
77 i pic 99.
77 ist pic XX.
77 factst pic X(18).
PROCEDURE DIVISION.
move 16 to n
move 0 to i
move 1 to fact
perform until i greater than n
move i to ist
move fact to factst
display ist "! = " factst
add 1 to i
multiply i by fact
on size error display "value too big"
end-multiply
end-perform.
stop run.
Comments
]]>blog comments powered by Disqus
]]>