Search code examples
stringloopsreversemovecobol

Reversing a string without using reverse function in COBOL


my task is to reverse a string in cobol without using the reverse function.

So far i've got this:

MOVE 20 TO LOO.                       
MOVE 1  TO LOP.                       
MOVE 20 TO LOU.                       
MOVE EINA01 OF FORMAT1 TO WORTTXT1.   

PERFORM 20 TIMES                      
   MOVE WORTTXT1 (LOP:1) TO B (20:LOO)
   SUBTRACT 1 FROM LOO                
   ADD 1 TO LOP                       
   MOVE B  TO WORTTXT2 (20:LOU)       
   SUBTRACT 1 FROM LOU                
END-PERFORM.                          
MOVE WORTTXT2 TO AUSA01 OF FORMAT1.

AUSA01 is the output EINA01 the input.

The problem i have right now is: If i write "Hello" into the input field, all i get is "00000000000h" he just reverses the first letter but its supposed to look like " Hello".


Solution

  • As you've mentioned that the program has to reverse the spaces as well, I suggest you to modify the PERFORM loop as shown below.

    PERFORM 20 TIMES
    MOVE WORTTXT1(LOP:1) TO B(LOO:1) 
    SUBTRACT 1 FROM LOO
    ADD 1 TO LOP
    END-PERFORM.
    

    Full program:

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO-WORLD.
    DATA DIVISION.
    WORKING-STORAGE SECTION. 
    01 EINA01 PIC X(20) VALUE 'Srinivasan          '.
    01 WORTTXT1 PIC X(20) VALUE SPACES.
    01 WORTTXT2 PIC X(20) VALUE SPACES.
    01 AUSA01 PIC X(20) VALUE SPACES.
    01 B PIC X(20) VALUE SPACES. 
    01 LOO PIC 9(2) VALUE 0.
    01 LOP PIC 9(2) VALUE 0.
    PROCEDURE DIVISION.
    
    MOVE 20 TO LOO.
    MOVE 1 TO LOP.
    MOVE EINA01 TO WORTTXT1.
    
    PERFORM 20 TIMES
    MOVE WORTTXT1(LOP:1) TO B(LOO:1) 
    SUBTRACT 1 FROM LOO
    ADD 1 TO LOP
    END-PERFORM.
    
    MOVE B TO AUSA01.
    DISPLAY AUSA01.
    STOP RUN.
    

    Note: I'm not using the data items, B, LOU & WORTTXT2 as I felt that they are not required.

    Output:

              nasavinirS
    

    Try it here