close
close

fortran write

2 min read 03-10-2024
fortran write

Fortran is one of the oldest high-level programming languages and is predominantly used in scientific and engineering applications. One of its critical features is the WRITE statement, which is essential for outputting data. In this article, we will demystify the WRITE statement in Fortran, analyze its components, and provide practical examples to help you effectively utilize it in your code.

Original Scenario and Code

Let’s consider the following piece of Fortran code where the WRITE statement is utilized:

PROGRAM example_write
    IMPLICIT NONE
    INTEGER :: number

    number = 10
    WRITE(*,*) 'The value of number is:', number
END PROGRAM example_write

In this code snippet, we have a simple Fortran program that declares an integer variable number, assigns it the value of 10, and then uses the WRITE statement to output the value of number to the standard output.

Breakdown of the WRITE Statement

The syntax of the WRITE statement in Fortran is as follows:

WRITE (unit, format) list
  1. Unit: This specifies the output device. Asterisk (*) indicates the default output device, which is usually the console.
  2. Format: This defines how the output should be formatted. Asterisks for format indicate a free format output, while you can define a specific format using a format label or a format string.
  3. List: This is a list of variables or expressions that you want to output.

Practical Example

Let’s expand our earlier example to demonstrate different formatting options. Here is a modified code snippet:

PROGRAM formatted_write_example
    IMPLICIT NONE
    INTEGER :: a, b
    REAL :: c

    a = 5
    b = 10
    c = 20.5

    ! Writing to the console
    WRITE(*,*) 'Values in free format: ', a, b, c
    WRITE(*,'(I5, F10.2)') a, c   ! Using a format for integers and real numbers
END PROGRAM formatted_write_example

In this example:

  • The first WRITE outputs the values of a, b, and c in a simple and straightforward way.
  • The second WRITE uses a specific format that defines how to display a (an integer) and c (a real number). The (I5, F10.2) format specifies that a should be printed in a field of 5 characters, and c should have a total width of 10 characters with 2 decimal places.

Analyzing Output

When you run this program, you will see the following outputs on the console:

Values in free format: 5 10 20.500000
   5     20.50

Conclusion

The WRITE statement in Fortran is a powerful tool for outputting data in both free and formatted styles. Understanding its syntax and practical applications can significantly enhance how you present your program's output.

Additional Resources

To dive deeper into Fortran and its features, consider the following resources:

By following this guide and utilizing the provided examples, you can leverage the capabilities of the WRITE statement in your Fortran programs, making your output more informative and appealing.