is not a palindrome; however, the following one is.3 5 7 2 4
4 2 6 2 4
Write a program that reads in an array and checks if it is a palindrome.
Click here to download this program.! -------------------------------------------------------------------- ! PROGRAM Palindrome: ! This program checks to see if an array is a palindrome. An array ! is a palindrome if they read the same in both directions. ! -------------------------------------------------------------------- PROGRAM Palindrome IMPLICIT NONE INTEGER, PARAMETER :: LENGTH = 30 ! maximum array size INTEGER, DIMENSION(1:LENGTH) :: x ! the array INTEGER :: Size ! actual array size (input) INTEGER :: Head ! pointer moving forward INTEGER :: Tail ! pointer moving backward INTEGER :: i ! running index READ(*,*) Size, (x(i), i = 1, Size) ! read in the input array WRITE(*,*) "Input array:" ! display the input WRITE(*,*) (x(i), i = 1, Size) Head = 1 ! scan from the beginning Tail = Size ! scan from the end DO ! checking array IF (Head >= Tail) EXIT ! exit if two pointers meet IF (x(Head) /= x(Tail)) EXIT ! exit if two elements not equal Head = Head + 1 ! equal. Head moves forward Tail = Tail - 1 ! and Tail moves backward END DO ! until done WRITE(*,*) IF (Head >= Tail) THEN ! if Head cross Tail, then we have WRITE(*,*) "The input array is a palindrome" ! a palindrome ELSE ! otherwise, it is not a palindrome WRITE(*,*) "The input array is NOT a palindrome" END IF END PROGRAM Palindrome
The out of the program is:7 1 2 3 4 3 2 1
If the input data consist of the following:Input array: 1, 2, 3, 4, 3, 2, 1 The input array is a palindrome
The out of the program is:10 1 3 5 7 9 7 5 3 2 1
Input array: 1, 3, 5, 7, 9, 7, 5, 3, 2, 1 The input array is NOT a palindrome
You may consider Head moving from left to right and Tail moving from right to left. If the elements at Head and Tail are equal, that means the input array read from left and read from right are the same from 1 up to Head and from n down to Tail.1 3 5 7 5 3 1 H T H T H T HT
To see if it is a palindrome, we should keep going until all elements are checked. However, if the elements at Head and Tail are not equal, then definitely the array is not a palindrome.
But, why do we stop when Head and Tail cross each other? This is because once they cross each other, those pairs compared earlier will be re-compared. The following illustrates the concept:
1 3 5 7 5 3 1 H T Head = 1, Tail = 7 H T Head = 2, Tail = 6 H T Head = 3, Tail = 5 HT Head = 4, Tail = 4 all pairs have been compared T H Head = 5, Tail = 3 we did it earlier!
The problem is that it contains duplicated work. Figure out it yourself please.DO Head = 1, n Tail = n - Head + 1 IF (x(Head) /= x(Tail)) EXIT END DO IF (Tail <= 0) THEN WRITE(*,*) "No." ELSE WRITE(*,*) "Yes" END IF