Hubbry Logo
FortranFortranMain
Open search
Fortran
Community hub
Fortran
logo
8 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Fortran
Fortran
from Wikipedia

Fortran
ParadigmMulti-paradigm: structured, imperative (procedural, object-oriented), generic, array
Designed byJohn Backus
DeveloperJohn Backus and IBM
First appeared1957; 68 years ago (1957)
Stable release
Fortran 2023 (ISO/IEC 1539:2023) / November 17, 2023; 23 months ago (2023-11-17)
Typing disciplinestrong, static, manifest
Filename extensions.f90, .f, .for
Websitefortran-lang.org
Major implementations
Absoft, Cray, GFortran, G95, IBM XL Fortran, Intel, Hitachi, Lahey/Fujitsu, Numerical Algorithms Group, Open Watcom, PathScale, PGI, Silverfrost, Oracle Solaris Studio, VAX/DEC/VSI, others
Influenced by
Speedcoding
Influenced
ALGOL 58, BASIC, C, Chapel,[1] CMS-2, DOPE, Fortress, MATLAB, PL/I, PACT I, MUMPS, IDL, Ratfor, SAKO[2]
  • Fortran at Wikibooks

Fortran (/ˈfɔːrtræn/; formerly FORTRAN) is a third-generation, compiled, imperative programming language that is especially suited to numeric computation and scientific computing.

Fortran was originally developed by IBM with a reference manual being released in 1956;[3] however, the first compilers only began to produce accurate code two years later.[4] Fortran computer programs have been written to support scientific and engineering applications, such as numerical weather prediction, finite element analysis, computational fluid dynamics, plasma physics, geophysics, computational physics, crystallography and computational chemistry. It is a popular language for high-performance computing[5] and is used for programs that benchmark and rank the world's fastest supercomputers.[6][7]

The IBM Blue Gene/P supercomputer installation in 2007 at the Argonne Leadership Computing Facility located in the Argonne National Laboratory, in Lemont, Illinois, US

Fortran has evolved through numerous versions and dialects. In 1966, the American National Standards Institute (ANSI) developed a standard for Fortran to limit proliferation of compilers using slightly different syntax.[8] Successive versions have added support for a character data type (Fortran 77), structured programming, array programming, modular programming, generic programming (Fortran 90), parallel computing (Fortran 95), object-oriented programming (Fortran 2003), and concurrent programming (Fortran 2008).

FORTRAN and COBOL genealogy tree

Since April 2024, Fortran has ranked among the top ten languages in the TIOBE index, a measure of the popularity of programming languages.[9]

Naming

[edit]

The first manual for FORTRAN describes it as a Formula Translating System, and printed the name with small caps, Fortran.[10]: p.2 [11] Other sources suggest the name stands for Formula Translator,[12] or Formula Translation.[13]

Early IBM computers did not support lowercase letters, and the names of versions of the language through FORTRAN 77 were usually spelled in all-uppercase.[14] FORTRAN 77 was the last version in which the Fortran character set included only uppercase letters.[15]

The official language standards for Fortran have referred to the language as "Fortran" with initial caps since Fortran 90.[citation needed]

Origins

[edit]
John Backus (1924–2007) proposed the FORTRAN project in December 1953 and received the A.M. Turing Award in 1977.

In late 1953, John W. Backus submitted a proposal to his superiors at IBM to develop a more practical alternative to assembly language for programming their IBM 704 mainframe computer.[11]: 69  Backus' historic FORTRAN team consisted of programmers Richard Goldberg, Sheldon F. Best, Harlan Herrick, Peter Sheridan, Roy Nutt, Robert Nelson, Irving Ziller, Harold Stern, Lois Haibt, and David Sayre.[16] Its concepts included easier entry of equations into a computer, an idea developed by J. Halcombe Laning and demonstrated in the Laning and Zierler system of 1952.[17]

The Fortran Automatic Coding System for the IBM 704 (October 15, 1956), the first programmer's reference manual for Fortran[10]

A draft specification for The IBM Mathematical Formula Translating System was completed by November 1954.[11]: 71  The first manual for FORTRAN appeared in October 1956,[10][11]: 72  with the first FORTRAN compiler delivered in April 1957.[11]: 75  Fortran produced efficient enough code for assembly language programmers to accept a high-level programming language replacement.[18]

John Backus said during a 1979 interview with Think, the IBM employee magazine, "Much of my work has come from being lazy. I didn't like writing programs, and so, when I was working on the IBM 701, writing programs for computing missile trajectories, I started work on a programming system to make it easier to write programs."[19]

The language was widely adopted by scientists for writing numerically intensive programs, which encouraged compiler writers to produce compilers that could generate faster and more efficient code. The inclusion of a complex number data type in the language made Fortran especially suited to technical applications such as electrical engineering.[20]

By 1960, versions of FORTRAN were available for the IBM 709, 650, 1620, and 7090 computers. Significantly, the increasing popularity of FORTRAN spurred competing computer manufacturers to provide FORTRAN compilers for their machines, so that by 1963 over 40 FORTRAN compilers existed.

FORTRAN was provided for the IBM 1401 computer by an innovative 63-phase compiler that ran entirely in its core memory of only 8000 (six-bit) characters. The compiler could be run from tape, or from a 2200-card deck; it used no further tape or disk storage. It kept the program in memory and loaded overlays that gradually transformed it, in place, into executable form, as described by Haines.[21] This article was reprinted, edited, in both editions of Anatomy of a Compiler[22] and in the IBM manual "Fortran Specifications and Operating Procedures, IBM 1401".[23] The executable form was not entirely machine language; rather, floating-point arithmetic, sub-scripting, input/output, and function references were interpreted, preceding UCSD Pascal P-code by two decades. GOTRAN, a simplified, interpreted version of FORTRAN I (with only 12 types of statements not 32) for "load and go" operation was available (at least for the early IBM 1620 computer).[24] Modern Fortran, and almost all later versions, are fully compiled, as done for other high-performance languages.

The development of Fortran paralleled the early evolution of compiler technology, and many advances in the theory and design of compilers were specifically motivated by the need to generate efficient code for Fortran programs.

FORTRAN

[edit]

The initial release of FORTRAN for the IBM 704[10] contained 32 types of statements, including:

  • DIMENSION and EQUIVALENCE statements
  • Assignment statements
  • Three-way arithmetic IF statement (since deprecated), which passed control to one of three locations in the program depending on whether the result of the arithmetic expression was negative, zero, or positive
  • Control statements for checking exceptions (IF ACCUMULATOR OVERFLOW, IF QUOTIENT OVERFLOW, and IF DIVIDE CHECK); and control statements for manipulating sense switches and sense lights (IF (SENSE SWITCH), IF (SENSE LIGHT), and SENSE LIGHT)
  • GO TO, computed GO TO, ASSIGN, and assigned GO TO
  • DO loops
  • Formatted I/O: FORMAT, READ, READ INPUT TAPE, WRITE OUTPUT TAPE, PRINT, and PUNCH
  • Unformatted I/O: READ TAPE, READ DRUM, WRITE TAPE, and WRITE DRUM
  • Other I/O: END FILE, REWIND, and BACKSPACE
  • PAUSE, STOP, and CONTINUE
  • FREQUENCY statement (for providing optimization hints to the compiler).

The arithmetic IF statement was reminiscent of (but not readily implementable by) a three-way comparison instruction (CAS—Compare Accumulator with Storage) available on the 704. The statement provided the only way to compare numbers—by testing their difference, with an attendant risk of overflow. This deficiency was later overcome by "logical" facilities introduced in FORTRAN IV.

The FREQUENCY statement was used originally (and optionally) to give branch probabilities for the three branch cases of the arithmetic IF statement. It could also be used to suggest how many iterations a DO loop might run. The first FORTRAN compiler used this weighting to perform at compile time a Monte Carlo simulation of the generated code, the results of which were used to optimize the placement of basic blocks in memory—a very sophisticated optimization for its time. The Monte Carlo technique is documented in Backus et al.'s paper on this original implementation, The FORTRAN Automatic Coding System:

The fundamental unit of program is the basic block; a basic block is a stretch of program which has one entry point and one exit point. The purpose of section 4 is to prepare for section 5 a table of predecessors (PRED table) which enumerates the basic blocks and lists for every basic block each of the basic blocks which can be its immediate predecessor in flow, together with the absolute frequency of each such basic block link. This table is obtained by running the program once in Monte-Carlo fashion, in which the outcome of conditional transfers arising out of IF-type statements and computed GO TO's is determined by a random number generator suitably weighted according to whatever FREQUENCY statements have been provided.[16]

The first FORTRAN compiler reported diagnostic information by halting the program when an error was found and outputting an error code on its console. That code could be looked up by the programmer in an error messages table in the operator's manual, providing them with a brief description of the problem.[10]: p.19–20 [25] Later, an error-handling subroutine to handle user errors such as division by zero, developed by NASA,[26] was incorporated, informing users of which line of code contained the error.

Fixed layout and punched cards

[edit]
FORTRAN code on a punched card, showing the specialized uses of columns 1–5, 6 and 73–80
A pad of FORTRAN coding forms, used by programmers to prepare programs for punching onto cards by keypunch operators.

Before the development of disk files, text editors and terminals, programs were most often entered on a keypunch keyboard onto 80-column punched cards, one line to a card. The resulting deck of cards would be fed into a card reader to be compiled. Punched card codes included no lower-case letters or many special characters, and special versions of the IBM 026 keypunch were offered that would correctly print the re-purposed special characters used in FORTRAN.

Reflecting punched card input practice, Fortran programs were originally written in a fixed-column format. A letter "C" in column 1 caused the entire card to be treated as a comment and ignored by the compiler. Otherwise, the columns of the card were divided into four fields:

  • 1 to 5 were the label field: a sequence of digits here was taken as a label for use in DO or control statements such as GO TO and IF, or to identify a FORMAT statement referred to in a WRITE or READ statement. Leading zeros are ignored and 0 is not a valid label number.
  • 6 was a continuation field: a character other than a blank or a zero here caused the card to be taken as a continuation of the statement on the prior card. The continuation cards were usually numbered 1, 2, etc. and the starting card might therefore have zero in its continuation column—which is not a continuation of its preceding card.
  • 7 to 72 contained the statement field.
  • 73 to 80 were ignored (the card reader for the IBM 704, the computer on which Fortran was developed, could only read 72 columns, placing them into twenty-four 36-bit words).[27]

Columns 73 to 80 could therefore be used for identification information, such as punching a sequence number or text, which could be used to re-order cards if a stack of cards was dropped; though in practice this was reserved for stable, production programs. An IBM 519 could be used to copy a program deck and add sequence numbers. Some early compilers, e.g., the IBM 650's, had additional restrictions due to limitations on their card readers.[28] Keypunches could be programmed to tab to column 7 and skip out after column 72. Later compilers relaxed most fixed-format restrictions, and the requirement was eliminated in the Fortran 90 standard.

Within the statement field, whitespace characters (blanks) were ignored outside a text literal. This allowed omitting spaces between tokens for brevity or including spaces within identifiers for clarity. For example, AVG OF X was a valid identifier, equivalent to AVGOFX, and 101010DO101I=1,101 was a valid statement, equivalent to 10101 DO 101 I = 1, 101 because the zero in column 6 is treated as if it were a space, while 101010DO101I=1.101 was instead 10101 DO101I = 1.101, the assignment of 1.101 to a variable called DO101I. Note the slight visual difference between a comma and a period.

Hollerith strings, originally allowed only in FORMAT and DATA statements, were prefixed by a character count and the letter H (e.g., 26HTHIS IS ALPHANUMERIC DATA.), allowing blanks to be retained within the character string. Miscounts were a problem.

Evolution

[edit]
Timeline of Fortran language
Year Informal name Official Standard
1957 FORTRAN
1958 FORTRAN II
1958 FORTRAN III
1961 FORTRAN IV
1966 FORTRAN 66 ANSI X3.9-1966
1978 FORTRAN 77 ANSI X3.9-1978
ISO 1539:1980
1991 Fortran 90 ANSI X3.198-1992
ISO/IEC 1539:1991
1997 Fortran 95 ISO/IEC 1539-1:1997
2004 Fortran 2003 ISO/IEC 1539-1:2004
2010 Fortran 2008 ISO/IEC 1539-1:2010
2018 Fortran 2018 ISO/IEC 1539-1:2018
2023 Fortran 2023 ISO/IEC 1539-1:2023

FORTRAN II

[edit]

IBM's FORTRAN II appeared in 1958. The main enhancement was to support procedural programming by allowing user-written subroutines and functions which returned values with parameters passed by reference. The COMMON statement provided a way for subroutines to access common (or global) variables. Six new statements were introduced:[29]

  • SUBROUTINE, FUNCTION, and END
  • CALL and RETURN
  • COMMON

Over the next few years, FORTRAN II added support for the DOUBLE PRECISION and COMPLEX data types.

Early FORTRAN compilers supported no recursion in subroutines. Early computer architectures supported no concept of a stack, and when they did directly support subroutine calls, the return location was often stored in one fixed location adjacent to the subroutine code (e.g. the IBM 1130) or a specific machine register (IBM 360 et seq), which only allows recursion if a stack is maintained by software and the return address is stored on the stack before the call is made and restored after the call returns. Although not specified in FORTRAN 77, many F77 compilers supported recursion as an option, and the Burroughs mainframes, designed with recursion built-in, did so by default. It became a standard in Fortran 90 via the new keyword RECURSIVE.[30]

Simple FORTRAN II program

[edit]

