Implied do loop and format specifier

It seems like using implied do I can not get the 2D matrix type output here

program test
    implicit none
    integer :: i,j
    real(4), dimension(4,4) :: r
    
    call random_number(r)
    
    print*, "with format specifier"
    do i=1,4
        write(*,10) (r(i,j), j=1,4)
    end do
    
    print*, "without format specifier"
    do i=1,4
        write(*,*) (r(i,j), j=1,4)
    end do
    
    10 format (f10.4)

end program test

The output with gfortran on windows 10 is

 with format specifier
    0.0405
    0.8949
    0.2582
    0.4270
    0.3203
    0.7786
    0.3008
    0.1856
    0.5101
    0.1429
    0.8176
    0.2664
    0.2779
    0.9987
    0.4930
    0.4464
 without format specifier
   4.05029058E-02  0.894873738      0.258236468      0.426996052
  0.320268631      0.778587878      0.300842881      0.185597003
  0.510103643      0.142944932      0.817550063      0.266373038
  0.277874827      0.998683572      0.493006110      0.446365178

How to get the output as 2D Matrix using implied do construct with format specifier?

Try changing the format specifier to 10 format (*(f10.4)).
10 format (f10.4) would always print a single value per line, regardless of whether it receives a scalar or a ND-array.

4 Likes

Ditto. Before non-advancing and stream I/O was used the implied do in a WRITE statement was particularly useful for printing arbitrariy numbers of values on a single line, but an asterisk repeat count is a relatively new addition, so you would see formats like “(9999(f10.4,1x))”. It might not be needed if “f10” is sufficient to always leave a space but adding an explicit “1x” makes sure values always have white-space between them.

if available as an fpm package if you have a lot of little arrays to print and are an fpm user(it also has a gmake file). I think the stdlib project has included procedures for printing small arrays as well.

5 Likes