CBL 5: Subroutines in COBOL (30 pts)

Hello with a Subroutine

Enter this program into a file named caller.cbl:
IDENTIFICATION DIVISION.  
   PROGRAM-ID. CALLER.  
  
DATA DIVISION.  
   WORKING-STORAGE SECTION.  
      01 WS-NAME PIC A(20) VALUE 'Dolly'.  
  
PROCEDURE DIVISION.  
   CALL 'HELLO-SUB' USING WS-NAME.
STOP RUN.
Notice these items: Enter this program into a file named hello-sub.cbl:
IDENTIFICATION DIVISION.  
   PROGRAM-ID. HELLO-SUB.  
  
DATA DIVISION.  
   LINKAGE SECTION.
      01 LS-NAME PIC A(20).  
  
PROCEDURE DIVISION USING LS-NAME.  
      DISPLAY 'Hello ' LS-NAME.  
EXIT PROGRAM.
Notice these items: Execute this command to compile both source code files into an executable:
cobc -free -x -o caller caller.cbl hello-sub.cbl
Run the program. As shown below, the program works.

For more details, see COBOL - SUBROUTINES

Factoring with a Subroutine

Enter this program into a file named factor.cbl:
IDENTIFICATION DIVISION.  
   PROGRAM-ID. FACTOR.  
  
DATA DIVISION.  
   WORKING-STORAGE SECTION.  
      01 WS-I PIC 9(2).  
      01 WS-J PIC 9(2).  
      01 WS-FACTORS PIC 9(1).  
  
PROCEDURE DIVISION.  
   DISPLAY 'IS J A FACTOR OF I?'
   DISPLAY 'ENTER I'.
   ACCEPT WS-I.
   DISPLAY 'ENTER J'.
   ACCEPT WS-J.
   CALL 'DIVIDER-SUB' USING WS-I, WS-J, WS-FACTORS.
   IF WS-FACTORS = 1 THEN
      DISPLAY WS-J " FACTORS " WS-I
   ELSE
      DISPLAY WS-J " DOES NOT FACTOR " WS-I
   END-IF.
STOP RUN.
Enter this program into a file named divider-sub.cbl:
*> Divides integers I/J 
*> Returns a value of 1 if I is a factor of J
*> Otherwise returns zero

IDENTIFICATION DIVISION.  
    PROGRAM-ID. DIVIDER-SUB.  

DATA DIVISION.  
   WORKING-STORAGE SECTION.
      01 WS-K PIC 9(2).
      01 WS-R PIC 9(2).
   LINKAGE SECTION.
      01 LS-I PIC 9(2).
      01 LS-J PIC 9(2).
      01 LS-FACTORS PIC 9(1).

PROCEDURE DIVISION USING LS-I, LS-J, LS-FACTORS.
   DIVIDE LS-I BY LS-J GIVING WS-K REMAINDER WS-R.
   IF WS-R = 0 THEN
      MOVE 1 TO LS-FACTORS
   ELSE
      MOVE 0 TO LS-FACTORS
   END-IF.
EXIT PROGRAM.
Notice these items: Execute this command to compile both source code files into an executable:
cobc -free -x -o factor factor.cbl divider-sub.cbl
Run the program. As shown below, the program works.

Flag CBL 5.1: Prime below 100 (10 pts)

Write a subroutine that will test a number and determine whether it is prime.

One way to test for primality is to try dividing by all odd numbers less than half the number being tested.

Find the largest prime number below 100. That's the flag.

Flag CBL 5.2: Primes from 100 to 200 (10 pts)

Total all the prime numbers between 100 and 200. That's the flag.

Flag CBL 5.3: Twin Primes below 1000 (10 pts)

Find the largest twin prime numbers below 1000.

The flag is the larger prime of the pair.

Posted 4-8-2020 by Sam Bowne