This program, for Heron's formula, reads data on a tape reel containing three 5-digit integers A, B, and C as input. There are no "type" declarations available: variables whose name starts with I, J, K, L, M, or N are "fixed-point" (i.e. integers), otherwise floating-point. Since integers are to be processed in this example, the names of the variables start with the letter "I". The name of a variable must start with a letter and can continue with both letters and digits, up to a limit of six characters in FORTRAN II. If A, B, and C cannot represent the sides of a triangle in plane geometry, then the program's execution will end with an error code of "STOP 1". Otherwise, an output line will be printed showing the input values for A, B, and C, followed by the computed AREA of the triangle as a floating-point number occupying ten spaces along the line of output and showing 2 digits after the decimal point, the .2 in F10.2 of the FORMAT statement with label 601.

C AREA OF A TRIANGLE WITH A STANDARD SQUARE ROOT FUNCTION
C INPUT - TAPE READER UNIT 5, INTEGER INPUT
C OUTPUT - LINE PRINTER UNIT 6, REAL OUTPUT
C INPUT ERROR DISPLAY ERROR OUTPUT CODE 1 IN JOB CONTROL LISTING
      READ INPUT TAPE 5, 501, IA, IB, IC
  501 FORMAT (3I5)
C IA, IB, AND IC MAY NOT BE NEGATIVE OR ZERO
C FURTHERMORE, THE SUM OF TWO SIDES OF A TRIANGLE
C MUST BE GREATER THAN THE THIRD SIDE, SO WE CHECK FOR THAT, TOO
      IF (IA) 777, 777, 701
  701 IF (IB) 777, 777, 702
  702 IF (IC) 777, 777, 703
  703 IF (IA+IB-IC) 777, 777, 704
  704 IF (IA+IC-IB) 777, 777, 705
  705 IF (IB+IC-IA) 777, 777, 799
  777 STOP 1
C USING HERON'S FORMULA WE CALCULATE THE
C AREA OF THE TRIANGLE
  799 S = FLOATF (IA + IB + IC) / 2.0
      AREA = SQRTF( S * (S - FLOATF(IA)) * (S - FLOATF(IB)) *
     +     (S - FLOATF(IC)))
      WRITE OUTPUT TAPE 6, 601, IA, IB, IC, AREA
  601 FORMAT (4H A= ,I5,5H  B= ,I5,5H  C= ,I5,8H  AREA= ,F10.2,
     +        13H SQUARE UNITS)
      STOP
      END

FORTRAN III

[edit]

IBM also developed a FORTRAN III in 1958 that allowed for inline assembly code among other features; however, this version was never released as a product. Like the 704 FORTRAN and FORTRAN II, FORTRAN III included machine-dependent features that made code written in it unportable from machine to machine, as well as Boolean expression support.[11]: 76  Early versions of FORTRAN provided by other vendors suffered from the same disadvantage.

FORTRAN IV

[edit]

IBM began development of FORTRAN IV in 1961 as a result of customer demands. FORTRAN IV removed the machine-dependent features of FORTRAN II (such as READ INPUT TAPE), while adding new features such as a LOGICAL data type, logical Boolean expressions, and the logical IF statement as an alternative to the arithmetic IF statement. Type declarations were added, along with an IMPLICIT statement to override earlier conventions that variables are INTEGER if their name begins with I, J, K, L, M, or N; and REAL otherwise.[31]: pp.70, 71 [32]: p.6-9 

FORTRAN IV was eventually released in 1962, first for the IBM 7030 ("Stretch") computer, followed by versions for the IBM 7090, IBM 7094, and later for the IBM 1401 in 1966.[33]

By 1965, FORTRAN IV was supposed to be compliant with the standard being developed by the American Standards Association X3.4.3 FORTRAN Working Group.[34]

Between 1966 and 1968, IBM offered several FORTRAN IV compilers for its System/360, each named by letters that indicated the minimum amount of memory the compiler needed to run. [35] The letters (F, G, H) matched the codes used with System/360 model numbers to indicate memory size, each letter increment being a factor of two larger:[36]: p. 5 

  • 1966 : FORTRAN IV F for DOS/360 (64K bytes)
  • 1966 : FORTRAN IV G for OS/360 (128K bytes)
  • 1968 : FORTRAN IV H for OS/360 (256K bytes)

Digital Equipment Corporation maintained DECSYSTEM-10 Fortran IV (F40) for PDP-10 from 1967 to 1975.[32] Compilers were also available for the UNIVAC 1100 series and the Control Data 6000 series and 7000 series systems.[37]

At about this time FORTRAN IV had started to become an important educational tool and implementations such as the University of Waterloo's WATFOR and WATFIV were created to simplify the complex compile and link processes of earlier compilers.

In the FORTRAN IV programming environment of the era, except for that used on Control Data Corporation (CDC) systems, only one instruction was placed per line. The CDC version allowed for multiple instructions per line if separated by a $ (dollar) character. The FORTRAN sheet was divided into four fields, as described above.

Two compilers of the time, IBM "G" and UNIVAC, allowed comments to be written on the same line as instructions, separated by a special character: "master space": V (perforations 7 and 8) for UNIVAC and perforations 12/11/0/7/8/9 (hexadecimal FF) for IBM. These comments were not to be inserted in the middle of continuation cards.[32][37]

FORTRAN 66

[edit]

Perhaps the most significant development in the early history of FORTRAN was the decision by the American Standards Association (now American National Standards Institute (ANSI)) to form a committee sponsored by the Business Equipment Manufacturers Association (BEMA) to develop an American Standard Fortran. The resulting two standards, approved in March 1966, defined two languages, FORTRAN (based on FORTRAN IV, which had served as a de facto standard), and Basic FORTRAN (based on FORTRAN II, but stripped of its machine-dependent features). The FORTRAN defined by the first standard, officially denoted X3.9-1966, became known as FORTRAN 66 (although many continued to term it FORTRAN IV, the language on which the standard was largely based). FORTRAN 66 effectively became the first industry-standard version of FORTRAN. FORTRAN 66 included:

  • Main program, SUBROUTINE, FUNCTION, and BLOCK DATA program units
  • INTEGER, REAL, DOUBLE PRECISION, COMPLEX, and LOGICAL data types
  • COMMON, DIMENSION, and EQUIVALENCE statements
  • DATA statement for specifying initial values
  • Intrinsic and EXTERNAL (e.g., library) functions
  • Assignment statement
  • GO TO, computed GO TO, assigned GO TO, and ASSIGN statements
  • Logical IF and arithmetic (three-way) IF statements
  • DO loop statement
  • READ, WRITE, BACKSPACE, REWIND, and ENDFILE statements for sequential I/O
  • FORMAT statement and assigned format
  • CALL, RETURN, PAUSE, and STOP statements
  • Hollerith constants in DATA and FORMAT statements, and as arguments to procedures
  • Identifiers of up to six characters in length
  • Comment lines
  • END line

The above Fortran II version of the Heron program needs several modifications to compile as a Fortran 66 program. Modifications include using the more machine independent versions of the READ and WRITE statements, and removal of the unneeded FLOATF type conversion functions. Though not required, the arithmetic IF statements can be re-written to use logical IF statements and expressions in a more structured fashion.

C AREA OF A TRIANGLE WITH A STANDARD SQUARE ROOT FUNCTION
C INPUT - TAPE READER UNIT 5, INTEGER INPUT
C OUTPUT - LINE PRINTER UNIT 6, REAL OUTPUT
C INPUT ERROR DISPLAY ERROR OUTPUT CODE 1 IN JOB CONTROL LISTING
      READ (5, 501) IA, IB, IC
  501 FORMAT (3I5)
C
C IA, IB, AND IC MAY NOT BE NEGATIVE OR ZERO
C FURTHERMORE, THE SUM OF TWO SIDES OF A TRIANGLE
C MUST BE GREATER THAN THE THIRD SIDE, SO WE CHECK FOR THAT, TOO
      IF (IA .GT. 0 .AND. IB .GT. 0 .AND. IC .GT. 0) GOTO 10
        WRITE (6, 602)
  602   FORMAT (42H IA, IB, AND IC MUST BE GREATER THAN ZERO.)
        STOP 1
   10 CONTINUE
C
      IF (IA+IB-IC .GT. 0
     +    .AND. IA+IC-IB .GT. 0
     +    .AND. IB+IC-IA .GT. 0) GOTO 20
        WRITE (6, 603)
  603   FORMAT (50H SUM OF TWO SIDES MUST BE GREATER THAN THIRD SIDE.)
        STOP 1
   20 CONTINUE
C
C USING HERON'S FORMULA WE CALCULATE THE
C AREA OF THE TRIANGLE
      S = (IA + IB + IC) / 2.0
      AREA = SQRT ( S * (S - IA) * (S - IB) * (S - IC))
      WRITE (6, 601) IA, IB, IC, AREA
  601 FORMAT (4H A= ,I5,5H  B= ,I5,5H  C= ,I5,8H  AREA= ,F10.2,
     +        13H SQUARE UNITS)
      STOP
      END

FORTRAN 77

[edit]
FORTRAN-77 program with compiler output, written on a CDC 175 at RWTH Aachen University, Germany, in 1987
4.3 BSD for the Digital Equipment Corporation (DEC) VAX, displaying the manual for FORTRAN 77 (f77) compiler

After the release of the FORTRAN 66 standard, compiler vendors introduced several extensions to Standard Fortran, prompting ANSI committee X3J3 in 1969 to begin work on revising the 1966 standard, under sponsorship of CBEMA, the Computer Business Equipment Manufacturers Association (formerly BEMA). Final drafts of this revised standard circulated in 1977, leading to formal approval of the new FORTRAN standard in April 1978. The new standard, called FORTRAN 77 and officially denoted X3.9-1978, added a number of significant features to address many of the shortcomings of FORTRAN 66:

  • Block IF and END IF statements, with optional ELSE IF and ELSE clauses, to provide improved language support for structured programming
  • DO loop extensions, including parameter expressions, negative increments, and zero trip counts
  • OPEN, CLOSE, and INQUIRE statements for improved I/O capability
  • Direct-access file I/O
  • CHARACTER data type, replacing Hollerith strings with vastly expanded facilities for character input and output and processing of character-based data
  • PARAMETER statement for specifying constants
  • SAVE statement for persistent local variables
  • Generic names for intrinsic functions (e.g. SQRT also accepts arguments of other types, such as COMPLEX or REAL*16).
  • A set of intrinsics (LGE, LGT, LLE, LLT) for lexical comparison of strings, based upon the ASCII collating sequence. (These ASCII functions were demanded by the U.S. Department of Defense, in their conditional approval vote.[citation needed])
  • A maximum of seven dimensions in arrays, rather than three. Allowed subscript expressions were also generalized.

In this revision of the standard, a number of features were removed or altered in a manner that might invalidate formerly standard-conforming programs. (Removal was the only allowable alternative to X3J3 at that time, since the concept of "deprecation" was not yet available for ANSI standards.) While most of the 24 items in the conflict list (see Appendix A2 of X3.9-1978) addressed loopholes or pathological cases permitted by the prior standard but rarely used, a small number of specific capabilities were deliberately removed, such as:

  • Hollerith constants and Hollerith data, such as GREET = 12HHELLO THERE!
  • Reading into an H edit (Hollerith field) descriptor in a FORMAT specification
  • Overindexing of array bounds by subscripts
          DIMENSION A(10,5)
          Y = A(11,1)
    
  • Transfer of control out of and back into the range of a DO loop (also known as "Extended Range")

A Fortran 77 version of the Heron program requires no modifications to the Fortran 66 version. However this example demonstrates additional cleanup of the I/O statements, including using list-directed I/O, and replacing the Hollerith edit descriptors in the FORMAT statements with quoted strings. It also uses structured IF and END IF statements, rather than GOTO/CONTINUE.

      PROGRAM HERON
C AREA OF A TRIANGLE WITH A STANDARD SQUARE ROOT FUNCTION
C INPUT - DEFAULT STANDARD INPUT UNIT, INTEGER INPUT
C OUTPUT - DEFAULT STANDARD OUTPUT UNIT, REAL OUTPUT
C INPUT ERROR DISPLAY ERROR OUTPUT CODE 1 IN JOB CONTROL LISTING
      READ (*, *) IA, IB, IC
C
C IA, IB, AND IC MAY NOT BE NEGATIVE OR ZERO
C FURTHERMORE, THE SUM OF TWO SIDES OF A TRIANGLE
C MUST BE GREATER THAN THE THIRD SIDE, SO WE CHECK FOR THAT, TOO
      IF (IA .LE. 0 .OR. IB .LE. 0 .OR. IC .LE. 0) THEN
        WRITE (*, *) 'IA, IB, and IC must be greater than zero.'
        STOP 1
      END IF
C
      IF (IA+IB-IC .LE. 0
     +    .OR. IA+IC-IB .LE. 0
     +    .OR. IB+IC-IA .LE. 0) THEN
        WRITE (*, *) 'Sum of two sides must be greater than third side.'
        STOP 1
      END IF
C
C USING HERON'S FORMULA WE CALCULATE THE
C AREA OF THE TRIANGLE
      S = (IA + IB + IC) / 2.0
      AREA = SQRT ( S * (S - IA) * (S - IB) * (S - IC))
      WRITE (*, 601) IA, IB, IC, AREA
  601 FORMAT ('A= ', I5, '  B= ', I5, '  C= ', I5, '  AREA= ', F10.2,
     +        ' square units')
      STOP
      END

Transition to ANSI Standard Fortran

[edit]

