12. Arrays in subprograms

Fortran subprogram calls are based on call by reference . This means that the calling parameters are not copied to the called subprogram, but rather that the addresses of the parameters (variables) are passed. This saves a lot of memory space when dealing with arrays. No extra storage is needed as the subroutine operates on the same memory locations as the calling (sub-)program. However, you as a programmer have to know about this and take it into account.

It is possible to declare local arrays in Fortran subprograms, but this feature is rarely used. Typically, all arrays are declared (and dimensioned) in the main program and then passed on to the subprograms as needed.

Variable length arrays

A basic vector operation is the saxpy operation. This calculates the expression

where alpha is a scalar but x and y are vectors. Here is a simple subroutine for this:

The only new feature here is the use of the asterisk in the declarations x(*) and y(*) . This notation says that x and y are arrays of arbitrary length. The advantage of this is that we can use the same subroutine for all vector lengths. Recall that since Fortran is based on call-by-reference, no additional space is allocated but rather the subroutine works directly on the array elements from the calling routine/program. It is the responsibility of the programmer to make sure that the vectors x and y really have been declared to have length n or more in some other program unit. A common error in Fortran 77 occurs when you try to access out-of-bounds array elements.

We could also have declared the arrays like this:

Most programmers prefer to use the asterisk notation to emphasize that the "real array length" is unknown. Some old Fortran 77 programs may declare variable length arrays like this:

This is legal syntax even if the array lengths are greater than one! But this is poor programming style and is strongly discouraged.

Passing subsections of arrays

Next we want to write a subroutine for matrix-vector multiplication. There are two basic ways to do this, either by using inner products or saxpy operations. Let us be modular and re-use the saxpy code from the previous section. A simple code is given below.

There are several important things to note here. First, note that even if we have written the code as general as possible to allow for arbitrary dimensions m and n, we still need to specify the leading dimension of the matrix A. The variable length declaration (*) can only be used for the last dimension of an array! The reason for this is the way Fortran 77 stores multidimensional arrays (see the section on arrays).

When we compute y = A*x by saxpy operations, we need to access columns of A. The j'th column of A is A(1:m,j). However, in Fortran 77 we cannot use such subarray syntax (but it is encouraged in Fortran 90!). So instead we provide a pointer to the first element in the column, which is A(1,j) (it is not really a pointer, but it may be helpful to think of it as if it were). We know that the next memory locations will contain the succeeding array elements in this column. The saxpy subroutine will treat A(1,j) as the first element of a vector, and does not know that this vector happens to be a column of a matrix.

Finally, note that we have stuck to the convention that matrices have m rows and n columns. The index i is used as a row index (1 to m) while the index j is used as a column index (1 to n). Most Fortran programs handling linear algebra use this notation and it makes it a lot easier to read the code!

Different dimensions

Sometimes it can be beneficial to treat a 1-dimensional array as a 2-dimensional array and vice versa. This is fairly simple to do in Fortran 77, some will say it is too easy!

Let us look at a very simple example. Another basic vector operation is scaling , i.e. multiplying each element in a vector by the same constant. Here is a subroutine for this:

Now suppose we have a m by n matrix we want to scale. Instead of writing a new subroutine for this, we can simply treat the matrix as a vector and use the subroutine scale . A simple version is given first:

Note that this example works because we assume the declared dimension of A equals the actual dimension of the matrix stored in A. This does not hold in general. Often the leading dimension lda is different from the actual dimension m, and great care must be taken to handle this correctly. Here is a more robust subroutine for scaling a matrix that uses the subroutine scale :

This version works even when m is not equal to lda since we scale one column at a time and only process the m first elements of each column (leaving the rest untouched).

Copyright © 1995-7 by Stanford University. All rights reserved.

Initialisation

The value of every variable and array element is undefined at the start of program execution unless it has been initialised in a DATA statement. Undefined values may be used in executable statements only in ways which cause them to become defined. There are a number of ways of assigning a value to a variable or array element, including:

  • on the left side of an assignment statement
  • in the data transfer list of a READ statement
  • as a DO  loop control variable
  • in a procedure call provided that the corresponding dummy argument is defined before control is returned to the calling program unit
  • as an internal file identifer in a WRITE statement
  • as an I/O status identifier in any I/O statement
  • in an INQUIRE statement

Using undefined variables in any other way can cause obscure errors which are fiendishly difficult to track down. Make sure your variables and arrays are properly initialised before you use them.

Assignment Operator

The equals sign = acts as an assignment operator in FORTRAN 77.

An arithmetic assignment statement has the form

