after reversing the order of elements, the result is3 5 7 2 4
4 2 7 5 3
! ---------------------------------------------------------------
! PROGRAM Reverse:
! This program reverses the order of an input array.
! ---------------------------------------------------------------
PROGRAM Reverse
IMPLICIT NONE
INTEGER, PARAMETER :: SIZE = 30 ! maximum array size
INTEGER, DIMENSION(1:SIZE) :: a ! input array
INTEGER :: n ! actual input array size
INTEGER :: Head ! pointer moving forward
INTEGER :: Tail ! pointer moving backward
INTEGER :: Temp, i
READ(*,*) n ! read in the input array
READ(*,*) (a(i), i = 1, n)
WRITE(*,*) "Input array:" ! display the input array
WRITE(*,*) (a(i), i = 1, n)
Head = 1 ! start with the beginning
Tail = n ! start with the end
DO ! for each pair...
IF (Head >= Tail) EXIT ! if Head crosses Tail, exit
Temp = a(Head) ! otherwise, swap them
a(Head) = a(Tail)
a(Tail) = Temp
Head = Head + 1 ! move forward
Tail = Tail - 1 ! move backward
END DO ! loop back
WRITE(*,*) ! display the result
WRITE(*,*) "Reversed array:"
WRITE(*,*) (a(i), i = 1, n)
END PROGRAM Reverse
Click here to download this program.
The out of the program is:8 10 50 30 70 35 97 65 59
Input array: 10, 50, 30, 70, 35, 97, 65, 59 Reversed array: 59, 65, 97, 35, 70, 30, 50, 10
The first line contains the value for n, and the second line has that number of values for the array. Please note that the following input does not work with the READ(*,*) pair:8 10 50 30 70 35 97 65 59
The reason is simple. After reading 8 into n, the remaining values on the same line are ignored. When the second READ(*,*) reads values for array a(), there is no values in the input.8 10 50 30 70 35 97 65 59
10 50 30 70 35 97 65 59
H T
H T
H T
H T
To reverse the above successfully, 10 and 59, 50 and 65,
30 and 97, and 70 and 35 must be swapped. H and T are
used to indicate the positions of the Head and Tail
pointers. Therefore,
if we have n elements, the 1st and the n-th must
be swapped, the 2nd and the (n-1)-th must be swapped,
the 3rd and the (n-2)-th must be swapped and so on.
In general, element i must be swapped with element
n-i+1.
Therefore, we could use two pointers, Head which starts at the beginning, and Tail which starts at the end and swap the elements pointed to by Head and Tail. After swapping, move Head forward and Tail backward. Then, we have a new pair of elements. In the above example, the values of Head and Tail are 1 and 8, 2 and 7, 3 and 6 and 4 and 5.
However, the following does work. Its merit is identical to that of the solution above, expressed in a slightly different way.DO i = 1, n ! Head moves forward j = n + i - 1 ! j = Tail moves backward Temp = a(i) ! swap elements a(i) = a(j) a(j) = Temp END DO
DO i = 1, n/2 ! Head moves forward j = n +i - 1 ! J = Tail moves backward Temp = a(i) ! swap elements a(i) = a(j) a(j) = Temp END DO