! Fortran Example-2: Recursive subprograms (Internal) program main implicit integer(A-Z) Parameter (Last=5, Size=10000) integer Result(Size,Last) ! to contain permutations of 5 Dimension Current(Last) Data Current /1,2,3,4,5/ ! compile-time initialization integer :: Count=0 ! Compile-time initialization call Permu (1,Last) print *, "THERE ARE ", count, " PERMUTATIONS FOUND:" Print * do 100 k=1, count write(66,55) (Result(k, Col), Col=1,Last) 100 continue 55 format (1X, 6I5) print * print * Print *, 'Factorial of ', Last, " IS ", Fact(last) stop contains Recursive subroutine Permu (P1, P2) Integer Cur, Temp, Save(Last) Intent(IN) P1, P2 ! These parameters not to be altered If (P1 .EQ. P2) then call Store ! Done in finding all permutations return end if ! else not done yet do cur=p1,p2 Save=Current ! Array expression Call Swap (Current(cur), Current(P1)) Call Permu (P1+1,P2) Current = Save ! Restore 'Current' results end do End Subroutine ! This is mandatory !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Subroutine Swap (A,B) integer A,B real :: XX=1.000 intent(Inout) A, B Temp=A A=B B=Temp End Subroutine Swap !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Subroutine Store ! This subroutine stores the current permutation found ! into the 'Result' after incrementing the count integer M count=count+1 if (Count > Size) then print *, "ERROR::: RESULT ARRAY OVERFLOW" return end if Result(Count,:) = Current ! Array expression end subroutine Store !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Recursive Integer Function Fact(N) RESULT (Fa) ! Above type specification is for RESULT name and not for the function ! Name. And, neither is to be declared again. Integer N !, Fa : This will cause a syntax error: Multiply-declaring Fa=1 If (N .LE. 1) Return Fa = N * Fact(N-1) End function FACT !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! End Program