Saving iterations

The following program saves all iterations. I wish to save every 10th iteration; the total iteration is 100. How I can modify it? The only way I know is somehow using a mod like if(mod(iteration,10)==0) then…

But I still do not understand how and where to use it!

or there is any routine in the stdlib to save step iterations?

iteration.f90 (2.2 KB)

1 Like

You do not want to open and leave open many files, if you
use NEWUNIT= on your open and close the file after you are
done with it you only need one filename open at a time; and
if you build the filename at time of use you do not need to
create an array of names. MOD(3f) is indeed one of several
ways you can selectively choose when to dump the files.

Are you learning Fortran on your own? If this is a homework
assignment please mark it as such, as it is not appropriate
to provide a solution as code if it is, but you are over-complicating
the problem. This would be all that is needed:

program iteration
implicit none
integer, parameter   :: timestep = 100, frequency=10
character(len = 80 ) :: filename 
integer              :: i, lun
real(kind = 8 )      :: r(10)

  do i = 1, timestep
     call random_number(r)
        open ( newunit = lun, file = filename, status = 'replace' )
        write(lun,'(e12.4)') r
  end do

end program iteration
1 Like

Of course, I am learning it by myself through books or through different websites. It is not homework. I am learning Fortran purely for my personal interest in this language.
one source out of several

OK. The reference examples are showing various cases, such as how to intentionally open and leave open multiple files and so on. It was also written prior to NEWUNIT= being commonly available, so you had to do a little work to make sure you were opening a file with an unused LUN (Logical Unit Number, or more simply the value you specified for UNIT=). For the problem as you described it the file only needs to be open for writing a single checkpoint, so you would not need or want to create an array, especially of a fixed size; but just create the name at time of use. This is assuming you know you want to overwrite any such pre-existing file of that name, as was implied by the use of STATUS=‘REPLACE’ in your example. So those are not incorrect examples, but for the problem you describe a much simpler construct is all that is needed.

1 Like