Beliavsky / FortranTip

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

Tip: implied do loop #32

Open Beliavsky opened 2 years ago

Beliavsky commented 2 years ago

An implied do loop can be used to set the values of an array in one line and to access array elements in a READ or WRITE statement, but sometimes a whole-array operation suffices. It can also be used to print a variable repeatedly.

program implied_do_loop
implicit none
integer, parameter :: n = 3
character (len=5)  :: words(n) = ["one ","four","nine"]
integer            :: vec(n),i
write (*,"(*(a,1x))") words ! one   four  nine
write (*,"(*(a,1x))") (trim(words(i)),i=1,size(words)) 
! one four nine -- one space between trimmed words
! write (*,"(*(a,1x))") trim(words) ! illegal since trim is not elemental
vec = [(i**2,i=1,n)] ! set to [1, 4, 9]
print*,vec ! 1 4 9
print*,(vec(i),i=1,n) ! same output, but simpler to use line above
! Implied do loop can have multiple entities:
print"(*(i0,1x,a,:,1x))",(vec(i),trim(words(i)),i=1,n) ! 1 one 4 four 9 nine
! print one element of vec and words on each line using "format reversion"
print"(i0,1x,a)",(vec(i),trim(words(i)),i=1,n) 
! Line above equivalent to loop below:
do i=1,n
   print"(i0,1x,a)",vec(i),trim(words(i))
end do
print "(*(1x,f0.2))",(3.14,i=1,3) ! 3.14 3.14 3.14
end program implied_do_loop
! output:
! one   four  nine 
! one four nine
!            1           4           9
!            1           4           9
! 1 one 4 four 9 nine
! 1 one
! 4 four
! 9 nine
! 1 one
! 4 four
! 9 nine
! 3.14 3.14 3.14