Let's understand Mainframe
Home Tutorials Interview Q&A Quiz Mainframe Memes Contact us About us

Module 9: Array processing and Table handling


SEARCH (Sequential/Linear search)

  • The SEARCH statement is used to search element in one-dimensional array
  • This will be easy to understand with example:-
    • Assume we have below declaration in DATA DIVISION,

      01 NAME PIC A(15). 01 STUDENT-DATA. 05 STUDENT-ARRAY OCCURS 500 TIMES INDEXED BY S1. 10 STUDENT-ID PIC 9(04). 10 STUDENT-NAME PIC A(15). 10 STUDENT-MARKS PIC 9(03).

    • As shown above, we have data of 500 students which are stored as array. Each array elements consist of STUDENT-ID, STUDENT-NAME, STUDENT-MARKS. Now, as per our requirement we have to perform search on this array and we want to find out whether particular student name is present in array or not. When found, display it’s corresponding STUDENT-ID and STUDENT-MARKS
    • This can be achieved by coding below snippet in PROCEDURE DIVISION,

      SET S1 TO 1. SEARCH STUDENT-ARRAY AT END DISPLAY ‘STUDENT NOT FOUND’. WHEN NAME = STUDENT-NAME(S1) DISPLAY ‘STUDENT-ID:’ STUDENT-ID(S1) DISPLAY ‘STUDENT-MARKS:’ STUDENT-MARKS(S1)

    • Above code will look up STUDENT-ARRAY and if condition NAME = STUDENT-NAME(S1) is satisfied for any value of S1 then that student’s ID and marks will be displayed. This search will continue till the last element of array or the condition mentioned in when condition is satisfied. When entire array’s search is complete, AT END part is executed. SEARCH statement auto-increments index S1 by 1 after each single element’s look up.
  • This kind of SEARCH is called as sequential search or linear search.
  • Basic syntax:-

    SEARCH array-name     [AT END <imperative-statement-1>]     WHEN condition-1          <imperative-statement-2>    [WHEN condition-2          <imperative-statement-3>]…

  • Some important consideration while using SEARCH:-
    • SEARCH verb can ONLY be used on arrays coded with OCCURS and INDEXED BY
    • Index item must be initialized before using SEARCH
    • SEARCH statement terminated without finding particular element in table, causes Index to have unpredictable value
    • SEARCH works like this: SEARCH on array-name starts with initial value of associated index. If any of condition-1, condition-2 etc. satisfied, respective imperative statement will be executed and SEARCH is terminated and index remains set at point where condition met. If none of conditions are met then index is auto-incremented by 1. The search continues till the end of array or condition is met. AT END of the search, imperateive-statement-1 will be executed and index will have unpredictable value






© copyright mainframebug.com
Privacy Policy