Brian
Brian

Reputation: 14836

Loop in Fortran from a list

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.

Upvotes: 10

Views: 14476

Answers (2)

alexurba
alexurba

Reputation: 1664

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

Upvotes: 8

High Performance Mark
High Performance Mark

Reputation: 78354

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.

Upvotes: 3

Related Questions