The development of a revised standard to succeed FORTRAN 77 would be repeatedly delayed as the standardization process struggled to keep up with rapid changes in computing and programming practice. In the meantime, as the "Standard FORTRAN" for nearly fifteen years, FORTRAN 77 would become the historically most important dialect.

An important practical extension to FORTRAN 77 was the release of MIL-STD-1753 in 1978.[38] This specification, developed by the U.S. Department of Defense, standardized a number of features implemented by most FORTRAN 77 compilers but not included in the ANSI FORTRAN 77 standard. These features would eventually be incorporated into the Fortran 90 standard.

The IEEE 1003.9 POSIX Standard, released in 1991, provided a simple means for FORTRAN 77 programmers to issue POSIX system calls.[39] Over 100 calls were defined in the document – allowing access to POSIX-compatible process control, signal handling, file system control, device control, procedure pointing, and stream I/O in a portable manner.

Fortran 90

[edit]

The much-delayed successor to FORTRAN 77, informally known as Fortran 90 (and prior to that, Fortran 8X), was finally released as ISO/IEC standard 1539:1991 in 1991 and an ANSI Standard in 1992. In addition to changing the official spelling from FORTRAN to Fortran, this major revision added many new features to reflect the significant changes in programming practice that had evolved since the 1978 standard:

  • Free-form source input removed the need to skip the first six character positions before entering statements.
  • Lowercase Fortran keywords
  • Identifiers up to 31 characters in length (In the previous standard, it was only six characters).
  • Inline comments
  • Ability to operate on arrays (or array sections) as a whole, thus greatly simplifying math and engineering computations.
    • whole, partial and masked array assignment statements and array expressions, such as X(1:N)=R(1:N)*COS(A(1:N))
    • WHERE statement for selective array assignment
    • array-valued constants and expressions,
    • user-defined array-valued functions and array constructors.
  • RECURSIVE procedures
  • Modules, to group related procedures and data together, and make them available to other program units, including the capability to limit the accessibility to only specific parts of the module.
  • A vastly improved argument-passing mechanism, allowing interfaces to be checked at compile time
  • User-written interfaces for generic procedures
  • Operator overloading
  • Derived (structured) data types
  • New data type declaration syntax, to specify the data type and other attributes of variables
  • Dynamic memory allocation by means of the ALLOCATABLE attribute and the ALLOCATE and DEALLOCATE statements
  • POINTER attribute, pointer assignment, and NULLIFY statement to facilitate the creation and manipulation of dynamic data structures
  • Structured looping constructs, with an END DO statement for loop termination, and EXIT and CYCLE statements for terminating normal DO loop iterations in an orderly way
  • SELECT CASE, CASE, . . . CASE DEFAULT, END SELECT construct for multi-way selection
  • Portable specification of numerical precision under the user's control
  • New and enhanced intrinsic procedures.

Obsolescence and deletions

[edit]

Unlike the prior revision, Fortran 90 removed no features.[40] Any standard-conforming FORTRAN 77 program was also standard-conforming under Fortran 90, and either standard should have been usable to define its behavior.

A small set of features were identified as "obsolescent" and were expected to be removed in a future standard. All of the functionalities of these early-version features can be performed by newer Fortran features. Some are kept to simplify porting of old programs but many were deleted in Fortran 95.

Obsolescence and deletions
Obsolescent feature Current status
Arithmetic IF-statement Obsolescent in F90, deleted in F2018
Non-integer DO parameters or control variables Obsolescent in F90, deleted in F95
Shared DO-loop termination or termination with a statement other than END DO or CONTINUE   Obsolescent in F90, deleted in F2018
Branching to END IF from outside a block Obsolescent in F90, deleted in F95
PAUSE statement Obsolescent in F90, deleted in F95
ASSIGN statement and assigned GO TO statement Obsolescent in F90, deleted in F95
Assigned statement numbers and FORMAT specifiers Obsolescent in F90, deleted in F95
H edit descriptor Obsolescent in F90, deleted in F95
Vertical format control Deleted in F2003
Alternate return Obsolescent in F90
Computed GO TO statement Obsolescent in F90
Statement functions Obsolescent in F90
DATA statements among executable statements Obsolescent in F90
Assumed length character functions Obsolescent in F90
Fixed form source code Obsolescent in F90
CHARACTER* form of CHARACTER declaration Obsolescent in F90
ENTRY statements Obsolescent in F2008
Label form of DO statement Obsolescent in F2018
COMMON and EQUIVALENCE statements, and the BLOCK DATA program unit Obsolescent in F2018
Specific names for intrinsic function Obsolescent in F2018
FORALL construct and statement Obsolescent in F2018

"Hello, World!" example

[edit]
program helloworld
     print *, "Hello, World!"
end program helloworld

Fortran 95

[edit]

Fortran 95, published officially as ISO/IEC 1539-1:1997, was a minor revision, mostly to resolve some outstanding issues from the Fortran 90 standard. Nevertheless, Fortran 95 also added a number of extensions, notably from the High Performance Fortran specification:

  • FORALL and nested WHERE constructs to aid vectorization
  • User-defined PURE and ELEMENTAL procedures
  • Default initialization of derived type components, including pointer initialization
  • Expanded the ability to use initialization expressions for data objects
  • Initialization of pointers to NULL()
  • Clearly defined that ALLOCATABLE arrays are automatically deallocated when they go out of scope.

A number of intrinsic functions were extended (for example a dim argument was added to the maxloc intrinsic).

Several features noted in Fortran 90 to be "obsolescent" were removed from Fortran 95:

  • DO statements using REAL and DOUBLE PRECISION index variables
  • Branching to an END IF statement from outside its block
  • PAUSE statement
  • ASSIGN and assigned GO TO statement, and assigned format specifiers
  • H Hollerith edit descriptor.

An important supplement to Fortran 95 was the ISO technical report TR-15581: Enhanced Data Type Facilities, informally known as the Allocatable TR. This specification defined enhanced use of ALLOCATABLE arrays, prior to the availability of fully Fortran 2003-compliant Fortran compilers. Such uses include ALLOCATABLE arrays as derived type components, in procedure dummy argument lists, and as function return values. (ALLOCATABLE arrays are preferable to POINTER-based arrays because ALLOCATABLE arrays are guaranteed by Fortran 95 to be deallocated automatically when they go out of scope, eliminating the possibility of memory leakage. In addition, elements of allocatable arrays are contiguous, and aliasing is not an issue for optimization of array references, allowing compilers to generate faster code than in the case of pointers.[41])

Another important supplement to Fortran 95 was the ISO technical report TR-15580: Floating-point exception handling, informally known as the IEEE TR. This specification defined support for IEEE floating-point arithmetic and floating-point exception handling.

Conditional compilation and varying length strings

[edit]

In addition to the mandatory "Base language" (defined in ISO/IEC 1539-1 : 1997), the Fortran 95 language also included two optional modules:

  • Varying length character strings (ISO/IEC 1539-2 : 2000)
  • Conditional compilation (ISO/IEC 1539-3 : 1998)

which, together, compose the multi-part International Standard (ISO/IEC 1539).

According to the standards developers, "the optional parts describe self-contained features which have been requested by a substantial body of users and/or implementors, but which are not deemed to be of sufficient generality for them to be required in all standard-conforming Fortran compilers." Nevertheless, if a standard-conforming Fortran does provide such options, then they "must be provided in accordance with the description of those facilities in the appropriate Part of the Standard".

Modern Fortran

[edit]

The language defined by the twenty-first century standards, in particular because of its incorporation of object-oriented programming support and subsequently Coarray Fortran, is often referred to as 'Modern Fortran', and the term is increasingly used in the literature.[42]

Fortran 2003

[edit]

Fortran 2003, officially published as ISO/IEC 1539-1:2004, was a major revision introducing many new features.[43] A comprehensive summary of the new features of Fortran 2003 is available at the Fortran Working Group (ISO/IEC JTC1/SC22/WG5) official Web site.[44]

From that article, the major enhancements for this revision include:

  • Derived type enhancements: parameterized derived types, improved control of accessibility, improved structure constructors, and finalizers
  • Object-oriented programming support: type extension and inheritance, polymorphism, dynamic type allocation, and type-bound procedures, providing complete support for abstract data types
  • Data manipulation enhancements: allocatable components (incorporating TR 15581), deferred type parameters, VOLATILE attribute, explicit type specification in array constructors and allocate statements, pointer enhancements, extended initialization expressions, and enhanced intrinsic procedures
  • Input/output enhancements: asynchronous transfer, stream access, user specified transfer operations for derived types, user specified control of rounding during format conversions, named constants for preconnected units, the FLUSH statement, regularization of keywords, and access to error messages
  • Procedure pointers
  • Support for IEEE floating-point arithmetic and floating-point exception handling (incorporating TR 15580)
  • Interoperability with the C programming language
  • Support for international usage: access to ISO 10646 4-byte characters and choice of decimal or comma in numeric formatted input/output
  • Enhanced integration with the host operating system: access to command-line arguments, environment variables, and processor error messages

An important supplement to Fortran 2003 was the ISO technical report TR-19767: Enhanced module facilities in Fortran. This report provided sub-modules, which make Fortran modules more similar to Modula-2 modules. They are similar to Ada private child sub-units. This allows the specification and implementation of a module to be expressed in separate program units, which improves packaging of large libraries, allows preservation of trade secrets while publishing definitive interfaces, and prevents compilation cascades.

Fortran 2008

[edit]

ISO/IEC 1539-1:2010, informally known as Fortran 2008, was approved in September 2010.[45][46] As with Fortran 95, this is a minor upgrade, incorporating clarifications and corrections to Fortran 2003, as well as introducing some new capabilities. The new capabilities include:

  • Sub-modules – additional structuring facilities for modules; supersedes ISO/IEC TR 19767:2005
  • Coarray Fortran – a parallel execution model
  • The DO CONCURRENT construct – for loop iterations with no interdependencies
  • The CONTIGUOUS attribute – to specify storage layout restrictions
  • The BLOCK construct – can contain declarations of objects with construct scope
  • Recursive allocatable components – as an alternative to recursive pointers in derived types

The Final Draft international Standard (FDIS) is available as document N1830.[47]

A supplement to Fortran 2008 is the International Organization for Standardization (ISO) Technical Specification (TS) 29113 on Further Interoperability of Fortran with C,[48][49] which has been submitted to ISO in May 2012 for approval. The specification adds support for accessing the array descriptor from C and allows ignoring the type and rank of arguments.

Fortran 2018

[edit]

The Fortran 2018 revision of the language was earlier referred to as Fortran 2015.[50] It was a significant revision and was released on November 28, 2018.[51]

Fortran 2018 incorporates two previously published Technical Specifications:

  • ISO/IEC TS 29113:2012 Further Interoperability with C[52]
  • ISO/IEC TS 18508:2015 Additional Parallel Features in Fortran[53]

Additional changes and new features include support for ISO/IEC/IEEE 60559:2011 (the version of the IEEE floating-point standard before the latest minor revision IEEE 754–2019), hexadecimal input/output, IMPLICIT NONE enhancements and other changes.[54][55][56][57]

Fortran 2018 deleted the arithmetic IF statement. It also deleted non-block DO constructs - loops which do not end with an END DO or CONTINUE statement. These had been an obsolescent part of the language since Fortran 90.

New obsolescences are: COMMON and EQUIVALENCE statements and the BLOCK DATA program unit, labelled DO loops, specific names for intrinsic functions, and the FORALL statement and construct.

Fortran 2023

[edit]

Fortran 2023 (ISO/IEC 1539-1:2023) was published in November 2023, and can be purchased from the ISO.[58] Fortran 2023 is a minor extension of Fortran 2018 that focuses on correcting errors and omissions in Fortran 2018. It also adds several small features, including conditional expressions and arguments, simple procedures, and an enumerated type capability. Degree- and half revolution based trig functions were also added. Degree-based trig functions were previously a very common vendor extension.

Language features

[edit]

A full description of the Fortran language features brought by Fortran 95 is covered in the related article, Fortran 95 language features. The language versions defined by later standards are often referred to collectively as 'Modern Fortran' and are described in the literature.

Science and engineering

[edit]
General relativistic magnetohydrodynamic Fortran simulation of black hole accretion using the BHAC code with cartesian adaptive mesh
Flow around a cylinder computed in Fortran with OpenCL
Velocity and sea surface temperature in the oceans, computed with the NEMO Fortran code

Although a 1968 journal article by the authors of BASIC already described FORTRAN as "old-fashioned",[59] programs have been written in Fortran for many decades and there is a vast body of Fortran software in daily use throughout the scientific and engineering communities.[60] Jay Pasachoff wrote in 1984 that "physics and astronomy students simply have to learn FORTRAN. So much exists in FORTRAN that it seems unlikely that scientists will change to Pascal, Modula-2, or whatever."[61] In 1993, Cecil E. Leith called FORTRAN the "mother tongue of scientific computing", adding that its replacement by any other possible language "may remain a forlorn hope".[62]

It is the primary language for some of the most intensive super-computing tasks, such as in astronomy, climate modeling, computational chemistry, computational economics, computational fluid dynamics, computational physics, data analysis,[63] hydrological modeling, numerical linear algebra and numerical libraries (LAPACK, IMSL and NAG), optimization, satellite simulation, structural engineering, and weather prediction.[64] Many of the floating-point benchmarks to gauge the performance of new computer processors, such as the floating-point components of the SPEC benchmarks (e.g., CFP2006, CFP2017) are written in Fortran. Math algorithms are well documented in Numerical Recipes.