where the symbolic name represents a variable or array element of type COMPLEX , DOUBLE PRECISION , INTEGER or REAL . If the arithmetic expression on the right side of the = operator has a different type from the symbolic name on the left, type conversion is automatically applied to the value of the arithmetic expression before it is applied to the variable or array element.

Consider this program fragment where an array and a number of variables are declared and then initialised.

In this example, the REAL variable Y is assigned the value 119.7 and the REAL variable Z is assigned the value -4.5.

The COMPLEX variable X holds the value which can be written mathematically as 119.7 - 4.5 i .

The variable DUB is given the value 3.21 × 10 8 using double precision rather than single precision.

In the statement K = Y , automatic type conversion occurs since K is type INTEGER and Y is type REAL . However, the value assigned to K is 119 and not 120. The REAL value is truncated, not rounded.

Finally, a DO  loop is used to initialise the REAL array:

  • ARRAY(1) is assigned 2.0*Y + 1*Z
  • ARRAY(2) is assigned 2.0*Y + 2*Z
  • ARRAY(3) is assigned 2.0*Y + 3*Z
  • ARRAY(4) is assigned 2.0*Y + 4*Z
  • ARRAY(5) is assigned 2.0*Y + 5*Z

An character assignment statement has the form

where the symbolic name represents a variable, array element or substring of type CHARACTER .

In the first assignment statement, the string Hello world is assigned to the variable HELLO and is stored as Hello ␣ world where ␣ is a blank or space. The second assignment statement assigns the string Earth to the substring HELLO(7:11) which means the variable HELLO now contains Hello ␣ Earth . The previously defined values in positions 1 through 6 are unaffected. (If HELLO had not been previously defined, then those positions would still be undefined.)

Now consider what happens if the expression on the right is longer than the variable on the left:

In this statement, a character expression of length 11 is assigned to a variable of length 5. When this occurs, the characters after position 5 are lost and the variable GREET contains Hello , the first 5 characters of HELLO .

Finally, examine the case where the expression on the right is shorter than the variable on the left:

When this happens, blanks ␣ are appended (added to the right side). The variable BYE is stored as Farewell ␣ ␣ ␣ ␣ ␣ ␣ ␣ ␣ ␣ ␣ ␣ ␣ .

An logical assignment statement has the form

where the symbolic name represents a variable or array element of type LOGICAL .

The logical expression ANS .EQ. 'Y' .OR. ANS .EQ. 'y' evaluates to .TRUE. only if ANS contains either Y or y . Once the expression is evaluated, the value assigned to the LOGICAL variable DEBUG

= Is Not 'Equals'

It is important to realise that the assignment operator = is not an 'equals sign' in the mathematical sense. In FORTRAN 77, the assignment operator = always assigns the value on the right side of the operator to the symbolic name on the left side of the operator. Thus, X = -13 is a valid arithmetic assignment statement but -13 = X is not, even though the mathematical statements x = -13 and -13 = x are equivalent.

PARAMETER Statement

A variable is simply a named memory location of a fixed type. The value of a variable can be changed during the execution of the program. A named constant , on the other hand, is fixed at compile time and cannot be changed. The PARAMETER statement is used to assign a constant value to a symbolic name.

Although the value of a FORTRAN 77 constant cannot be changed elsewhere in the program, it can be used in other PARAMETER statements as well as in type declarations, DATA statements and in calculations.

The value of the DOUBLE PRECISION constant PI is assigned in the PARAMETER statement. The value of another DOUBLE PRECISION constant, TWOPI , is also assigned in the same PARAMETER statement. This is done simply by multiplying the already-defined constant PI by 2D0 . Later in the program, the value of PI is used in an arithmetic expression.

In this set of declarations, the constants COLS and ROWS are declared to be of type INTEGER before being given the values in the following PARAMETER statement. After the constants have been defined, they can be used in the array declarations on the next line. Using named constants as array bounds is a common application in FORTRAN 77.

CHARACTER constants are also possible. They can be declared in the following manner:

The length of the CHARACTER constant cname is automatically set to the length of the string in the PARAMETER statement. This only works with CHARACTER constants, not CHARACTER variables which must have the length explicitly declared. The CHARACTER*(*) statement must precede the PARAMETER statement.

In this example, the CHARACTER constant ERRMSG is 17 characters long and contains the string Division by zero!

LOGICAL constants can take the values .TRUE. or .FALSE.

The LOGICAL constant DEBUG is set to .TRUE. and is used in an IF statement later in the program.

DATA Statement

