Loop in Fortran from a list

10,614

Solution 1

I would introduce a second index to iterate over the elements of an array:

program test

  implicit none

  integer, dimension(6)  :: A
  integer, dimension(10) :: B
  integer                :: i, j

  A = (/ 1, 3, 4, 5, 8, 9 /)
  B = (/ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 /)

  do j = 1, size(A)
     i = A(j)
     write(*,*) i, B(i)
  end do

end program test

Solution 2

Do you mean that you want to write some of the elements of an array called other_array but not all of them, and that i should take, essentially, arbitrary values in turn ? In other words you want to print not

do i = 1, size(other_array,1)
    write(*,*) other_array(i)
end do

but something like

array = [1,3,4,2,3,7,8,8,12]
write(*,*) another_array(array)

which will write the elements of another_array specified in array ? This is called array subscripting. I haven't tested this and I'm heading out now so won't.

Share:
10,614
Brian
Author by

Brian

Updated on June 13, 2022

Comments

  • Brian
    Brian almost 2 years

    I use Fortran and I was wondering if it's possible to make something like that

      do i = array
        write (*,*) i
      end do
    

    where array is a list of integer numbers not necessarily ordered.