Input and output (I/O) operations are essential in any programming language. They allow programs to interact with users, read data from files, and display results. In Fortran, input and output operations are performed using commands like read, print, and write. This post will explore these commands in detail, along with practical examples and best practices for effective I/O in Fortran.
1. Introduction to Input and Output
Input refers to the process of receiving data from the user or a file, while output refers to sending data to the user or storing it in a file. Fortran, being a language focused on scientific and numerical computation, provides a variety of methods for input and output. Proper handling of I/O is crucial for creating interactive and user-friendly programs.
Fortran distinguishes between formatted and unformatted I/O:
- Formatted I/O: Data is read or written in a human-readable format.
- Unformatted I/O: Data is stored in binary form for faster processing and compact storage.
In most beginner and intermediate programs, formatted I/O using read, print, and write is sufficient and commonly used.
2. Using print for Output
The print statement is the simplest way to display output on the screen. It writes formatted text to the standard output. Its syntax is straightforward:
print *, "Your message here"
The * indicates list-directed formatting, which automatically chooses the format based on the data type.
2.1 Example: Simple Print Statement
program print_example
print *, "Hello, welcome to Fortran programming!"
end program print_example
Output:
Hello, welcome to Fortran programming!
2.2 Printing Variables
You can also print variables alongside messages:
program print_variables
integer :: age
age = 25
print *, "Your age is", age
end program print_variables
Output:
Your age is 25
2.3 Printing Multiple Variables
Fortran allows multiple variables to be printed in a single statement:
program multiple_print
integer :: a, b
a = 10
b = 20
print *, "Values of a and b are:", a, b
end program multiple_print
Output:
Values of a and b are: 10 20
3. Using read for Input
The read statement allows programs to accept data from the user via the keyboard or from a file. Its basic syntax is:
read *, variable
The * indicates list-directed input, which automatically interprets the type of data being read.
3.1 Example: Reading a Single Value
program read_example
integer :: age
print *, "Enter your age:"
read *, age
print *, "You are", age, "years old"
end program read_example
Sample Input:
30
Output:
You are 30 years old
3.2 Reading Multiple Values
You can read multiple values in a single statement:
program read_multiple
integer :: a, b, c
print *, "Enter three integers:"
read *, a, b, c
print *, "You entered:", a, b, c
end program read_multiple
Sample Input:
5 10 15
Output:
You entered: 5 10 15
3.3 Reading Real and Character Data
Fortran allows reading different types of data:
program read_mixed
integer :: age
real :: height
character(len=20) :: name
print *, "Enter your name, age, and height:"
read *, name, age, height
print *, "Name:", name
print *, "Age:", age
print *, "Height:", height
end program read_mixed
Sample Input:
Alice 28 5.6
Output:
Name: Alice
Age: 28
Height: 5.6
4. Using write for Output
The write statement is more versatile than print. It can write to the screen, files, or other output devices. Its general syntax is:
write(unit, format) output_list
- unit: The I/O unit number (for standard output,
*is used) - format: The format specifier (
*for list-directed formatting) - output_list: The list of variables or strings to output
4.1 Example: Simple Write Statement
program write_example
write(*, *) "This is a message using write"
end program write_example
Output:
This is a message using write
4.2 Writing Variables
program write_variables
integer :: a, b
a = 7
b = 14
write(*, *) "Values of a and b:", a, b
end program write_variables
Output:
Values of a and b: 7 14
5. Formatting Output
Fortran allows formatting output to control the appearance of data. This is useful for creating tables, aligning columns, or specifying decimal precision.
5.1 Using Format Specifiers
program formatted_output
real :: pi
pi = 3.14159265
write(*,'(A, F6.2)') "Value of pi: ", pi
end program formatted_output
Output:
Value of pi: 3.14
Explanation:
Aprints a string.F6.2prints a floating-point number with a total width of 6 characters and 2 decimal places.
5.2 Example: Column Alignment
program table_output
integer :: i
real :: square
print *, "Number Square"
do i = 1, 5
square = i**2
write(*,'(I6, F8.2)') i, square
end do
end program table_output
Output:
Number Square
1 1.00
2 4.00
3 9.00
4 16.00
5 25.00
6. Combining Input and Output
Most programs require a combination of input and output to interact with users. Fortran makes this process simple and efficient.
6.1 Example: Age Calculator
program age_calculator
integer :: birth_year, current_year, age
print *, "Enter your birth year:"
read *, birth_year
print *, "Enter the current year:"
read *, current_year
age = current_year - birth_year
print *, "Your age is", age, "years"
end program age_calculator
Sample Input:
1990
2025
Output:
Your age is 35 years
6.2 Example: Sum of Numbers
program sum_numbers
integer :: n, i, sum, value
sum = 0
print *, "How many numbers do you want to sum?"
read *, n
do i = 1, n
print *, "Enter number", i, ":"
read *, value
sum = sum + value
end do
print *, "The total sum is", sum
end program sum_numbers
Sample Input:
3
10
20
30
Output:
The total sum is 60
7. Reading and Writing from Files
Fortran allows input and output not only from the keyboard and screen but also from files. File I/O involves specifying a unit number, file name, and mode (read, write, or append).
7.1 Writing to a File
program write_file
integer :: i
open(unit=10, file="numbers.txt", status="replace")
do i = 1, 5
write(10, *) i, i**2
end do
close(10)
print *, "Data written to numbers.txt"
end program write_file
This creates a file numbers.txt with numbers and their squares.
7.2 Reading from a File
program read_file
integer :: i, square
open(unit=10, file="numbers.txt", status="old")
do
read(10, *, iostat=i) i, square
if (i /= 0) exit
print *, "Number:", i, "Square:", square
end do
close(10)
end program read_file
8. Best Practices for Input and Output
- Prompt users clearly: Always display clear messages when expecting input.
- Validate input: Ensure that the data entered is valid for calculations.
- Use formatted output: Align columns and control decimal places for readability.
- Close files: Always close files after reading or writing.
- Use meaningful variable names: Improves readability in I/O operations.
- Error handling: Use
iostatto handle input/output errors gracefully.
9. Advanced Input and Output
Fortran provides several advanced I/O features:
- Formatted strings: Use
formatstatements for reusable formatting. - Internal files: Treat strings as input/output targets.
- Non-blocking I/O: Perform background input/output operations.
- Direct-access files: Random access to data in files for efficiency.
9.1 Example: Using Format Statement
program format_example
integer :: a, b
a = 5
b = 10
write(*, 100) a, b
100 format('First value:', I4, ' Second value:', I4)
end program format_example
Output:
First value: 5 Second value: 10
Leave a Reply