Wednesday, December 5, 2018

How to reverse a string in COBOL without using FUNCTION REVERSE

Hello,

In this post I'll be showing how to reverse a string in COBOL without using an instrinsic (read instrinsic as in-built) function in COBOL, called FUNCTION REVERSE. This is also a common question asked in COBOL language interviews.

Pseudocode goes like this:
  1. Have the string you want to reverse, in a data-item.
  2. Define a data item (or) a table to store the reversed string.
  3. PERFORM a loop, with a data-item whose value is the length of the string, decremented by 1 in each iteration, until the data-item's value reached zero.
  4. Inside the loop, for each iteration, MOVE, starting from the last character of the string, either to the destination table (or) data-item.
  5. After loop, DISPLAY the reversed string.
In the following code, I've used a table to store the characters of the reversed string.

 IDENTIFICATION DIVISION.  
 PROGRAM-ID. REVERS.  
 DATA DIVISION.  
 WORKING-STORAGE SECTION.  
 01 WS-A   PIC X(50) VALUE 'SRINIVASAN'.  
 01 WS-TABLE.  
   05 WS-O OCCURS 0 TO 50 TIMES DEPENDING ON WS-LEN PIC X.   
 01 WS-I   PIC   9(3) VALUE 0.  
 01 WS-J   PIC   9(2) VALUE 1.   
 01 WS-LEN PIC 9(3) VALUE 0.   
 PROCEDURE DIVISION.  
     MOVE FUNCTION LENGTH(WS-A) TO WS-LEN.  
     PERFORM VARYING WS-I FROM WS-LEN BY -1 UNTIL WS-I = 0  
     MOVE WS-A(WS-I:1) TO WS-O(WS-J)  
     ADD 1 TO WS-J  
     END-PERFORM  
     DISPLAY WS-TABLE.   
     STOP RUN.  

Running the above COBOL program will give the following output. 


                                        NASAVINIRS

If you wish to use a data-item to store the reversed string, you can very well make use of reference modification to write the characters one by one to the destination data item as shown in the following code snippet.
 WORKING-STORAGE SECTION.  
 01 WS-A PIC X(50) VALUE 'SRINIVASAN'.  
 01 WS-OUT PIC X(50).   
 ...  
 ...  
 ...  
 PROCEDURE DIVISION.  
 MOVE FUNCTION LENGTH(WS-A) TO WS-LEN.  
 PERFORM VARYING WS-I FROM WS-LEN BY -1 UNTIL WS-I = 0  
 MOVE WS-A(WS-I:1) TO WS-OUT(WS-J:1)  
 ...  
 ...  
 ...  
 DISPLAY WS-OUT.   
 STOP RUN.  

Hope this helps!


2 comments:

  1. hi can you tell me if below answer for second one is correct ?



    DATA DIVISION.
    WORKING-STORAGE SECTION.
    01 WS-A PIC x(10) VALUE 'SRINIVASAN'.

    01 WS-I PIC 9(3) VALUE 1.
    01 WS-LEN PIC 9(3) VALUE 0.

    01 WS-OUT PIC X(10).

    PROCEDURE DIVISION.


    MOVE FUNCTION LENGTH(WS-A) TO WS-LEN.
    PERFORM VARYING WS-I FROM 1 BY 1 UNTIL WS-I = WS-LEN+1
    MOVE WS-A(WS-I:1) TO WS-OUT(WS-I:1)
    END-PERFORM.
    DISPLAY WS-OUT.
    STOP RUN.

    ReplyDelete