0

Could someone please show me how to do an implied loop in Fortran? I'm starting to learn this language.

For example, how can I do it with this piece of code?

integer(8) :: a(100), i

a(:3) = (/ 1, 2, 3 /)
do i = 4, 30
  a(i) = a(i-1) - a(i-2) + 2 * a(i-3)
enddo

Thank you.

PS: I'm happy if someone can also show me a place to read and learn Fortran from basic to advance with lots of examples.

Ovl0422
  • 13
  • 3
  • 2
    If you are learning the language, unlearn `integer(8)` immediately. Using a literal `8` for the kind constant is ugly code smell and not portable. See https://stackoverflow.com/questions/3170239/fortran-integer4-vs-integer4-vs-integerkind-4 Why would you want an implied loop? I do not think it is useful here. – Vladimir F Героям слава May 10 '20 at 07:00
  • I want to learn it as much as I can. Like in C++, I also know a range-based loop in addition to an index-wise loop. It comes in handy if I want to shorten my codes. Thank you. For shortness, this is only an example. I don't want to introduce irrelevant variables. – Ovl0422 May 10 '20 at 07:08
  • 3
    Short code doesn't mean good code. A do loop is a perfectly clear in this instance - array syntax is the only other half sensible option, is it this that you mean? An implied do loop as Vladimir says is used a bit differently. Also please unlearn integer( 8 ) – Ian Bush May 10 '20 at 07:50

2 Answers2

1

At the moment of building the implied loop, you have no array, you have an expression that just builds some sequence of things.

(i, i = 1, 3)

generates a sequence

1, 2, 3

You can print it

print *, (i, i = 1, 3)

An array only appears once you put the implied loop into an array constructor.

(/ (i, i = 1, 3) /) 

or

[(i, i = 1, 3)]

generates an anonymous array 1:3 with three elements.

But even then you get an array expression, which is indexed from one, not your array a that is on the left hand side of the assignment. The right hand side is always evaluated completely and only after that the compiler looks at the left hand side of =.

So you cannot really index and reference any previous elements of the array in an implied loop, if those elements are created by the implied loop. Keep your normal do loop for what you are doing here.

1

I can't add it as a comment since my reputation is too low: Sources for learning fortran:

Tine198
  • 136
  • 3