The DATA statement is also used to initialise variables and arrays. It takes the form

where var-list is a list of variable names, array names, substring names and implied  DO lists, and value-list is a list of literal or named constants, optionally preceded by a repeat-count and an asterisk * . The repeat-count is either an unsigned integer value or a named constant.

The DATA statement must follow the type specification statements but can appear anywhere else in the program unit. By convention, they always appear directly after the specification statements and before the executable statements.

The important difference between the DATA and PARAMETER statements is that the DATA statement specifies an initial value for a variable or array element which may be subsequently changed during program execution. The value of a named constant defined by a PARAMETER statement may not be changed.

In this example, the CHARACTER variable is initialised to the value myinput.dat ␣ ␣ ␣ ␣ ␣ ␣ ␣ ␣ ␣ where ␣ is a blank or space. YEAR takes the initial value 2013 and DEBUG is set to .FALSE.

An equivalent set of statements would be

although there is little to recommend this last version.

Initialising Arrays

Either an entire array or just certain specified elements can be initialised in a DATA statement. If the entire array is being initialised, then just the name of the array is used in the DATA statement but all of the elements must then be initialised.

A repeat count of 500 is used to initialise all elements of the array MASS to 0.0 . The first 100 elements of the array OFFON are initialised to .TRUE. and the remaining 400 elements are set to .FALSE. .

It is common practice to use named constants as array bounds and it is permissible to use named constants (but not expressions involving named constants) in DATA statements.

This code accomplishes the same task as the previous snippet but uses named constants in the DATA statement.

If only a few elements of an array are to initialised, then each element must be listed separately.

Only the second and seventh elements of the array SMALL are initialised. All of the rest of the array elements remain undefined.

Implied DO loop

An implied  DO  loop allows selective access to array elements and is used in I/O statements as well as DATA statements. The general form of the implied  DO  loop is

The rules for the initial-value , final-value and step-size are exactly the same as for a DO  loop. An implied  DO  loop may contain other implied  DO  loops nested within.

The first line of the DATA statement assigns the value .TRUE. to the array elements with odd-numbered indices whilst the continuation line of the statement initialises the even-numbered array elements with the value .FALSE.

Nested implied  DO  loops are particularly useful when initialising multi-dimensional arrays.

This DATA statement initialises the upper triangular part of the square matrix (two-dimensional array) UPTRI to 1.0 . The rest of the matrix is undefined.

DATA Statements in Procedures

In the main program unit, a nonexecutable DATA statement has the same effect as a bunch of assignment statements at the very beginning of the program.

is equivalent to

However, this does not hold true in procedures. In an external function or subroutine, the DATA statement sets the values exactly once, before the procedure is called, whereas assignment statements are executed every time the procedure is called. This can be useful if there are certain actions which need to happen the first time a procedure is called but not subsequently.

The first time the subroutine is called, the LOGICAL variable OPENED is initialised to .FALSE. Therefore, the logical expression .NOT. OPENED is .TRUE. on the first call and the block  IF statement is executed. A file is opened and the variable OPENED is reset to .TRUE. . Then RECORD is read in from the opened file and the subroutine returns to the calling program. On subsequent calls to this subroutine, the logical expression in the block  IF will always be .FALSE. and the subroutine will only read in another value into RECORD . This is because the SAVE command preserves the value of OPENED between calls to the subroutine.

Note that DATA cannot be used to initialise variables or arrays which are dummy arguments in the procedure. DATA cannot be used to initialise values in blank COMMON blocks but can be used in the special BLOCK DATA subroutine to initialise variables in named COMMON blocks.

Table of Contents Index

Obliquity

Allocatable Arrays #

The allocatable attribute provides a safe way for memory handling. In comparison to variables with pointer attribute the memory is managed automatically and will be deallocated automatically once the variable goes out-of-scope. Using allocatable variables removes the possibility to create memory leaks in an application.

They can be used in subroutines to create scratch or work arrays, where automatic arrays would become too large to fit on the stack.

The allocation status can be checked using the allocated intrinsic to avoid uninitialized access

To allocate variables inside a procedure the dummy argument has to carry the allocatable attribute. Using it in combination with intent(out) will deallocate previous allocations before entering the procedure:

The allocated array can be used afterwards like a normal array

An already allocated array cannot be allocated again without prior deallocation. Similarly, deallocation can only be invoked for allocated arrays. To reallocate an array use

Passing allocated arrays to procedures does not require the allocatable attribute for the dummy arguments anymore.

