SEARCH ALL
Part of the Tables and Text section of Coddy's COBOL Programming journey. Lesson 7 of 19.
SEARCH ALL is a binary search: it checks the middle element, keeps the half that can hold the key and repeats. A table of 1000 elements takes about 10 checks instead of up to 1000.
It needs the table sorted on a key, and the key declared in the OCCURS clause:
05 CODE-ENTRY OCCURS 5 TIMES
ASCENDING KEY IS CTRY
INDEXED BY CX.
10 CTRY PIC X(2).
10 DIAL PIC 9(3).No SET first: SEARCH ALL places the index itself. Its one WHEN compares the key with =:
SEARCH ALL CODE-ENTRY
AT END DISPLAY "No such country"
WHEN CTRY(CX) = WANTED
DISPLAY DIAL(CX)
END-SEARCH.COBOL does not check the order. If the rows are not sorted on the key, SEARCH ALL can run AT END for a key that is in the table. DESCENDING KEY declares a table sorted from high to low.
Challenge
EasyThe table is sorted by CTRY. Declare ASCENDING KEY IS CTRY on CODE-ENTRY, then use SEARCH ALL to display Dial 033 for FR, or No such country.
Example input, one line per ACCEPT: FR.
Try it yourself
IDENTIFICATION DIVISION.
PROGRAM-ID. DIAL.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 CODES.
05 CODE-ENTRY OCCURS 5 TIMES
INDEXED BY CX.
10 CTRY PIC X(2).
10 DIAL PIC 9(3).
01 WANTED PIC X(2).
PROCEDURE DIVISION.
MOVE "DE049ES034FR033IL972US001" TO CODES.
ACCEPT WANTED.
*> Use SEARCH ALL here
STOP RUN.