BudiBadu Logo
Samplebadu

COBOL by Example: Table Search

COBOL 2002

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.

Code Breakdown

7
INDEXED BY IDX. Creates an internal index variable 'IDX' specifically for this table. You cannot use a regular numeric variable for SEARCH.
15
SET IDX TO 1. You must initialize the index before starting a linear SEARCH. 'SET' is used instead of 'MOVE' for indexes.
16
SEARCH STUDENT-INFO. Begins the search operation on the table row.
17
AT END. This clause executes if the search reaches the end of the table without finding a match.
18
WHEN ID-NUM(IDX) = 20. The condition to check for each row. If true, the search stops and the following code runs.