Apart from this, more modern codes in computational science generally use large program libraries, such as METIS for graph partitioning, PETSc or Trilinos for linear algebra capabilities, deal.II or FEniCS for mesh and finite element support, and other generic libraries. Since the early 2000s, many of the widely used support libraries have also been implemented in C and more recently, in C++. On the other hand, high-level languages such as the Wolfram Language, MATLAB, Python, and R have become popular in particular areas of computational science. Consequently, a growing fraction of scientific programs are also written in such higher-level scripting languages. For this reason, facilities for inter-operation with C were added to Fortran 2003 and enhanced by the ISO/IEC technical specification 29113, which was incorporated into Fortran 2018 to allow more flexible interoperation with other programming languages.

Portability

[edit]

Portability was a problem in the early days because there was no agreed upon standard—not even IBM's reference manual—and computer companies vied to differentiate their offerings from others by providing incompatible features. Standards have improved portability. The 1966 standard provided a reference syntax and semantics, but vendors continued to provide incompatible extensions. Although careful programmers were coming to realize that use of incompatible extensions caused expensive portability problems, and were therefore using programs such as The PFORT Verifier,[65][66] it was not until after the 1977 standard, when the National Bureau of Standards (now NIST) published FIPS PUB 69, that processors purchased by the U.S. Government were required to diagnose extensions of the standard. Rather than offer two processors, essentially every compiler eventually had at least an option to diagnose extensions.[67][68]

Incompatible extensions were not the only portability problem. For numerical calculations, it is important to take account of the characteristics of the arithmetic. This was addressed by Fox et al. in the context of the 1966 standard by the PORT library.[66] The ideas therein became widely used, and were eventually incorporated into the 1990 standard by way of intrinsic inquiry functions. The widespread (now almost universal) adoption of the IEEE 754 standard for binary floating-point arithmetic has essentially removed this problem.

