SEARCH
Part of the Tables and Text section of Coddy's COBOL Programming journey. Lesson 6 of 19.
SEARCH looks through a table for the first element that matches. The table needs an index:
SET IX TO 1.
SEARCH ITEM
AT END DISPLAY "Unknown item"
WHEN ITEM-CODE(IX) = WANTED
DISPLAY ITEM-PRICE(IX)
END-SEARCH.SEARCH starts at the element the index points to and moves the index up one element at a time. SET IX TO 1 first, or the search starts wherever the index was left.
WHEN is the test. On the first match its statements run, the search stops and IX stays on the match. AT END runs when the index passes the last element.
An index that was never set has no value to rely on. Here it starts at 0, and the first WHEN stops the program:
error: subscript of 'ITEM-CODE' out of bounds: 0Challenge
EasyThe program reads an item code into WANTED. Search ITEM and display the matching price through PRICE-OUT, like 1.50 for TEA, or Unknown item when no code matches.
Example input, one line per ACCEPT: TEA.
Try it yourself
IDENTIFICATION DIVISION.
PROGRAM-ID. PRICE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 PRICE-LIST.
05 ITEM OCCURS 4 TIMES INDEXED BY IX.
10 ITEM-CODE PIC X(3).
10 ITEM-PRICE PIC 9V99.
01 WANTED PIC X(3).
01 PRICE-OUT PIC 9.99.
PROCEDURE DIVISION.
MOVE "TEA150COF220CAK310JUI180" TO PRICE-LIST.
ACCEPT WANTED.
*> Search ITEM here
STOP RUN.