2

I have the following program:

program example
implicit none
integer::i, x1
real::x(10)=0
do i=10,1,-2
  x(10-i)=2*i+1
enddo
x1=i*2-1
end program example

My problem is to determine the value of x1 but since variable i was never input or specified, how does Fortran determine the value of i used in the calculation of x1?

1 Answer 1

3

"since variable i was never input or specified"

This assumption is wrong. Inside the loop i takes exactly defined values 10, 8, 6, 4, 2.

After the loop finishes, the Fortran standard specifies that the value of i shall be the next value of the loop counter as if the loop still continued, so the value of i will be 0.

So the value of x1 will be 0*2 - 1 = -1 and it can be easily verified by adding print *, x1 at the end of the program.


But there is a different problem with your program as francescalus found out. On the first iteration the value of i is 10 and you are accessing x(10-i) which is x(0). This element does not exist, x has only elements from x(1) to x(10) so accessing x(0) is illegal and the behaviour of the whole program after that point is undefined.

Sign up to request clarification or add additional context in comments.

1 Comment

Fair enough, yes, the program as the whole becomes invalid. I have actually played with the code, but never enabled bounds checking thinking the code is too trivial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.