Printing a Fortran Array with write

February 6, 2006

Fortran 77, by default, includes a newline after every write statement. This can be a problem if you want to print a number of elements on the same line, but you don’t know how many elements there will be at compile time. Specifically, if you want to print a matrix or two-dimensional array but you don’t know the dimensions, you probably want to do something like the following:

do, i=1:m
    do, j=1:n
        write (*,*) matrix(i,j)
    enddo
enddo

Unfortunately, this will simply print all m*n numbers on separate lines because each write is followed by a newline.

There seems to be no real standard in Fortran 77 for how to suppress the linefeed. Fortran 90/95 apparently supports adding advance="no" to the end of the format descriptor:

write(*,"(A)",advance="no") "One "
write(*,"(A)") "line."

Other earlier compilers support adding either \ or $ to the end of the format descriptor:

write(*,'(A,$)') 'One '
write(*,'(A)') 'line.'

Neither of these approaches worked with GNU g77. Instead, I used an implied do loop:

do, i=1,m
    write(*,"100g15.5") ( matrix(i,j), j=1,n )
enddo

The outer loop runs over each row of the matrix and the inner implied do loop lists each entry in row i.

References