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.
- Have the string you want to reverse, in a data-item.
- Define a data item (or) a table to store the reversed string.
- 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.
- Inside the loop, for each iteration, MOVE, starting from the last character of the string, either to the destination table (or) data-item.
- After loop, DISPLAY 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!
THANKS YARRR
ReplyDeletehi can you tell me if below answer for second one is correct ?
ReplyDeleteDATA 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.