Passing an unallocated array in this context will lead to an invalid memory access. Allocatable arrays can be passed to optional dummy arguments – if they are unallocated the argument will not be present. The allocatable attribute is not limited to arrays and can also be associated with scalars, which can be useful in combination with optional dummy arguments.

Allocations can be moved between different arrays with allocatable attribute using the move_alloc intrinsic subroutine.

Finally, allocations do not initialize the array. The content of the uninitialized array is most likely just the bytes of whatever was previously at the respective address. The allocation supports initialization using the source attribute:

The source keyword supports scalar and array valued variables and constants.

Two-Dimensional Array

where A is the name of the array. E1 and F1 are the lower bounds of the first and second dimensions, respectively, and E2 and F2 are the upper bounds of the first and second dimensions, respectively. If either of the lower bounds is not specified, such as in A(E2,F1:F2) , the value is assumed to be 1. The upper bounds are always required for each dimension. For examples of Fortran 77 usage, see SGEMV, DGEMV, CGEMV, ZGEMV, SGEMX, DGEMX, SGEMTX, and DGEMTX (Matrix-Vector Product for a General Matrix, Its Transpose, or Its Conjugate Transpose) .

Each element A(I,J) of the array A , declared A (1: n , 1: m ), containing real or complex data, occupies the storage location whose address is given by the following formula:

  • Previous : Arithmetic Expressions
  • Next : Rules of Assignment

Character String Assignment

The meaning of character assignment is to copy characters from the right to the left side.

Execution of a character assignment statement causes evaluation of the character expression and assignment of the resulting value to v .

If e is longer than v , characters on the right are truncated.

If e is shorter than v , blank characters are padded on the right.

Example: The following program below displays joined DD : CHARACTER A*4, B*2, C*8 A = 'join' B = 'ed' C = A // B PRINT *, C END

