Skip to main content

Palindrome check in FORTRAN

Short answer

Reverse the integer: repeatedly take last digit (MOD 10), build rev = rev*10 + digit, divide by 10. If reverse equals original, it is a palindrome; e.g., 121 reversed gives 121.

Write a program in FORTRAN, to check whether a positive integer entered from the keyboard is a palindrome or not. (Hints: A number is palindrome if its reverse is equal to the number itself).

Method. Keep a copy of the number in M. Reverse it: take the last digit (MOD(M,10)), append it to REV (REV = REV*10 + digit), and drop it from M (M/10) until M becomes 0. The number is a palindrome if REV equals the original N.

      PROGRAM PALIN
      INTEGER N, M, R, REV
      PRINT *, 'ENTER A POSITIVE INTEGER'
      READ *, N
      M = N
      REV = 0
   10 IF (M .GT. 0) THEN
         R = MOD(M, 10)
         REV = REV * 10 + R
         M = M / 10
         GO TO 10
      END IF
      IF (REV .EQ. N) THEN
         PRINT *, N, ' IS A PALINDROME'
      ELSE
         PRINT *, N, ' IS NOT A PALINDROME'
      END IF
      STOP
      END

Trace for 121: REV = 1, then 12, then 121; REV equals N, so it is a palindrome. For 123 the reverse is 321, so it is not.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 11 questions →