The example program below accepts an upper case letter from the user and then uses the
SEARCH verb to search a pre-filled table of letters to
find and display the position of the letter in the alphabet.
Because a table index can be tricky to manipulate (can't display it, can't move it) the
program uses the VARYING phrase to vary an ordinary
numeric value along with the index. When the letter is found in the table, this item will
contain the same value as the index and we can display it without the complications we might
encounter with the index item. For instance, to display the value of the index item we would
require following code -
SET LetterPos TO LetterIdx
MOVE LetterPos TO PrnPos
DISPLAY LetterIn, " is in position ", PrnPos
The example below is not meant to be a practical example of how to find the position of a
letter in the alphabet. Nowadays, this task would be accomplished in much the same way as it
would in C or Modula-2 except that, in COBOL, we would use the Intrinsic Function - ORD - as
shown below.
COMPUTE PrnIdx = FUNCTION ORD(LetterIn) - FUNCTION ORD("A") + 1
>>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. LetterSearch.
AUTHOR. Michael Coughlan.
*> This program accepts an upper case letter from the
*> user and then displays which letter of the alphabet
*> it is.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 LetterTable.
02 LetterValues.
03 FILLER PIC X(13)
VALUE "ABCDEFGHIJKLM".
03 FILLER PIC X(13)
VALUE "NOPQRSTUVWXYZ".
02 FILLER REDEFINES LetterValues.
03 Letter PIC X OCCURS 26 TIMES
INDEXED BY LetterIdx.
01 LetterIn PIC X.
01 LetterPos PIC 99.
01 PrnPos PIC Z9.
PROCEDURE DIVISION.
Begin.
DISPLAY "Enter the letter please - "
WITH NO ADVANCING
ACCEPT LetterIn
SET LetterIdx LetterPos TO 1
SEARCH Letter VARYING LetterPos
AT END DISPLAY "Letter " LetterIn " not found!"
WHEN Letter(LetterIdx) = LetterIn
MOVE LetterPos TO PrnPos
DISPLAY LetterIn, " is in position ", PrnPos
END-SEARCH
STOP RUN.