COBOL by Example: Table Search
Searching tables with SEARCH for linear sequential search and SEARCH ALL for binary search, using INDEXED BY clause for table index variables, initializing indexes with SET statement before searching, and implementing efficient lookups with sorted tables.
Code
IDENTIFICATION DIVISION.
PROGRAM-ID. SEARCH-DEMO.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 STUDENT-TABLE.
05 STUDENT-INFO OCCURS 5 TIMES INDEXED BY IDX.
10 ID-NUM PIC 99.
10 NAME PIC X(10).
PROCEDURE DIVISION.
MOVE 10 TO ID-NUM(1) MOVE "Alice" TO NAME(1).
MOVE 20 TO ID-NUM(2) MOVE "Bob" TO NAME(2).
SET IDX TO 1.
SEARCH STUDENT-INFO
AT END DISPLAY "Not Found"
WHEN ID-NUM(IDX) = 20
DISPLAY "Found: " NAME(IDX)
END-SEARCH.
STOP RUN.Explanation
COBOL provides built-in verbs for searching tables: SEARCH (linear search) and SEARCH ALL (binary search). To use them, the table must be defined with an INDEXED BY clause. This creates a special index variable that is distinct from standard numeric variables and is optimized for table access.
The SEARCH statement starts from the current index value and checks each element sequentially. This means you must initialize the index (e.g., SET IDX TO 1) before starting the search. The AT END clause handles the case where the item is not found after scanning the entire table.
SEARCH ALL is faster for large tables because it uses a binary search algorithm. However, it requires the data in the table to be sorted by the search key (using ASCENDING/DESCENDING KEY in the definition), and it manages the index automatically.

