!====================================================================== ! This file: http://ftp.aset.psu.edu/pub/ger/fortran/hdk/loopnest.f90 ! ! ROUTINE: LOOPNEST FORTRAN ! ! PURPOSE: To illustrate how to program an variable number of loop ! index values. ! COPYRIGHT (c) H. D. Knoble 03/16/88 ! The Pennsylvania State University ! Center for Academic Computing ! hdkLESS at NOSPAMpsu dot edu ! !====================================================================== ! IMPLICIT NONE INTEGER :: NumberOfLoops,t,z,TotalTrips INTEGER, DIMENSION(10) :: LoopIndex, TripCount LOGICAL :: PREVIOUS CHARACTER (LEN=80) :: Line ! Print *, "Please enter the number of loops to be generated:" READ(*,"(A)") Line if(Line == "") GoTo 99 READ(Line,*,END=99) NumberOfLoops if (NumberOfLoops < 1) GoTo 99 Print *, "Please enter #trips for each loop (",NumberOfLoops, & " positive integers):" READ(*,"(A)") Line if(Line == "") GoTo 99 READ(Line,*,End=99) (TripCount(t),t=1,NumberOfLoops) ! !---Algorithm Begin ! ! Input: NumberOfLoops, and the trip count set: ! (TripCount(1), TripCount(2), ... TripCount(NumberOfLoops). ! Output: Each index set, one at a time, in lexicographic order. ! !--- Initialize. TotalTrips=1 DO t=1,NumberOfLoops TotalTrips=TotalTrips*TripCount(t) if (TotalTrips < 1 ) then print *, "Zero trip count or Integer overflow at", & & "TripCount=",TripCount(t)," t=",t GoTo 99 endif LoopIndex(t)=TripCount(t) END DO !--- The two nested coded loops following the comments are equivalent ! to an indefinite number "NumberOfLoops" of loops illustrated in ! the comments: ! do LoopIndex(1)=1 to TripCount(1) ! do LoopIndex(2)=1 to TripCount(2) ! ... ! do LoopIndex(NumberOfLoops) = 1 to TripCount(NumberOfLoops) ! PRINT *, (LoopIndex(t),t=1,NumberOfLoops) ! enddo; enddo; , ... , enddo ! DO z=1,TotalTrips previous=.TRUE. DO t=NumberOfLoops,1,-1 !-------- Generate the index set "LoopIndex" in lexicographic order, if(previous) LoopIndex(t)=1+MOD(LoopIndex(t),TripCount(t)) previous=previous .AND. (LoopIndex(t) == 1) END DO !------ and use them here (or output them) one set at a time. Print *, (LoopIndex(t),t=1,NumberOfLoops) END DO !---Algorithm End 99 STOP END