Jump to content

Fortran/Fortran variables: Difference between revisions

From Wikibooks, open books for an open world
[unreviewed revision][unreviewed revision]
The indices of the c array should go from 0 to 3, not 1 to 4. I think.
m Programming:Fortran variables moved to Fortran/Fortran variables: to comply with wikibooks standard naming policy
(No difference)

Revision as of 11:23, 3 July 2006

In programming, a variable is a bit of data which the program can change. You normally need to declare variables before you use them, to provide information on what kind of data it should store.


In FORTRAN, by default, you do not need to declare variables before they are used. Fortran will guess the type of the variable from the first letter (if it's an I, J, K, L or M it will assume it's an integer, otherwise a real).


Allowing this is generally considered a bad idea, so it is recommended that the statement implicit none is used.


Examples of variables are:

integer, parameter :: num_days_week = 7 ! declare a constant, whose value cannot be changed
integer            :: i,j(2), k(0:1) ! declare i as an integer, j as an array of 2 integers from j(1) to j(2), k as an array of 2 integers from k(0) to k(1)
real               :: c(0:3) ! declare c as an array of 4 floating point numbers from c(0) to c(3)
character (len=5)  :: word   ! declare word as a string of length 5
logical            :: tf     ! declare a boolean variable with values .true. or .false.


A variable can be set by placing it before an equal sign, which is followed by the value to which it is set. Given the declarations above, the following assignments are possible:

i    = 3*4                 ! set i to 3*4 = 12         
j    = (/1,4/)             ! set j(1) to 1, j(2) to 4
c    = (/1.0,4.0,5.0,9.0/) ! set c(0) to 1.0, c(1) to 4.0, c(2) to 5.0, c(3) to 9.0
word = "dog"               ! set word = "dog  " . The variable word is padded with spaces on the right
tf   = .true.              ! set tf to True

A variable can appear on both sides of an assignment. The right hand side is evaluated first, and the variable is then assigned to that value. Here is an example:

i = 3    ! i has value 3
i = i*i  ! i has value 3*3 = 9

Variables can be converted from one type to another, but unlike in C or Java where you would typecast the variable, in Fortran you use the intrinsic proceedures. For instance:

real             :: r = 1.5
double precision :: d = 1.5
integer          :: i = 1.5
print *, dble(r), dble(d), dble(i)   ! Convert number to a double precision
print *, real(r), real(d), real(i)   ! Convert number to a single precision (REAL)
print *, int(r), int(d), int(i)      ! Convert number to an integer