Cobol reverse a string
To reverse a string in COBOL, you can use the following code:
IDENTIFICATION DIVISION.
PROGRAM-ID. REVERSE-STRING.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 INPUT-STRING PIC X(100).
01 REVERSED-STRING PIC X(100).
01 LENGTH PIC 9(3).
PROCEDURE DIVISION.
DISPLAY "Enter a string: ".
ACCEPT INPUT-STRING.
MOVE FUNCTION LENGTH(INPUT-STRING) TO LENGTH.
PERFORM REVERSE-LOOP VARYING I FROM LENGTH BY -1 UNTIL I = 0.
DISPLAY "Reversed string: " REVERSED-STRING.
STOP RUN.
REVERSE-LOOP.
MOVE FUNCTION SUBSTRING(INPUT-STRING, I, 1) TO REVERSED-STRING(LENGTH - I + 1:1).
This code prompts the user to enter a string, then it uses a loop to reverse the string character by character. The reversed string is stored in the variable REVERSED-STRING
, and it is displayed at the end.
Please note that the code assumes a maximum string length of 100 characters. You can adjust the PIC X(100)
declarations to match your desired maximum string length.