Also, this program displays the equal string: IF ( ('ab' // 'cd') .EQ. 'abcd' ) PRINT *, 'equal' END

Example: Character assignment: CHARACTER BELL*1, C2*2, C3*3, C5*5, C6*6 REAL Z C2 = 'z' C3 = 'uvwxyz' C5 = 'vwxyz' C5(1:2) = 'AB' C6 = C5 // C2 I = 'abcd' Z = 'wxyz' BELL = CHAR(7) Control Character (^G)

Example 4: A Hollerith assignment: @ CHARACTER S*4 INTEGER I2*2, I4*4 REAL R S = 4Hwxyz I2 = 2Hyz I4 = 4Hwxyz R = 4Hwxyz

  • © 2010, Oracle Corporation and/or its affiliates

IMAGES

  1. (PDF) FORTRAN 77 & MATLAB Codes

    fortran 77 array assignment

  2. Classical Fortran 77 work array containing 3 grids.

    fortran 77 array assignment

  3. The storage format of arrays in Fortran (a), and the plastic strain

    fortran 77 array assignment

  4. FORTRAN 77

    fortran 77 array assignment

  5. FORTRAN 77 Programming

    fortran 77 array assignment

  6. Fortran 77 Intrinsic Functions

    fortran 77 array assignment

VIDEO

  1. NPTEL assignment 1 Jan -April|Network Analysis|problem on mesh analysis

  2. assignment 30 to 32 govornor sindh it course

  3. bpsc 103 solved assignment 2023-24 || bpsc 103 solved assignment 2024 in Hindi || ignou bpsc103

  4. Array Assignment

  5. Chapter 7 Arrays and Arraylist Part 1

  6. 5. Programming with modern FORTRAN. Variables and assignment operator

COMMENTS

  1. Arrays (FORTRAN 77 Language Reference)

    FORTRAN 77 Language Reference. ... Arrays . An array is a named collection of elements of the same type. It is a nonempty sequence of data and occupies a group of contiguous storage locations. An array has a name, a set of elements, and a type. ... you can assign a value to a particular element, as follows: M(1,2) = 0.0.

  2. Fortran 77 Tutorial

    The data type Fortran uses for representing such objects is the array . A one-dimensional array corresponds to a vector, while a two-dimensional array corresponds to a matrix. To fully understand how this works in Fortran 77, you will have to know not only the syntax for usage, but also how these objects are stored in memory in Fortran 77.

  3. How to initialize two-dimensional arrays in Fortran

    For multidimensional (rank>1) arrays, the Fortran way for initialization differs from the C solution because in C multidimensional arrays are just arrays of arrays of etc. In Fortran, each rank corresponds to a different attribute of the modified data type. But there is only one array constructor, for rank-1 arrays. From these two reasons ...

  4. Arrays

    Arrays are a central object in Fortran. The creation of dynamic sized arrays is discussed in the allocatable arrays section. To pass arrays to procedures four ways are available. The preferred way to pass arrays to procedures is as assumed-shape arrays. Higher-dimensional arrays can be passed in a similar way.

  5. Arrays and strings

    An array of strings can be expressed in Fortran as an array of character variables. All elements in a character array have equal length. However, strings of varying lengths can be provided as input to the array constructor, as shown in the example below. They will be truncated or right-padded with spaces if they are longer or shorter ...

  6. FORTRAN 77

    FORTRAN 77 - Arrays. Arrays. A constant or variable is simply a symbolic name which refers to a particular memory location holding a particular type of data. An array, however, is a symbolic name which refers to a group of memory locations, all holding the same data type. Each individual memory location in an array is referenced by a subscript.

  7. PDF A Fortran Tutorial

    Fortran 77 has only one type for integer variables. Integers are usually stored as 32 bits (4 bytes) variables. Therefore, all integer variables should take on values in the range [-m,m] where m is approximately 2*10^9. Fortran 77 has two different types for floating point variables, called real and double precision.

  8. PDF Fortran 77 : Arrays

    The following Fortran program and output demonstrate the setting up and print out of arrays. Note the used of the DATA statement to input data into an array. Accessing Arrays Arrays are effectively subscripted variables. Each component of an array can be accessed for assignment of values to the array or to find the value of components of the array.

  9. Fortran 77 Tutorial

    The reason for this is the way Fortran 77 stores multidimensional arrays (see the section on arrays). When we compute y = A*x by saxpy operations, we need to access columns of A. The j'th column of A is A(1:m,j). However, in Fortran 77 we cannot use such subarray syntax (but it is encouraged in Fortran 90!).

  10. Array Declarators (FORTRAN 77 Language Reference)

    An array declarator specifies the name and properties of an array. a ( d [, d ] ... [ dl:] du. An array must appear only once in an array declarator within a program unit (main program, subroutine, function, or block common). The compiler flags multiple or duplicate array declarations within the same unit as errors.

  11. FORTRAN 77

    FORTRAN 77 - Initialisation. Initialisation. The value of every variable and array element is undefined at the start of program execution unless it has been initialised in a DATA statement. Undefined values may be used in executable statements only in ways which cause them to become defined. There are a number of ways of assigning a value to a ...

  12. Allocatable Arrays

    Allocatable Arrays#. The allocatable attribute provides a safe way for memory handling. In comparison to variables with pointer attribute the memory is managed automatically and will be deallocated automatically once the variable goes out-of-scope. Using allocatable variables removes the possibility to create memory leaks in an application.. They can be used in subroutines to create scratch or ...

  13. PDF fortran 77 tutorial

    Fortran 77 is not a free-format language, but has a very strict set of rules for how the ... Expressions and assignment Constants The simplest form of an expression is a constant. There are 6 types of constants, corresponding to the 6 data types. Here are some integer constants: ... These are most often used as an array of characters, called a ...

  14. Arrays in Fortran 77

    Multi-dimensional arrays. Fortran 77 allows arrays of up to seven dimensions. The syntax and storage format are analogous to the two-dimensional case, so we will not spend time on this. The dimension statement. There is an alternate way to declare arrays in Fortran 77. The statements.

  15. Two-Dimensional Array

    Two-Dimensional Array. Two-Dimensional Array. Edit online. For a two-dimensional array in Fortran 77, you can code: DIMENSION A (E1:E2,F1:F2) where A is the name of the array. E1 and F1 are the lower bounds of the first and second dimensions, respectively, and E2 and F2 are the upper bounds of the first and second dimensions, respectively.

  16. Allocatable arrays in fortran 77 and gfortran

    Dynamic array in Fortran 77. 12. Automatic array allocation upon assignment in Fortran. 0. Problem with memory allocation for allocatable array( real type ) 5. Fortran (re-)allocation on assignment and gfortran warnings. Hot Network Questions Execute two statements with a small difference between them

  17. fortran

    As a bit of a hack, one option you could try is the following: Declare a 2D array at least as big as the largest value you expect & initialize it all to zero. Read in row and col from the file. Only use the array with the specified range: array (1:row,1:col) This would work like so. program pre_define_array.

  18. Character String Assignment (FORTRAN 77 Language Reference)

    The form of the character string assignment is: v = e. e. Expression giving the value to be assigned. v. Variable, array element, substring, or character record field. The meaning of character assignment is to copy characters from the right to the left side. Execution of a character assignment statement causes evaluation of the character ...