Access to the computing environment (e.g., the program's command line, environment variables, textual explanation of error conditions) remained a problem until it was addressed by the 2003 standard.

Large collections of library software that could be described as being loosely related to engineering and scientific calculations, such as graphics libraries, have been written in C, and therefore access to them presented a portability problem. This has been addressed by incorporation of C interoperability into the 2003 standard.

It is now possible (and relatively easy) to write an entirely portable program in Fortran, even without recourse to a preprocessor.

Obsolete variants

[edit]

Until the Fortran 66 standard was developed, each compiler supported its own variant of Fortran. Some were more divergent from the mainstream than others.

The first Fortran compiler set a high standard of efficiency for compiled code. This goal made it difficult to create a compiler so it was usually done by the computer manufacturers to support hardware sales. This left an important niche: compilers that were fast and provided good diagnostics for the programmer (often a student). Examples include Watfor, Watfiv, PUFFT, and on a smaller scale, FORGO, Wits Fortran, and Kingston Fortran 2.

Fortran 5 was marketed by Data General Corp from the early 1970s to the early 1980s, for the Nova, Eclipse, and MV line of computers. It had an optimizing compiler that was quite good for minicomputers of its time. The language most closely resembles FORTRAN 66.

FORTRAN V was distributed by Control Data Corporation in 1968 for the CDC 6600 series. The language was based upon FORTRAN IV.[69]

Univac also offered a compiler for the 1100 series known as FORTRAN V. A spinoff of Univac Fortran V was Athena FORTRAN.

Specific variants produced by the vendors of high-performance scientific computers (e.g., Burroughs, Control Data Corporation (CDC), Cray, Honeywell, IBM, Texas Instruments, and UNIVAC) added extensions to Fortran to take advantage of special hardware features such as instruction cache, CPU pipelines, and vector arrays. For example, one of IBM's FORTRAN compilers (H Extended IUP) had a level of optimization which reordered the machine code instructions to keep multiple internal arithmetic units busy simultaneously. Another example is CFD, a special variant of FORTRAN designed specifically for the ILLIAC IV supercomputer, running at NASA's Ames Research Center. IBM Research Labs also developed an extended FORTRAN-based language called VECTRAN for processing vectors and matrices.

Object-Oriented Fortran was an object-oriented extension of Fortran, in which data items can be grouped into objects, which can be instantiated and executed in parallel. It was available for Solaris, IRIX, NeXTSTEP, iPSC, and nCUBE, but is no longer supported.[70][71]

Such machine-specific extensions have either disappeared over time or have had elements incorporated into the main standards. The major remaining extension is OpenMP, which is a cross-platform extension for shared memory programming. One new extension, Coarray Fortran, is intended to support parallel programming.

FOR TRANSIT was the name of a reduced version of the IBM 704 FORTRAN language, which was implemented for the IBM 650, using a translator program developed at Carnegie in the late 1950s.[72] The following comment appears in the IBM Reference Manual (FOR TRANSIT Automatic Coding System C28-4038, Copyright 1957, 1959 by IBM):

The FORTRAN system was designed for a more complex machine than the 650, and consequently some of the 32 statements found in the FORTRAN Programmer's Reference Manual are not acceptable to the FOR TRANSIT system. In addition, certain restrictions to the FORTRAN language have been added. However, none of these restrictions make a source program written for FOR TRANSIT incompatible with the FORTRAN system for the 704.

The permissible statements were:

  • Arithmetic assignment statements, e.g., a = b
  • GO to n
  • GO TO (n1, n2, ..., nm), i
  • IF (a) n1, n2, n3
  • PAUSE
  • STOP
  • DO n i = m1, m2
  • CONTINUE
  • END
  • READ n, list
  • PUNCH n, list
  • DIMENSION V, V, V, ...
  • EQUIVALENCE (a,b,c), (d,c), ...

Up to ten subroutines could be used in one program.

FOR TRANSIT statements were limited to columns 7 through 56, only. Punched cards were used for input and output on the IBM 650. Three passes were required to translate source code to the "IT" language, then to compile the IT statements into SOAP assembly language, and finally to produce the object program, which could then be loaded into the machine to run the program (using punched cards for data input, and outputting results onto punched cards).

Two versions existed for the 650s with a 2000 word memory drum: FOR TRANSIT I (S) and FOR TRANSIT II, the latter for machines equipped with indexing registers and automatic floating-point decimal (bi-quinary) arithmetic. Appendix A of the manual included wiring diagrams for the IBM 533 card reader/punch control panel.

Fortran-based languages

[edit]

Prior to FORTRAN 77, many preprocessors were commonly used to provide a friendlier language, with the advantage that the preprocessed code could be compiled on any machine with a standard FORTRAN compiler.[73] These preprocessors would typically support structured programming, variable names longer than six characters, additional data types, conditional compilation, and even macro capabilities. Popular preprocessors included EFL, FLECS, iftran, MORTRAN, SFtran, S-Fortran, Ratfor, and Ratfiv. EFL, Ratfor and Ratfiv, for example, implemented C-like languages, outputting preprocessed code in standard FORTRAN 66. The PFORT preprocessor was often used to verify that code conformed to a portable subset of the language. Despite advances in the Fortran language, preprocessors continue to be used for conditional compilation and macro substitution.

One of the earliest versions of FORTRAN, introduced in the '60s, was popularly used in colleges and universities. Developed, supported, and distributed by the University of Waterloo, WATFOR was based largely on FORTRAN IV. A student using WATFOR could submit their batch FORTRAN job and, if there were no syntax errors, the program would move straight to execution. This simplification allowed students to concentrate on their program's syntax and semantics, or execution logic flow, rather than dealing with submission Job Control Language (JCL), the compile/link-edit/execution successive process(es), or other complexities of the mainframe/minicomputer environment. A down side to this simplified environment was that WATFOR was not a good choice for programmers needing the expanded abilities of their host processor(s), e.g., WATFOR typically had very limited access to I/O devices. WATFOR was succeeded by WATFIV and its later versions.

program; s=0 i=1,n; s=s+1; stop i; s='s'  Stop

(line programming)

LRLTRAN was developed at the Lawrence Radiation Laboratory to provide support for vector arithmetic and dynamic storage, among other extensions to support systems programming. The distribution included the Livermore Time Sharing System (LTSS) operating system.

The Fortran-95 Standard includes an optional Part 3 which defines an optional conditional compilation capability. This capability is often referred to as "CoCo".

Many Fortran compilers have integrated subsets of the C preprocessor into their systems.

SIMSCRIPT is an application specific Fortran preprocessor for modeling and simulating large discrete systems.

The F programming language was designed to be a clean subset of Fortran 95 that attempted to remove the redundant, unstructured, and deprecated features of Fortran, such as the EQUIVALENCE statement. F retains the array features added in Fortran 90, and removes control statements that were made obsolete by structured programming constructs added to both FORTRAN 77 and Fortran 90. F is described by its creators as "a compiled, structured, array programming language especially well suited to education and scientific computing".[74] Essential Lahey Fortran 90 (ELF90) was a similar subset.

Lahey and Fujitsu teamed up to create Fortran for the Microsoft .NET Framework.[75] Silverfrost FTN95 is also capable of creating .NET code.[76]

Code examples

[edit]

The following program illustrates dynamic memory allocation and array-based operations, two features introduced with Fortran 90. Particularly noteworthy is the absence of DO loops and IF/THEN statements in manipulating the array; mathematical operations are applied to the array as a whole. Also apparent is the use of descriptive variable names and general code formatting that conform with contemporary programming style. This example computes an average over data entered interactively.

program average

    ! Read in some numbers and take the average
    ! As written, if there are no data points, an average of zero is returned
    ! While this may not be desired behavior, it keeps this example simple

    implicit none

    real, allocatable :: points(:)
    integer           :: number_of_points
    real              :: average_points, positive_average, negative_average
    average_points   = 0.
    positive_average = 0.
    negative_average = 0.
    write (*,*) "Input number of points to average:"
    read  (*,*) number_of_points

    allocate (points(number_of_points))

    write (*,*) "Enter the points to average:"
    read  (*,*) points

    ! Take the average by summing points and dividing by number_of_points
    if (number_of_points > 0) average_points = sum(points) / number_of_points

    ! Now form average over positive and negative points only
    if (count(points > 0.) > 0) positive_average = sum(points, points > 0.) / count(points > 0.)
    if (count(points < 0.) > 0) negative_average = sum(points, points < 0.) / count(points < 0.)

    ! Print result to terminal stdout unit 6
    write (*,'(a,g12.4)') 'Average = ', average_points
    write (*,'(a,g12.4)') 'Average of positive points = ', positive_average
    write (*,'(a,g12.4)') 'Average of negative points = ', negative_average
    deallocate (points) ! free memory

end program average

Humor

[edit]

During the same FORTRAN standards committee meeting at which the name "FORTRAN 77" was chosen, a satirical technical proposal was incorporated into the official distribution bearing the title "Letter O Considered Harmful". This proposal purported to address the confusion that sometimes arises between the letter "O" and the numeral zero, by eliminating the letter from allowable variable names. However, the method proposed was to eliminate the letter from the character set entirely (thereby retaining 48 as the number of lexical characters, which the colon had increased to 49). This was considered beneficial in that it would promote structured programming, by making it impossible to use the notorious GO TO statement as before. (Troublesome FORMAT statements would also be eliminated.) It was noted that this "might invalidate some existing programs" but that most of these "probably were non-conforming, anyway".[77][unreliable source?][78]

When X3J3 debated whether the minimum trip count for a DO loop should be zero or one in Fortran 77, Loren Meissner suggested a minimum trip count of two—reasoning (tongue-in-cheek) that if it were less than two, then there would be no reason for a loop.

When assumed-length arrays were being added, there was a dispute as to the appropriate character to separate upper and lower bounds. In a comment examining these arguments, Walt Brainerd penned an article entitled "Astronomy vs. Gastroenterology" because some proponents had suggested using the star or asterisk ("*"), while others favored the colon (":").[citation needed]

Variable names beginning with the letters I–N have a default type of integer, while variables starting with any other letters defaulted to real, although programmers could override the defaults with an explicit declaration.[79] This led to the joke: "In FORTRAN, GOD is REAL (unless declared INTEGER)."

See also

[edit]

References

[edit]

Further reading

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
Fortran is a general-purpose, language designed primarily for numeric computation and scientific computing, featuring strong support for array operations, mathematical functions, and high-performance execution. Developed by a team led by at starting in 1954, it was the first high-level programming language, aimed at translating mathematical formulas into efficient to simplify coding for scientists and engineers. The initial version, known as Fortran I, was commercially released in 1957 as the IBM Mathematical Formula Translating System, with its first delivered in April of that year after testing on the computer. The language's development addressed the limitations of early computers, where programming required low-level assembly code; Fortran reduced the effort dramatically, for example, condensing a problem that took about 1,000 assembly instructions into just 47 Fortran statements. Key contributors included a diverse team of experts such as a crystallographer, cryptographer, and Lois Haibt, who emphasized collaborative learning during the three-year project. Fortran I introduced innovations like an that produced code nearly as fast as hand-assembled programs, setting a for modern compilers. Subsequent versions, such as Fortran II (1958), expanded features like subroutines and capabilities, while the language became a U.S. national standard by the mid-1960s. Over decades, Fortran has evolved through international standards set by ISO and the IEC, with the latest being Fortran 2023, which enhances parallelism through coarrays, teams, and collective operations for (HPC). It supports multiple paradigms, including procedural, object-oriented, and , while remaining statically typed for reliability and efficiency. Today, Fortran dominates in fields like , , nuclear simulations, and benchmarks, powering much of the world's scientific software due to its maturity and performance on parallel architectures. Despite competition from newer languages, it continues to be actively developed and used in mission-critical applications, underscoring its enduring impact on .

History

Origins

Development of Fortran began in 1954 at , led by , with the goal of creating a for the computer to automate mathematical computations that had previously required tedious programming. This initiative addressed the pressing need for greater programming productivity in scientific research during the early computer era, where scientists and engineers often relied on professional programmers to translate formulas into , leading to significant delays and errors. The principles emphasized a language tailored for scientific programming, prioritizing —through algebraic notation resembling mathematical expressions—and in generated , while abstracting away machine-specific details to make it more accessible than low-level alternatives. Backus's team adopted a fixed-form layout based on 72-column punched cards, where specific columns designated lines (column 6), statement labels (columns 1-5), and comments (column 7 with a C), facilitating input on the era's hardware while enforcing structured organization. Key innovations in the initial implementation included automatic memory allocation for variables and expression evaluation that handled arithmetic operations without requiring programmers to manage registers manually, marking a significant departure from assembly practices. The first was completed in 1957, releasing the initial version known as FORTRAN (short for Formula Translation), which dramatically reduced programming effort—for instance, translating a 1,000-line assembly routine into just 47 lines of Fortran .

Early Development

Following the release of FORTRAN I, IBM introduced FORTRAN II in 1958, which significantly enhanced support for larger programs through features like separate compilation of subroutines, linking of relocatable binary modules, and overlay structures to manage efficiently. These additions allowed programmers to modularize , compile subroutines independently while retaining information, and combine FORTRAN and assembly components via a binary subroutine loader, addressing the limitations of monolithic compilation in earlier versions. FORTRAN III, also developed in 1958 and released on a limited basis to approximately 20 installations (primarily sites), extended these capabilities by incorporating support for complex data types and basic operations, including enhanced I/O with alphanumeric handling via a new FORMAT code "A" for mixed symbolic and FORTRAN statements. However, its proved overly complex due to heavy reliance on machine-specific features of the , leading to a short lifespan and minimal adoption before development shifted focus. By 1961-1962, FORTRAN IV emerged as a more portable , expanding compatibility across diverse machines and introducing expressions through the logical IF statement, alongside improved handling and diagnostics to aid program reliability. This version also added debugging tools, such as better trace facilities, and expanded library functions available on tape (e.g., SQRTF for square roots), facilitating broader use in scientific . Key events included rapid adoption by vendors like (for the Solid-State 80) and CDC (for the 1604) starting in 1961, which helped propagate the language beyond IBM systems. Throughout this period, developers faced challenges in balancing portability with machine-specific optimizations, particularly as hardware transitioned from vacuum tube-based systems like the to transistorized architectures such as the , which demanded adjustments for differing word lengths, memory constraints, and I/O mechanisms. These evolutions from FORTRAN I's fixed layout laid the groundwork for more robust programming practices.

Standardization

The formal standardization of Fortran commenced in the mid-1960s amid growing concerns over inconsistencies across vendor implementations of FORTRAN IV, which featured varying interpretations of syntax and semantics. The American Standards Association (ASA), predecessor to the American National Standards Institute (ANSI), established the X3J3 committee to address these ambiguities and create a unified specification. This work resulted in the first official standard, FORTRAN 66 (ANSI X3.9-1966), published on March 7, 1966, which defined a core language for enhanced portability by stripping away many machine-dependent vendor extensions while retaining essential elements like program units (main, SUBROUTINE, FUNCTION, BLOCK DATA), data types (INTEGER, REAL, DOUBLE PRECISION, COMPLEX, LOGICAL), and statements for control flow, arrays, and I/O. FORTRAN 66 marked the first programming language to achieve formal standardization, earning international recognition through adoption by the International Organization for Standardization (ISO) shortly thereafter. By focusing on a minimal, consistent subset derived from FORTRAN IV, the standard promoted interoperability across diverse computing environments, though it drew criticism for its austerity, such as the absence of advanced features like formatted I/O enhancements present in some proprietary dialects. The X3J3 committee's efforts ensured that compilers adhering to this specification could produce portable code, significantly reducing the fragmentation that had plagued earlier Fortran variants. As computational needs evolved, the X3J3 committee initiated revisions in the early 1970s to incorporate constructs without sacrificing compatibility. This culminated in Fortran 77 (ANSI X3.9-1978), approved in April 1978 and also adopted by ISO, which extended the language with features including the block IF statement for improved , the CHARACTER data type for handling, parameterized DO loops, and direct-access I/O for efficient file operations. Debates within the committee highlighted tensions between advocates for fuller paradigms—such as eliminating GOTO statements—and proponents of to support the vast existing codebase, ultimately favoring a conservative approach that made Fortran 77 a superset of FORTRAN 66. Fortran 77 rapidly achieved dominance as the de facto global standard for scientific computing, with widespread implementation in compilers by major vendors and integration into educational curricula and industrial workflows through the . Its fostered reliability in numerical applications, enabling consistent performance across platforms and solidifying Fortran's role in until subsequent revisions.

Fortran 90 and 95

Fortran 90, formally known as ISO/IEC 1539:1991, represented a major revision of the language, developed by the ANSI X3J3 subcommittee (now INCITS J3) in collaboration with the international ISO/IEC JTC1/SC22/WG5 during the . This effort aimed to modernize Fortran by incorporating elements, such as modules for data encapsulation and improved array handling, while ensuring full with Fortran 77 to preserve existing codebases in scientific and engineering applications. The standard was published in 1991 after extensive deliberation to balance innovation with reliability, addressing limitations in earlier versions like fixed-form source code and static memory allocation. Key innovations in Fortran 90 included free-form source code, which allowed statements to span multiple lines without column restrictions, enhancing readability and reducing errors from punched-card era constraints. Modules provided a mechanism for organizing code into reusable units, encapsulating data types, variables, and procedures to promote modularity; for example, a module might define a type and associated operations accessible via USE statements in other programs. Dynamic memory management was introduced through the ALLOCATE and DEALLOCATE statements, enabling runtime allocation of arrays whose sizes were determined during execution, such as ALLOCATE(A(10)) for a one-dimensional array. Recursive procedures were permitted, allowing functions to call themselves, which facilitated more elegant solutions to problems like tree traversals. To streamline the language, several outdated features from Fortran 77 were designated obsolescent, including Hollerith constants for character data and the EQUIVALENCE statement for overlaying storage, signaling their potential removal in future standards. Fortran 95, defined by ISO/IEC 1539-1:1997, built on Fortran 90 with minor refinements and was published in 1997 as a technical corrigendum and extension, maintaining compatibility while addressing practical needs in high-performance computing. Notable additions included the FORALL construct for concurrent array assignments without dependencies, improving expressiveness for vectorized operations, as in FORALL (I=1:N) A(I) = B(I) + C(I). PURE procedures were introduced to denote functions without side effects, enabling compiler optimizations and safer use in parallel contexts. Conditional compilation via directives in ISO/IEC 1539-3:1997 allowed source code variants for different platforms, such as #ifdef blocks for architecture-specific code. Minor enhancements supported varying-length character strings through adjustable bounds. This revision also deleted obsolescent features from Fortran 90, such as Hollerith constants and EQUIVALENCE, to simplify the language core. The introduction of these features in Fortran 90 and 95 marked a pivotal shift, revitalizing the language for modern scientific computing by supporting larger, more maintainable codebases and leveraging emerging hardware capabilities like vector processors. This overhaul facilitated Fortran's continued dominance in numerical simulations and , with widespread adoption in academic and national laboratory environments.

Modern Revisions

The modern revisions of Fortran, beginning with the 2003 standard, have introduced advanced language capabilities to address evolving demands in high-performance computing, object-oriented design, and interoperability with other languages. These updates build on the foundational modernizations of Fortran 90 and 95 by incorporating features for parallelism, safety, and integration with contemporary software ecosystems. Published as ISO/IEC 1539-1:2004, Fortran 2003 marked a significant expansion, adding support for object-oriented programming through classes, inheritance, and polymorphism via type-bound procedures and dynamic dispatch. It also introduced interoperability with C via the ISO_C_BINDING module, enabling seamless calling of C functions and data sharing, which facilitates integration with libraries written in other languages. Additionally, parameterized derived types were added, allowing generic programming by parameterizing type definitions at compile time. Fortran 2008, formalized in ISO/IEC 1539-1:2010, further enhanced modularity and performance for large-scale applications. A key addition was submodules, which extend modules by providing a hierarchical structure for private implementation details without exposing them to users, improving code organization and encapsulation. Parallel I/O capabilities were introduced through enhancements to the OPEN and INQUIRE statements, supporting file operations across multiple processes to optimize handling in distributed environments. The standard also expanded intrinsic functions for mathematical operations, including support and improved bitwise operations, to better serve numerical computations. The Fortran 2018 revision, published as ISO/IEC 1539-1:2018, emphasized concurrency and robustness in response to multi-core architectures and high-performance needs. It expanded the DO CONCURRENT construct from Fortran 2008, adding support for reduction clauses and local initialization to enable more efficient loop-level parallelism without data races. Coarray teams were introduced, allowing dynamic creation and management of groups of images for scalable parallel execution, building on the coarray model for programming. Error handling was improved with the introduction of the STOP statement's support and enhanced ALLOCATE failure options, promoting safer program execution. Fortran 2023, released as ISO/IEC 1539-1:2023, focuses on enhanced expressiveness, safety, and further interoperability to meet modern development practices. It introduces enumerated types (ENUMs) for defining named constants, reducing errors in code that relies on flags. A standardized with directives for conditional compilation and macro-like expansions was added, improving portability across compilers that previously relied on non-standard tools like cpp. C interoperability was extended with features such as improved pointer handling and value types, streamlining mixed-language projects. These changes prioritize performance optimizations, like longer source lines and automatic reallocation for character variables, while addressing security concerns through obsolescence of vulnerable features. The evolution of Fortran's standardization process reflects a shift toward greater international . Originally managed by the U.S.-based INCITS J3 (formerly X3J3), development now involves ISO/IEC JTC1/SC22/WG5, which coordinates input from national bodies worldwide to ensure global applicability. This structure has enabled responses to demands from and multi-core systems, with features like coarrays and teams directly addressing scalability in parallel environments. As of 2025, work is underway on the next revision, tentatively Fortran 2025, with ongoing meetings and work item lists developed by WG5.

Language Features

Syntax and Layout

Fortran's syntax and layout have evolved significantly since its inception, transitioning from rigid, column-based formatting suited to punched-card input to more flexible structures that accommodate modern text editors and development practices. The language defines two primary source forms: fixed form, which was the sole format in early standards like Fortran 77, and free form, introduced in Fortran 90 to enhance readability and portability. These forms govern how lines are structured, including positioning of statements, comments, and continuations, while maintaining compatibility across implementations. In fixed form, source code adheres to a strict 72-column layout derived from 80-column punched cards, where positions 1 through 5 are reserved for optional statement labels (numeric identifiers for branching), position 6 indicates line continuation with any non-blank character (often '0' through '5'), and positions 7 through 72 contain the actual code. Positions 73 through 80, if present, are ignored as optional sequence numbers. Comments in fixed form begin with 'C', 'c', '*', or '!' in column 1, extending to the end of the line, and statements must start in column 7 or later unless labeled. Continuation lines are limited to a maximum of 19 in practice for many compilers, though the standard permits up to 255, and blank characters in column 6 signal the start of a new statement. This format, while obsolescent since Fortran 95, remains supported for legacy code portability. Free form, the default since Fortran 90, removes column restrictions, allowing code to begin anywhere on a line up to a maximum of 132 characters (extendable by processors). Statements can span multiple lines via an ampersand (&) as the last non-blank character before any comment or end-of-line, with an optional leading & on the continuation line for clarity; up to 255 such continuations are allowed. Comments start with '!' anywhere on the line and extend to the end, enabling inline annotations without disrupting layout. Semicolons may separate multiple statements on a single line in free form, though they are optional at the end, and block constructs like programs or subroutines require explicit END statements to terminate. Fortran keywords and identifiers are case-insensitive throughout both forms, treating variants like "PROGRAM" and "program" as identical, which simplifies code but requires careful naming to avoid unintended matches in mixed-case environments. This feature, consistent since the language's early days, applies to all lexical tokens except character literals. The evolution from fixed to free form reflects Fortran's adaptation to computing advancements, moving away from the punched-card era's constraints—where early programs like those on systems demanded precise columnar alignment—to editor-friendly formats that support indentation for readability without altering semantics. Fixed form has been obsolescent since Fortran 95 but remains supported for in modern standards, allowing mixed use via directives or file extensions (e.g., .f for fixed, .f90 for free). For example, a simple assignment in fixed form might appear as:

X = 1.0

X = 1.0

while in free form, it could be indented and annotated:

x = 1.0 ! Initialize variable

x = 1.0 ! Initialize variable

Both execute identically due to case insensitivity and layout flexibility in the latter.

Data Types and Declarations

Fortran supports five intrinsic data types: integer for whole numbers, real for floating-point values, complex for numbers with real and imaginary parts, logical for boolean values, and character for strings. These types can be specified with a kind parameter to control storage size and precision, which is processor-dependent but often follows common conventions such as INTEGER(KIND=4) for 32-bit integers or REAL(KIND=8) for double-precision floating-point with approximately 15 decimal digits of precision. For example, the declaration integer(kind=4) :: i declares a 32-bit signed integer variable, while real(kind=8) :: x = 3.141592653589793_8 declares a double-precision real. Variables in Fortran must be declared explicitly when using the IMPLICIT NONE statement, which disables the default implicit typing rules (where variables starting with I-N are integers and others reals) and is recommended for all modern code to enhance and prevent errors. Declarations follow the syntax type-specifier :: variable-list, such as integer :: count, index or character(len=20) :: name. Constants are defined using the PARAMETER attribute, ensuring their values cannot be modified at runtime; for instance, real, parameter :: pi = 3.1415926535 creates an unchangeable single-precision constant. Introduced in Fortran 90, derived types allow users to create composite data structures by combining intrinsic or other derived types as components, enabling encapsulation similar to or structs in other languages. A derived type is declared using the TYPE construct, such as:

type :: point real :: x, y end type point

type :: point real :: x, y end type point

This defines a type with two real components, which can then be instantiated as type(point) :: origin and accessed via origin%x = 0.0. Components support initialization, either at declaration (e.g., real :: z = 0.0 within the type) or via structure constructors like type(point)(1.0, 2.0). For dynamic memory management, Fortran provides the allocatable and pointer attributes, both introduced in Fortran 90 to support flexible storage allocation without fixed sizes at . The allocatable attribute applies to entities or components, allowing runtime allocation via the ALLOCATE statement; for example, real, allocatable :: array(:) declares a one-dimensional allocatable array, which can be sized with allocate(array(100)). Allocatable entities are automatically deallocated when out of scope, promoting safer memory handling compared to static arrays. The pointer attribute designates variables that reference (or "point to") other data objects, useful for linked structures or ; declaration uses type, pointer :: var, and association occurs via => in statements like allocate(target); var => target. Pointers must target entities with the TARGET attribute if needed, and they support dynamic polymorphism but require explicit nullification to avoid dangling references. Fortran 2003 extended derived types with object-oriented features, including type-bound procedures that bind specific subroutines or functions directly to a type, facilitating encapsulation and polymorphism. These are declared after the CONTAINS statement within a type definition, such as:

type :: vector real :: components(3) contains procedure :: norm => vector_norm end type vector

type :: vector real :: components(3) contains procedure :: norm => vector_norm end type vector

This allows invoking the bound procedure as vec%norm(), where vector_norm is an external subroutine, integrating behavior with data in an OOP manner without global procedure calls. Type-bound procedures support generics and finalizers for cleanup, enhancing modularity in complex simulations.

Control Structures

Fortran's control structures have evolved significantly since the language's , transitioning from unstructured branching mechanisms to modern, structured constructs that promote and . The original Fortran (1957) featured the arithmetic IF statement, which conditionally transferred control to one of three labels based on whether an arithmetic expression evaluated to negative, zero, or positive, reflecting the era's reliance on unconditional statements for flow control. This approach, while efficient for early compilers, led to "" issues, prompting later revisions to introduce more disciplined alternatives. The Fortran 77 standard marked a pivotal shift toward by introducing the block IF construct, which allowed multi-line conditional blocks with ELSE and ELSE IF clauses, replacing much of the need for arithmetic IF (now deprecated but still supported for legacy code). The block IF syntax is:

IF (logical-expression) THEN block [ELSE IF (logical-expression) THEN block ]... [ELSE block ] END IF

IF (logical-expression) THEN block [ELSE IF (logical-expression) THEN block ]... [ELSE block ] END IF

This enables chains of ELSE IF for handling multiple conditions, evaluating the logical expression (using relational operators like ==, /=, <, >, <=, >=) sequentially until a true branch is found or the ELSE executes. Looping constructs began with the indexed DO loop in early Fortran, specifying fixed iteration bounds and an optional step, as in DO i = 1, 10 or DO i = 1, 10, 2 for even increments. Fortran 77 formalized this as a block construct (END DO), preventing unstructured entry or exit except via transfers like (discouraged). The DO WHILE loop, added in Fortran 90, supports condition-based iteration without a predefined counter: DO WHILE (logical-expression) ... END DO, repeating until the expression is false. Fortran 2008 introduced DO CONCURRENT for expressing independent iterations amenable to parallel execution, though its core sequential semantics align with traditional loops; parallel aspects are detailed elsewhere. The SELECT CASE construct, introduced in Fortran 90, provides efficient multi-way branching on a scalar expression, akin to a , avoiding lengthy IF-ELSE IF chains for discrete values. Its syntax is:

SELECT CASE (expression) CASE (case-value-list) block [CASE DEFAULT block ] END SELECT

SELECT CASE (expression) CASE (case-value-list) block [CASE DEFAULT block ] END SELECT

Case values can be constants, ranges (e.g., 1:5), or defaults, with the first matching case executing; the expression must be , logical, character, or compatible. For finer loop control, Fortran 90 added EXIT and CYCLE statements, applicable to any enclosing DO construct (including named ones for nesting). EXIT terminates the loop immediately, transferring control to the statement after END DO, as in IF (condition) EXIT to break early. CYCLE skips the remaining statements in the current iteration, advancing to the next, useful for filtering, e.g., IF (i > 5) CYCLE to ignore later values. These enhancements, building on Fortran 77's foundations, ensure robust, structured flow control across revisions.

Procedures and Modules

In Fortran, procedures provide a mechanism for modularizing code through subroutines and functions. Subroutines are invoked using the CALL statement and perform actions without returning a value directly, while functions are invoked within expressions or assignments and return a computed value via the RESULT clause or the function name. This distinction allows subroutines to handle side effects like or state modifications, whereas functions emphasize pure computations. Dummy arguments in procedures specify the interface for actual arguments passed from the caller. By default, Fortran passes arguments by reference, meaning the procedure receives a pointer to the actual argument's storage, allowing modifications to propagate back to the caller. The attribute, introduced in Fortran 90, clarifies the usage intent of dummy arguments to aid optimization and error detection: INTENT(IN) indicates input-only arguments that cannot be modified; INTENT(OUT) specifies output arguments whose initial values are undefined and must be defined before use; INTENT(INOUT) allows both input and output, with the argument modifiable and its initial value preserved. For example, in a subroutine printing a matrix:

fortran

subroutine print_matrix(n, m, A) [integer](/page/Integer), intent(in) :: n, m real, intent(in) :: A(n, m) ! Printing logic here end subroutine print_matrix

subroutine print_matrix(n, m, A) [integer](/page/Integer), intent(in) :: n, m real, intent(in) :: A(n, m) ! Printing logic here end subroutine print_matrix

Here, n and m are inputs, and A is read-only. Fortran 2003 introduced the VALUE attribute for scalar dummy arguments in procedures with explicit interfaces and the BIND(C) attribute, enabling pass-by-value semantics where a local copy is made, isolating changes from the caller—primarily for C interoperability. Modules, added in Fortran 90, encapsulate data and procedures to promote reusability and management. A module declares entities with or PRIVATE access specifiers: entities are accessible outside the module, while PRIVATE ones are hidden, enforcing encapsulation. The CONTAINS statement within a module defines internal procedures, and the USE statement imports module entities into a program unit, optionally with ONLY to limit imports. For instance:

fortran

module math_utils implicit none private public :: vector_norm contains function vector_norm(n, vec) result(norm) integer, intent(in) :: n real, intent(in) :: vec(n) real :: norm norm = sqrt(sum(vec**2)) end function vector_norm end module math_utils

module math_utils implicit none private public :: vector_norm contains function vector_norm(n, vec) result(norm) integer, intent(in) :: n real, intent(in) :: vec(n) real :: norm norm = sqrt(sum(vec**2)) end function vector_norm end module math_utils

This module exports only vector_norm, keeping internal details private. USE math_utils; then invokes vector_norm(5, v) in the main program. Recursion became supported in Fortran 90 via the RECURSIVE prefix on SUBROUTINE or FUNCTION statements, allowing a procedure to invoke itself directly or indirectly, with local variables allocated on the stack per call. Prior standards prohibited recursion to simplify storage management. Procedure interfaces, also from Fortran 90, enable overloading through generic INTERFACE blocks, where a single name resolves to specific procedures based on argument types, ranks, or kinds—distinguishing calls without ambiguity. For example, a generic norm could overload for scalars, vectors, and matrices via an INTERFACE norm with multiple specific bindings. Fortran 2008 extended modules with submodules, which nest under a parent module or another submodule to organize implementations separately from interfaces. A submodule provides definitions for procedures declared in its ancestor, accessing ancestor's entities via host association without USE, and supports descendant submodules for hierarchical structures. This facilitates large-scale projects by reducing recompilation dependencies and isolating implementation details, as SAVE is implicit for entities. For example, a parent module declares a procedure interface, while a submodule supplies its body, enhancing without exposing internals.

Arrays and Parallelism

Fortran arrays have evolved significantly since the language's inception, transitioning from static, fixed-size declarations in early standards like Fortran 77 to dynamic allocatable arrays introduced in Fortran 90, which allow runtime dimensioning via the ALLOCATABLE attribute. This progression culminated in advanced parallel features in later revisions, such as assumed-rank arrays in Fortran 2018, enabling flexible handling of arrays of varying ranks without explicit rank specification. These developments reflect Fortran's adaptation to scientific computing needs, emphasizing efficiency in memory usage and parallelism for high-performance applications. Arrays in Fortran are declared using a type specifier followed by dimensions in parentheses, as in REAL :: A(10) for a one-dimensional array of ten real numbers, with indices starting at 1 by default and support for custom lower bounds like REAL :: B(-5:5). Whole-array operations permit concise element-wise computations without loops, such as A = B + C or assignment of constants like A = 0.0, leveraging the language's array-centric design for vectorizable code. further enhances manipulation, allowing sections like A(1:5) for the first five elements, A(1:10:2) for every other element, or multidimensional slices like Matrix(:, 1) for an entire column, all without data copying in many cases. Intrinsic functions underpin efficient and by compilers. The SUM function reduces an array to its scalar sum or along a , as in total = SUM(A), promoting rank reduction for multidimensional arrays. Similarly, MATMUL handles for compatible -1 or -2 arrays, treating vectors appropriately as rows or columns and supporting logical operations with .AND., which compilers optimize for SIMD instructions. Parallelism at the array level began with the FORALL construct in Fortran 90, a non-iterative generalization of masked array assignments that specifies independent element operations executable in any order, facilitating compiler-directed parallelism without explicit threading. This was introduced alongside the DO CONCURRENT construct in Fortran 2008, which structures loops for potential concurrent iteration execution across threads or devices, assuming no inter-iteration dependencies to enable safe parallelization, as in DO CONCURRENT (i=1:100) A(i) = B(i) + C(i). Fortran 2008 introduced coarrays for distributed-memory parallelism in a single-program multiple-data (SPMD) model, where arrays are declared with a codimension section like REAL :: X(100)[*] to replicate across images (processing units). Remote data access uses square-bracket notation, such as X = Y[2] to copy from image 2, with each image maintaining private memory copies. Synchronization ensures consistency via constructs like SYNC ALL for global barriers or SYNC IMAGES(img) for specific images, supporting scalable parallel algorithms with minimal code changes.

Applications

Scientific Computing

Fortran has been foundational in since its inception, enabling the implementation of complex mathematical models for atmospheric simulations. Developed in the mid-1950s to address the computational demands of scientific calculations, Fortran facilitated the first successful numerical forecasts by handling iterative solutions to partial differential equations that describe weather dynamics. Today, major operational models, such as those used by the (NOAA), continue to rely on Fortran for core numerical routines due to its proven reliability in processing vast meteorological datasets. In quantum chemistry, Fortran powers key software packages like Gaussian, which performs high-accuracy ab initio computations to predict molecular geometries, energies, and spectra. These tools leverage Fortran's robust support for intricate algorithms involving electron correlations and basis set expansions, essential for advancing chemical research. Similarly, early adoption in physics at involved Fortran-based codes for simulating nuclear processes and particle transport, where the language's efficiency supported critical national security applications during the era. A 2023 Los Alamos report highlights that many such legacy physics codes remain in active use, underscoring Fortran's enduring role in high-stakes simulations. Fortran's integration with libraries like BLAS (Basic Linear Algebra Subprograms) and (Linear Algebra Package) enhances its utility in scientific computing by providing optimized Fortran routines for vector and matrix operations, which are ubiquitous in and modeling. These libraries enable efficient solving of linear systems and eigenvalue problems, forming the backbone of algorithms in fields ranging from physics to . In biological simulations, for example, Fortran programs such as BIOTURB model bioturbation effects on distributions, while others simulate protein dynamics and genetic evolution, demonstrating the language's versatility in handling stochastic processes and large-scale biomolecular data. A primary advantage of Fortran in scientific contexts is its precise control over numerical representations, supporting data types from single to quadruple precision to mitigate errors in extended computations involving floating-point operations. Complementing this, Fortran's native I/O facilities excel at managing large datasets through unformatted binary transfers, which minimize overhead and support direct access for terabyte-scale simulation outputs. As of 2025, Fortran dominates open-source scientific software ecosystems, with its popularity surging in numerical and data-intensive applications and ongoing adoption in peer-reviewed research tools.

Engineering and Simulation

Fortran has been instrumental in engineering simulations since the mid-20th century, particularly in finite element analysis (FEA) for structural integrity and (CFD) for aerodynamic and hydrodynamic modeling. Its robust numerical capabilities enable engineers to solve complex partial differential equations that govern physical phenomena in materials under stress or fluids in motion. Key software packages developed in Fortran exemplify this role; for instance, , originally created by in the late 1960s, remains a cornerstone for multidisciplinary , performing static, dynamic, and thermal simulations on components. In CFD, Fortran-based solvers like NASA's FUN3D and CFL3D facilitate high-fidelity simulations of viscous flows around aircraft and vehicles, leveraging the language's efficiency in handling large-scale matrix operations. Fortran's built-in support for complex data types is particularly valuable in simulations, where it models impedance and representations in circuit analysis and computations. For example, complex numbers allow direct manipulation of AC signals without decomposing into real and imaginary components manually, streamlining simulations of power systems and antennas. Additionally, Fortran's double precision arithmetic, which provides up to 15-16 decimal digits of accuracy, is essential for maintaining precision in iterative solvers common to engineering models, reducing rounding errors in stress-strain calculations or . In industry applications, Fortran powers critical simulations in , where continues to rely on legacy Fortran codes for mission-critical analyses like and re-entry dynamics. In the automotive sector, tools such as PAM-CRASH utilize Fortran for explicit finite element crash simulations, predicting vehicle deformation and occupant safety during high-speed impacts. These examples highlight Fortran's enduring impact on design validation, enabling virtual prototyping that minimizes physical testing costs. The evolution of Fortran in traces back to the , when it supported batch-processed simulations on mainframes for early FEA and CFD prototypes, often integrated with nascent systems. By the 1970s and 1980s, advancements in Fortran standards allowed seamless incorporation into (CAD) environments, facilitating interactive modeling of complex geometries. As of , Fortran persists in through legacy systems wrapped in modern interfaces, such as Python or C++ bindings, ensuring compatibility with contemporary workflows while preserving validated simulation accuracy.

High-Performance Computing

Fortran has maintained a prominent role in high-performance computing (HPC), particularly on supercomputers listed in the TOP500 rankings, where it powers many scientific simulations due to its optimized handling of numerical computations and array operations. For instance, the Frontier supercomputer at Oak Ridge National Laboratory, ranked second on the TOP500 list as of June 2025 with a performance of 1.353 exaFLOPS, extensively utilizes Fortran-based codes for applications such as climate modeling through the Energy Exascale Earth System Model (E3SM). In E3SM, Fortran components enable high-resolution simulations of atmospheric and oceanic processes, achieving record performance metrics like 1.26 simulated years per day on Frontier's cloud-resolving configurations. This dominance stems from Fortran's legacy in legacy codes and its efficiency in vectorized operations, making it a staple for workloads that constitute a significant portion of supercomputer runtime in fields like earth system modeling. Fortran integrates seamlessly with parallel processing frameworks essential for distributed and shared-memory computing in HPC environments. The (MPI) and are widely adopted for Fortran applications, enabling scalable distributed-memory parallelism across clusters and node-level thread-based acceleration, respectively; hybrid MPI-OpenMP approaches have demonstrated performance gains in exascale prototypes by combining inter-node communication with intra-node vectorization. As a native alternative, Fortran's coarray feature, introduced in the 2008 standard, supports programming without external libraries, offering simpler syntax for parallel data sharing in multi-node setups. These integrations allow Fortran codes to exploit the heterogeneous architectures of modern supercomputers effectively. Compilers such as those from and provide advanced optimizations tailored for HPC, particularly in , which enhances performance on vector processors and SIMD units by transforming scalar loops into vector instructions. For example, Cray's vectorization options, including the -O vector n flag, can yield significant speedups in array-heavy computations with minimal changes, while 's Fortran uses directives like !DIR$ IVDEP to guide aggressive vectorization, achieving up to several-fold improvements in benchmarks on multi-core systems. Studies comparing these compilers on HPC mini-applications have shown and achieving high vectorization rates, often exceeding 80% efficiency on relevant workloads. In recent exascale developments, Fortran continues to adapt for systems like Aurora at , which entered production in early 2025 using Max and GPU Max processors and is ranked third on the list as of November 2025 with 1.012 exaFLOPS; preparation efforts emphasize Fortran compatibility via offloading for GPU acceleration. Tools like extend Fortran's parallelism to exascale GPUs, enabling legacy codes to run efficiently on heterogeneous nodes without full rewrites. However, challenges persist in migrating serial or CPU-centric Fortran codes to heterogeneous GPU systems, including performance portability across architectures and the need for directives-based offloading, which can introduce overheads and require substantial refactoring to maintain at exascale.

Implementations and Portability

Compilers and Tools

The development of Fortran compilers began with the pioneering efforts at , where the first Fortran was released in 1957 for the computer, marking the advent of the first with an . This initial implementation, led by , translated mathematical formulas into efficient , significantly advancing scientific computing. Subsequent compilers, such as Fortran II in 1958, introduced features like subroutines and function subprograms, evolving the language while maintaining backward compatibility. Among contemporary Fortran compilers, gfortran, the GNU Fortran frontend integrated into the GNU Compiler Collection (GCC), stands as a free, open-source option supporting Fortran standards up to 2018 and beyond, with the latest GCC 15.2 release in August 2025 providing robust optimizations for general-purpose use. The Intel Fortran Compiler, now primarily the LLVM-based ifx in the oneAPI 2025 release, is optimized for x86 architectures and Intel hardware, offering advanced for Intel processors while discontinuing the legacy ifort edition. For (HPC), the HPE Compiling Environment (CCE) Fortran compiler targets supercomputing systems, supporting most features of the Fortran 2023 standard except for the .NIL. constant and leveraging / backends for vector processors and accelerators. Additionally, Flang, an open-source -based Fortran compiler initiated around 2018, has matured by 2025 into a production-ready tool, renamed from flang-new and integrated into the ecosystem for modular, extensible compilation. , another open-source LLVM-based Fortran compiler, is a modern, interactive tool currently in alpha quality (stable release 0.58.0 as of December 2025), supporting interactive development and under active maintenance. Supporting these compilers are essential development tools, including debuggers like (GDB), which integrates seamlessly with gfortran for breakpoint setting and variable inspection on systems. For HPC environments, specialized debuggers such as TotalView and Arm DDT provide multi-process debugging capabilities for parallel Fortran applications. Profilers, including VTune Profiler bundled with oneAPI, enable performance analysis by identifying bottlenecks in memory access and computation loops. Integrated development environments (IDEs) like Photran, an Eclipse-based plugin, offer , refactoring, and build integration specifically for Fortran, supporting cross-platform workflows. Modern Fortran compilers in 2025 incorporate advanced features such as and vectorization to exploit multicore processors and SIMD instructions without manual intervention. For instance, ifx enables auto-vectorization at optimization level -O2 and higher, transforming scalar loops into vectorized code for improved throughput on enabled hardware. Similarly, gfortran supports loop parallelization via the -ftree-parallelize-loops flag, distributing iterations across threads, while HPE CCE applies directive-based auto-parallelization for DO CONCURRENT constructs in HPC workloads. These features, refined through iterative releases, allow compilers to achieve near-peak on diverse architectures by analyzing dependencies and loop structures. Fortran compilers exhibit broad cross-platform availability, running on operating systems from Windows and to macOS, and scaling to supercomputers via distributions like GCC and . gfortran, for example, compiles natively across these platforms through GCC binaries, ensuring portability for scientific applications. oneAPI tools extend to Windows and , while Flang's foundation facilitates builds on embedded systems to large clusters. HPE environments, though HPC-centric, support x86 and architectures for deployment on diverse supercomputing infrastructures.

Standards Compliance

Fortran standards compliance has evolved significantly since the language's inception, ensuring portability across implementations. In the , early Fortran implementations were often loose and vendor-specific, with dialects proliferating due to minimal ; the first ANSI standard, Fortran 66, was published in to address this but permitted extensions that hindered full . By the and , the Fortran 77 standard (ANSI X3.9-1978) introduced stricter conformance requirements, though was gradual as compilers updated slowly, leading to a more reliable but still varied ecosystem. The marked a pivotal shift with Fortran 90 (ISO/IEC 1539:1991), which mandated compilers to diagnose non-standard syntax and errors, enforcing rigorous testing and reducing dialectal deviations for enhanced portability. Validation of standard conformance relies on test suites designed to verify adherence to ISO/IEC specifications. Historically, the National Institute of Standards and Technology (NIST) developed comprehensive test programs in the 1970s, such as the NBS FORTRAN Test Programs, to check compliance with Fortran 66 and early revisions by exercising language forms and interpretations. These suites, written in standard Fortran, remain influential for legacy validation, though modern efforts have shifted toward community-driven and vendor-specific tools; for instance, the J3 Fortran committee has proposed a thorough testsuite covering positive and negative cases for all standard features and constraints since 2019, aiding ongoing verification. Frameworks like the Berkeley Lab Fortran Compiler Test Suite further support testing by providing a modular set of cases to evaluate behavior against current standards. Compliance levels vary between full implementation and subsets, allowing developers to target core features for broader portability. For example, the Fortran 2008 standard (ISO/IEC 1539-1:2010) defines a baseline "core" subset excluding advanced parallel features like coarrays, which some compilers, such as early implementations, supported partially for while deferring full adoption. Major compilers report feature-by-feature support rather than binary full/partial status; XL Fortran, starting with version 14.1, achieved progressive compliance with Fortran 2008 elements like submodules and polymorphic entities, reaching near-full coverage by later releases. This tiered approach ensures essential syntax and semantics are portable, with subsets like the Fortran 2008 core enabling compatibility across diverse hardware without requiring every optional extension. Vendor-specific extensions often contrast with standard purity, introducing flags that enhance performance or compatibility but risk portability. For instance, the GNU Fortran compiler's -fdefault-real-8 option defaults real literals to double precision (kind 8), a non-standard mimicking older dialects for legacy code, while standard-compliant modes enforce single precision unless specified. Similarly, DEC compatibility modes in gfortran enable nonstandard features like abbreviated keywords to emulate historical compilers, but these must be disabled for ISO conformance to avoid vendor lock-in. compilers include extensions for vector programming and shared extensions with other vendors, which are flagged during compilation to distinguish them from pure standard features, promoting awareness of potential issues. As of 2025, Fortran 2018 (ISO/IEC 1539-1:2018) enjoys near-universal support among major compilers, facilitating widespread portability for modern applications. The Fortran Compiler (ifx) in its 2025 release fully implements all Fortran 2018 features, including enhanced IEEE arithmetic and assume directives. (gfortran) provides comprehensive Fortran 2018 coverage, with parallel features via OpenCoarrays integration, while Flang achieves full syntactic and semantic support under active development. HPC SDK and NAG compilers also offer significant Fortran 2018 compliance, including atomic operations and teams. For the emerging Fortran 2023 standard (ISO/IEC 1539-1:2023), support remains partial; ifx includes select features like updated SYSTEM_CLOCK semantics and BOZ literal handling in array constructors, HPE supports most elements except the .NIL. constant, and Flang implements a subset such as extended IEEE functions but lacks coarrays and enumerations. This progressive adoption underscores ongoing efforts to balance innovation with .

Interoperability

Fortran's interoperability features enable seamless integration with other programming languages, particularly C, allowing Fortran code to be called from or to call C routines in mixed-language environments. Prior to the Fortran 2003 standard, interoperability relied on compiler-specific conventions and manual adjustments, such as explicit pointer manipulations and name mangling to align Fortran's calling mechanisms with C's, which often led to portability issues across implementations. The introduction of standardized mechanisms in Fortran 2003 marked a significant evolution, providing portable bindings that eliminated much of the vendor-specific code required in the 1990s. The core of Fortran's C interoperability is the ISO C Binding, introduced in Fortran 2003 via the intrinsic module iso_c_binding. This module defines named constants for C-compatible kind parameters (e.g., C_INT for C's int type, C_FLOAT for float), derived types like C_PTR for opaque C pointers and C_FUNPTR for function pointers, and procedures such as C_LOC to obtain the address of a Fortran object and C_F_POINTER to associate a C pointer with a Fortran pointer. The BIND(C) attribute is applied to procedures, derived types, and global variables to declare them interoperable with C, ensuring they adhere to C's naming and linkage rules without Fortran's default name decoration. For procedures, BIND(C) requires an explicit interface and supports the VALUE attribute for scalar arguments to pass them by value, aligning with C's convention, while arrays and other arguments default to pass-by-reference. Derived types marked BIND(C) must consist of interoperable components, excluding pointers or allocatables, to map directly to C structs. Key differences in calling conventions necessitate adjustments for reliable interoperability. Fortran passes arguments by reference using descriptors or addresses, whereas C passes scalars by value and arrays as pointers to their first element. To reconcile this, Fortran developers use the VALUE attribute in BIND(C) procedures for by-value passing of simple scalars, preventing unintended modifications in C code. Additionally, Fortran arrays are column-major and 1-based, contrasting C's row-major, 0-based indexing; interoperability mappings reverse dimensions and adjust indices accordingly, often requiring explicit transpositions in mixed code. The iso_fortran_env module complements this by providing environment constants like ATOMIC_INT_KIND, aiding in type matching across languages, though it is not exclusively for C binding. Practical use cases abound in scientific computing, where Fortran's numerical strengths are leveraged alongside other languages. For instance, the F2PY tool, part of , generates Python extension modules from Fortran source, enabling Python scripts to call Fortran subroutines for performance-critical tasks like matrix operations while handling I/O and orchestration in Python. F2PY supports Fortran 77 through modern features, including iso_c_binding interfaces, and automatically manages array passing and COMMON blocks as Python variables. Similarly, calling Fortran from uses extern "C" wrappers around BIND(C) procedures, allowing to invoke Fortran kernels for simulations, as seen in high-performance libraries where Fortran handles compute-intensive loops. Recent advancements, aligned with the Fortran 2023 standard, enhance in accelerator environments through improved support for directive-based GPU offloading via OpenACC. OpenACC directives, such as !$acc kernels or !$acc [parallel](/page/The_Parallel), allow Fortran code to offload computations to GPUs portably across vendors, with compilers like NVIDIA's NVFORTRAN providing seamless integration with C/C++ host code. These extensions build on Fortran 2003 bindings by enabling mixed-language GPU workflows, where C++ manages data transfer and Fortran performs kernels, improving in heterogeneous systems without altering core mechanisms.

Variants and Extensions

Obsolete Variants

Before the establishment of the Fortran 66 standard, numerous vendor-specific extensions and dialects proliferated, leading to significant incompatibilities across systems. These obsolete variants often introduced proprietary features to optimize for particular hardware or user needs, but their lack of adherence to a common specification rendered them non-portable. As standardization efforts gained traction through the (ANSI), these dialects were gradually supplanted, with most fading by the late 1970s or early 1980s. One prominent example is WATFOR, developed in 1965 by undergraduate students at the for the 7040 computer. Designed as a student-oriented Fortran IV , it emphasized rapid compilation—achieving compile times under 0.5 seconds for typical programs—through an in-core, load-and-go approach that sacrificed some optimization for speed and simplicity. This made it ideal for educational environments where frequent recompilation was common, but it omitted advanced features like complex arithmetic and certain I/O capabilities found in full Fortran IV. WATFOR was succeeded by WATFIV in 1967, which incorporated additional extensions such as enhanced debugging and elements presented at SHARE conferences, further tailoring it for academic use. However, as standardized Fortran compilers became widely available, WATFOR and WATFIV were phased out by the , though they influenced early by democratizing access to high-level programming. Data General's Fortran 5, introduced in the early 1970s, represented another discontinued dialect optimized for their line, including the Nova, , and later MV systems. Marketed until the early , it extended Fortran IV with vendor-specific enhancements like improved real-time support and business-oriented features, but included quirks such as non-standard division semantics and limited precision handling that deviated from emerging standards. For instance, its I/O routines supported proprietary disk formats incompatible with other systems, and math functions like logarithmic operations sometimes used machine-specific approximations no longer supported in modern compilers. This lack of portability doomed it as users migrated to ANSI-compliant versions, though it played a role in early -based scientific applications. Basic Fortran emerged as a minimal in the late 1960s and 1970s, targeted at resource-constrained microcomputers and small systems like the Intel 8080. It stripped down core Fortran features to essentials—such as basic arithmetic, loops, and simple I/O—excluding complex data types, subroutines, and advanced control structures to fit within limited memory (often under 64 KB). This made it suitable for early embedded and educational programming on devices like the , but its incomplete implementation led to issues like unsupported floating-point operations and non-standard array handling. By the 1980s, as full Fortran subsets aligned with standards like Fortran 77 became feasible on microcomputers, Basic Fortran was rendered obsolete, leaving a legacy in pioneering numerical computing on personal-scale hardware. Vendor extensions, such as those in CDC's Fortran implementations (e.g., FTN for the 6000 series), further exemplified pre-standard diversity. These often added hardware-tuned features like optimized vector arithmetic or graphical output primitives for plotters, but quirks including unique statement numbering and recovery mechanisms caused portability nightmares. The dominance of ANSI standards ultimately marginalized these variants by the , as their non-standard I/O (e.g., direct tape control) and math libraries (e.g., extended precision functions) were deprecated in favor of uniform compliance. Despite their obsolescence, these dialects shaped early Fortran adoption in education and industry, fostering innovation before portability became paramount.

Derived Languages

Several languages and extensions have been derived from Fortran's syntax and semantics to address its limitations in structured programming, array handling, or , often serving specialized domains such as scientific numerics or . Ratfor, developed by in 1975, is a for Fortran 66 that introduces C-like control structures, including multi-statement * blocks, * and for loops, repeat-until constructs, and break statements, while translating the code into equivalent Fortran statements to leverage existing compilers. This allowed programmers to write more readable, modular code without the goto-heavy style typical of early Fortran, though it remained tied to Fortran's underlying model for efficiency in numerical tasks. The F language, introduced in 1996 by Michael Metcalf and John Reid in their , is a strict of Fortran 95 designed for -oriented programming and teaching modern computational concepts, omitting legacy features like computed gotos and equivalence statements to promote safer, more regular code while retaining Fortran's powerful operations and modules. F programs compile directly with any Fortran 95-compliant , emphasizing simplicity for numerical algorithms without sacrificing performance. Fortress, initiated by in 2001 with funding from the High Productivity Computing Systems program, aimed to modernize Fortran for parallel by incorporating mathematical notation, implicit parallelism, and traits for reusable components, positioning itself as a successor language with syntax closer to . Despite prototypes demonstrating multicore efficiency, the project was discontinued in 2012 following Oracle's acquisition of , marking it as a failed effort to replace Fortran in large-scale scientific applications. MATLAB originated in the late 1970s as an interactive matrix laboratory built directly in Fortran by , leveraging libraries like LINPACK and EISPACK for numerical computations, which provided the foundation for its array-centric syntax and domain-specific focus on linear algebra and simulation. Although MATLAB evolved into an independent language with its own interpreter by the 1980s, its core numeric model retains Fortran's influence in handling multidimensional arrays and vectorized operations. Fortran's array model has indirectly shaped modern tools like in Python, which adopts Fortran's column-major (Fortran-order) memory layout for compatibility and efficiency in numerical array manipulations, enabling seamless integration with Fortran-based libraries such as BLAS. Similarly, Julia, developed since 2009, draws on Fortran's emphasis on high-performance array processing to achieve comparable speeds in scientific computing, while adding dynamic typing and for broader applicability. As of 2025, derived Fortran languages remain niche, with legacy extensions like Ratfor and F seeing limited use in educational or historical contexts, while broader influences persist in domain-specific tools rather than active, standalone languages.

Code Examples

Basic Program Structure

A Fortran program is structured as a main program unit that begins with a PROGRAM statement, followed by the executable statements forming the main block, and terminates with an END or END PROGRAM statement. This design allows execution to commence directly at the first executable statement after any specification statements, without requiring an explicit entry point function such as main() in languages like C. The PROGRAM statement optionally names the unit for identification and debugging purposes, while the ending statement ensures proper termination and return to the operating system. In historical Fortran 77, programs adhered to a fixed-form source layout, where statements occupied specific columns (typically 7 through 72), and comments began with a C or * in column 1. A simple "Hello, World!" example in this style demonstrates the core structure:

PROGRAM HELLO PRINT *, 'Hello, World!' END

PROGRAM HELLO PRINT *, 'Hello, World!' END

Here, the PROGRAM statement initiates the unit, the PRINT statement performs output to standard output using list-directed formatting, and END concludes the program. This fixed-form approach enforced rigid formatting to facilitate punched-card input during the era's hardware constraints. Modern Fortran, starting from the Fortran 90 standard, introduced free-form source layout, allowing more flexible indentation and line continuation without column restrictions, along with enhancements like explicit typing via IMPLICIT NONE. An equivalent uses the WRITE statement for output and follows this contemporary structure:

program hello implicit none write(*, *) 'Hello, World!' end program hello

program hello implicit none write(*, *) 'Hello, World!' end program hello

The program keyword (lowercase optional but conventional) starts the unit, implicit none prevents implicit variable declarations to promote safer coding, the write statement directs output similarly to PRINT but with explicit unit and format arguments, and end program hello explicitly names the ending for clarity. This evolution prioritizes readability and portability across compilers while preserving the fundamental program unit model.

Numerical Computation Example

A representative numerical computation in Fortran involves approximating the value of π using the Leibniz infinite series, where π/4 = ∑_{k=1}^∞ [(-1)^{k+1} / (2k - 1)]. This series summation demonstrates Fortran's strengths in handling iterative and operations efficiently. The following Fortran 95+ code snippet computes an approximation by allocating a real to store the series terms, summing them via the intrinsic SUM function, and scaling the result by 4.

fortran

PROGRAM ComputePi IMPLICIT NONE INTEGER :: i, n REAL, ALLOCATABLE :: terms(:) REAL :: pi_approx n = 1000000 ! Number of terms for summation ALLOCATE(terms(n)) DO i = 1, n terms(i) = (-1)**(i + 1) / (2 * i - 1) END DO pi_approx = 4.0 * SUM(terms) PRINT *, 'Approximation of pi:', pi_approx DEALLOCATE(terms) END PROGRAM ComputePi

PROGRAM ComputePi IMPLICIT NONE INTEGER :: i, n REAL, ALLOCATABLE :: terms(:) REAL :: pi_approx n = 1000000 ! Number of terms for summation ALLOCATE(terms(n)) DO i = 1, n terms(i) = (-1)**(i + 1) / (2 * i - 1) END DO pi_approx = 4.0 * SUM(terms) PRINT *, 'Approximation of pi:', pi_approx DEALLOCATE(terms) END PROGRAM ComputePi

In this example, variables are declared explicitly with IMPLICIT NONE to enforce type safety: i and n as integers for loop control and array size, and terms as a allocatable real array for storing the alternating fractional terms. The DO loop iterates over the indices, computing each term using the exponentiation operator (**) and basic arithmetic, which leverages Fortran's optimized handling of floating-point operations. The SUM intrinsic then aggregates the array elements in a vectorized manner, often benefiting from compiler optimizations like those in gfortran or Intel Fortran, which can achieve near-peak performance on modern CPUs for such workloads. Finally, the result is output via a simple PRINT statement, and memory is explicitly deallocated to prevent leaks in larger programs. Fortran excels in this context due to its design for high-performance numerical tasks, where tight loops and array intrinsics enable efficient execution on hardware accelerators, contrasting with interpreted scripting languages like Python that require additional libraries (e.g., ) and often incur overhead in pure loop-based computations. For instance, benchmarks show Fortran codes for series summations running 10-100 times faster than equivalent unoptimized Python scripts on multicore systems, underscoring its role in scientific simulations.

Cultural Aspects

Humor and Anecdotes

Fortran has elicited a wealth of humor in programming circles, often centered on its rigid and legacy features. A classic one-liner declares, " is REAL (unless declared )," playing on the language's explicit variable requirements. Similarly, programmers jest that "Fortran: what 2 computers do before interface," riffing on the language's early emphasis on mathematical expressions over modern interoperability concepts. Early development anecdotes highlight the intense, improvisational nature of Fortran's creation under at . Backus assembled a small team of recent graduates and mathematicians, many lacking formal programming experience, leading to late-night brainstorming sessions that transformed into executable code by 1957. mishaps added to the era's , as Fortran programs were typically submitted as physical decks that could scatter if dropped. Programmers witnessing students lose hours resorting hundreds of cards after an accidental spill, a disaster exacerbated by the lack of numbering on many decks. Such incidents fueled self-deprecating tales of Fortran's unforgiving input methods, contrasting sharply with its computational prowess. Fortran's cultural footprint includes nods in popular media and astronomy. In the 2016 film , mathematician self-teaches Fortran and instructs her team on it to transition from human computation to electronic programming for space missions. The language even earned a celestial tribute: asteroid (9548) Fortran, discovered in 1985 by the Spacewatch program at , orbits the main as a nod to its foundational role in scientific computing. As of 2025, Fortran continues to influence culture through discussions of its enduring relevance in scientific software.

Further reading

This section provides a curated list of recommended books on Fortran, drawn from suggestions in scientific computing communities and developer forums. The selection includes resources for learning the language, comprehensive references, and texts covering both classic and modern standards up to Fortran 2023.
  • Modern Fortran Explained: Incorporating Fortran 2023 by Michael Metcalf, John Reid, and Malcolm Cohen
    A definitive reference that elucidates the full Fortran language, including the latest standards up to 2023. It is particularly valuable for documentation and advanced users, featuring updates on modern elements such as enhanced parallelism.
  • Modern Fortran: Building Efficient Parallel Applications by Milan Curcic
    A practical guide emphasizing modern Fortran for high-performance computing, including parallelism. Suitable for beginners and experienced users in scientific applications.
  • Fortran 95/2003 for Scientists and Engineers by Stephen J. Chapman
    A textbook focused on scientific and engineering applications, covering fundamentals with examples. Widely used for learning and as a reference in technical fields.
  • Introduction to Programming with Fortran by Ian Chivers and Jane Sleightholme
    An introductory text progressing from basics to advanced topics, aligned with modern standards. Recommended for self-study and novices.
  • Guide to Fortran 2008 Programming by Walter S. Brainerd
    A clear guide on Fortran 2008 features, ideal for beginners adopting modern practices and as a syntax reference.
  • Fortran 90 Handbook: Complete ANSI/ISO Reference by Jeanne C. Adams et al.
    An exhaustive reference for Fortran 90 standards, foundational for understanding core language features and documentation.
  • Modern Fortran in Practice by Arjen Markus
    A book on practical techniques for real-world problems in science and engineering, suitable for intermediate users.
  • Structured FORTRAN 77 for Engineers and Scientists by D. M. Etter
    A classic text on structured programming, adopted in engineering education for foundational concepts.
  • Schaum's Outline of Programming with Fortran 77 by William E. Mayo and Martin Cwiakala
    A problem-oriented resource with solved examples, useful for practice and quick reference.
  • A First Course in Scientific Computing: Symbolic, Graphic, and Numeric Modeling Using Maple, Java, Mathematica, and Fortran90 by Rubin H. Landau
    An interdisciplinary introduction integrating Fortran 90 with computational science tools, common in academic curricula.

References

Add your contribution
Related Hubs
User Avatar
No comments yet.