MousumiG
MousumiG

Reputation: 41

Error 542 - N appears in the dimension of a variable

program factorial
implicit none
integer:: n1
real:: fact = 1.0
integer:: n = n1
integer, dimension(1:n):: x
integer:: i
print *, "Enter a number:"
read *, n1
x(1) = n1
do i=1,n1-1
  x(i+1) = n1-i
  fact = fact*x(i)
end do
print *, fact
end program factorial

I have written a code for calculating factorial of a number. I am asking the user to put in an integer 'n1', after which it will create an array variable containing n1 compartments. I am unsuccessful in compiling this. I keep getting the following error!

factorial.F95(6) : error 542 - N appears in the dimension of a variable, yet is not a dummy argument, a variable available through USE or CONTAINS association, a COMMON variable, a PARAMETER, or a PURE FUNCTION
Compilation failed.

How can I fix this? I want the array dimension to be equal to the input number. For example, say I want to calculate 5! (5 factorial), I want the x array to be of 5 (row or column) element length. Somehow, I am unable to do that!

Upvotes: 0

Views: 514

Answers (2)

Jack
Jack

Reputation: 6158

As Vladimir suggested, you have to allocate the array:

integer, dimension(:), allocatable :: x
integer :: alloc_stat

print *, "Enter a number:"
read *, n1

ALLOCATE( x(1:n1), STAT=alloc_stat )
IF ( alloc_stat .ne. 0 ) THEN
    WRITE(ERROR_UNIT,*) "Array allocation failed."
    ERROR_STOP alloc_stat
ENDIF

(I always check the status of my ALLOCATE statements. It's not whether you are paranoid or not, it's whether you're paranoid enough.)

Upvotes: 0

The constant n1 needs to be a compile time constant to be used as a static array dimension

program factorial
implicit none
integer, parameter:: n1
integer, dimension(1:n1):: x

or you need to use allocatable arrays.

Upvotes: 1

Related Questions