Beliavsky / FortranTip

Short instructional Fortran codes associated with Twitter @FortranTip
https://zmoon.github.io/FortranTipBrowser/
The Unlicense
64 stars 14 forks source link

Tip: nested implied do loop #34

Open Beliavsky opened 2 years ago

Beliavsky commented 2 years ago

Implied do loops can be nested, with syntax such as

print*,((m(i,j),j=1,n2),i=1,n1)

An application is to WRITE or READ array elements in an order other than the default column-major order.

program nested_implied_do
implicit none
integer, parameter :: n = 2
integer :: i,j,m(n,n)
character (len=*), parameter :: fmt = "(*(i0,:,1x))"
m(1,:) = [11,12]
m(2,:) = [21,22]
print fmt,m ! 11 21 12 22 -- column major
print fmt,((m(i,j),j=1,n),i=1,n) ! 11 12 21 22 -- row major
print fmt,(m(i,:),i=1,n) ! same as above
print fmt,transpose(m) ! same as above, but transpose is
                       ! limited to 2D arrays
end program nested_implied_do