Search code examples
cobol

How to move the last digit to the first position of a number in cobol


Say I have the number 123456, how can i move the 6 to the beginning so it becomes 612345?

needs to work if the number has fewer digits like 123 becoming 312.

many thanks in advance.


Solution

  • This is a general purpose method that will work with any integer from 2 to 32 digits. The number must be usage display.

       working-storage section.
       1 a-number pic 9(6) value 123456.
       1 b-number pic 9(3) value 123.
       1 work pic x(32).
       1 len-of-number binary pic 9(4).
       procedure division.
       begin.
           display a-number
           move a-number (1:) to work
           perform swap-digit
           move work to a-number (1:)
           display a-number
           display space
           display b-number
           move b-number (1:) to work
           perform swap-digit
           move work to b-number (1:)
           display b-number
           stop run
           .
       swap-digit.
           move 0 to len-of-number
           inspect work tallying
               len-of-number for characters before space
           move function reverse (work (1:len-of-number))
               to work
           move function reverse (work (2:len-of-number - 1))
               to work (2:len-of-number - 1)
           .
    

    Output:

    123456
    612345
    
    123
    312