Fortran – File Input Output ”; Previous Next Fortran allows you to read data from, and write data into files. In the last chapter, you have seen how to read data from, and write data to the terminal. In this chapter you will study file input and output functionalities provided by Fortran. You can read and write to one or more files. The OPEN, WRITE, READ and CLOSE statements allow you to achieve this. Opening and Closing Files Before using a file you must open the file. The open command is used to open files for reading or writing. The simplest form of the command is − open (unit = number, file = “name”). However, the open statement may have a general form − open (list-of-specifiers) The following table describes the most commonly used specifiers − Sr.No Specifier & Description 1 [UNIT=] u The unit number u could be any number in the range 9-99 and it indicates the file, you may choose any number but every open file in the program must have a unique number 2 IOSTAT= ios It is the I/O status identifier and should be an integer variable. If the open statement is successful then the ios value returned is zero else a non-zero value. 3 ERR = err It is a label to which the control jumps in case of any error. 4 FILE = fname File name, a character string. 5 STATUS = sta It shows the prior status of the file. A character string and can have one of the three values NEW, OLD or SCRATCH. A scratch file is created and deleted when closed or the program ends. 6 ACCESS = acc It is the file access mode. Can have either of the two values, SEQUENTIAL or DIRECT. The default is SEQUENTIAL. 7 FORM = frm It gives the formatting status of the file. Can have either of the two values FORMATTED or UNFORMATTED. The default is UNFORMATTED 8 RECL = rl It specifies the length of each record in a direct access file. After the file has been opened, it is accessed by read and write statements. Once done, it should be closed using the close statement. The close statement has the following syntax − close ([UNIT = ]u[,IOSTAT = ios,ERR = err,STATUS = sta]) Please note that the parameters in brackets are optional. Example This example demonstrates opening a new file for writing some data into the file. program outputdata implicit none real, dimension(100) :: x, y real, dimension(100) :: p, q integer :: i ! data do i=1,100 x(i) = i * 0.1 y(i) = sin(x(i)) * (1-cos(x(i)/3.0)) end do ! output data into a file open(1, file = ”data1.dat”, status = ”new”) do i=1,100 write(1,*) x(i), y(i) end do close(1) end program outputdata When the above code is compiled and executed, it creates the file data1.dat and writes the x and y array values into it. And then closes the file. Reading from and Writing into the File The read and write statements respectively are used for reading from and writing into a file respectively. They have the following syntax − read ([UNIT = ]u, [FMT = ]fmt, IOSTAT = ios, ERR = err, END = s) write([UNIT = ]u, [FMT = ]fmt, IOSTAT = ios, ERR = err, END = s) Most of the specifiers have already been discussed in the above table. The END = s specifier is a statement label where the program jumps, when it reaches end-of-file. Example This example demonstrates reading from and writing into a file. In this program we read from the file, we created in the last example, data1.dat, and display it on screen. Live Demo program outputdata implicit none real, dimension(100) :: x, y real, dimension(100) :: p, q integer :: i ! data do i = 1,100 x(i) = i * 0.1 y(i) = sin(x(i)) * (1-cos(x(i)/3.0)) end do ! output data into a file open(1, file = ”data1.dat”, status=”new”) do i = 1,100 write(1,*) x(i), y(i) end do close(1) ! opening the file for reading open (2, file = ”data1.dat”, status = ”old”) do i = 1,100 read(2,*) p(i), q(i) end do close(2) do i = 1,100 write(*,*) p(i), q(i) end do end program outputdata When the above code is compiled and executed, it produces the following result − 0.100000001 5.54589933E-05 0.200000003 4.41325130E-04 0.300000012 1.47636665E-03 0.400000006 3.45637114E-03 0.500000000 6.64328877E-03 0.600000024 1.12552457E-02 0.699999988 1.74576249E-02 0.800000012 2.53552198E-02 0.900000036 3.49861123E-02 1.00000000 4.63171229E-02 1.10000002 5.92407547E-02 1.20000005 7.35742599E-02 1.30000007 8.90605897E-02 1.39999998 0.105371222 1.50000000 0.122110792 1.60000002 0.138823599 1.70000005 0.155002072 1.80000007 0.170096487 1.89999998 0.183526158 2.00000000 0.194692180 2.10000014 0.202990443 2.20000005 0.207826138 2.29999995 0.208628103 2.40000010 0.204863414 2.50000000 0.196052119 2.60000014 0.181780845 2.70000005 0.161716297 2.79999995 0.135617107 2.90000010 0.103344671 3.00000000 6.48725405E-02 3.10000014 2.02930309E-02 3.20000005 -3.01767997E-02 3.29999995 -8.61928314E-02 3.40000010 -0.147283033 3.50000000 -0.212848678 3.60000014 -0.282169819 3.70000005 -0.354410470 3.79999995 -0.428629100 3.90000010 -0.503789663 4.00000000 -0.578774154 4.09999990 -0.652400017 4.20000029 -0.723436713 4.30000019 -0.790623367 4.40000010 -0.852691114 4.50000000 -0.908382416 4.59999990 -0.956472993 4.70000029 -0.995793998 4.80000019 -1.02525222 4.90000010 -1.04385209 5.00000000 -1.05071592 5.09999990 -1.04510069 5.20000029 -1.02641726 5.30000019 -0.994243503 5.40000010 -0.948338211 5.50000000 -0.888650239 5.59999990 -0.815326691 5.70000029 -0.728716135 5.80000019 -0.629372001 5.90000010 -0.518047631 6.00000000 -0.395693362 6.09999990 -0.263447165 6.20000029 -0.122622721 6.30000019 2.53026206E-02 6.40000010 0.178709000 6.50000000 0.335851669 6.59999990 0.494883657 6.70000029 0.653881252 6.80000019 0.810866773 6.90000010 0.963840425 7.00000000 1.11080539 7.09999990 1.24979746 7.20000029 1.37891412 7.30000019 1.49633956 7.40000010 1.60037732 7.50000000 1.68947268 7.59999990 1.76223695 7.70000029 1.81747139 7.80000019 1.85418403 7.90000010 1.87160957 8.00000000 1.86922085 8.10000038 1.84674001 8.19999981 1.80414569 8.30000019 1.74167395 8.40000057 1.65982044 8.50000000 1.55933595 8.60000038 1.44121361 8.69999981 1.30668485 8.80000019 1.15719533 8.90000057 0.994394958 9.00000000 0.820112705 9.10000038 0.636327863 9.19999981 0.445154816 9.30000019 0.248800844 9.40000057 4.95488606E-02 9.50000000 -0.150278628 9.60000038 -0.348357052 9.69999981 -0.542378068 9.80000019 -0.730095863 9.90000057 -0.909344316 10.0000000 -1.07807255 Print Page Previous Next Advertisements ”;
Category: fortran
Fortran – Programming Style
Fortran – Programming Style ”; Previous Next Programming style is all about following some rules while developing programs. These good practices impart values like readability, and unambiguity into your program. A good program should have the following characteristics − Readability Proper logical structure Self-explanatory notes and comments For example, if you make a comment like the following, it will not be of much help − ! loop from 1 to 10 do i = 1,10 However, if you are calculating binomial coefficient, and need this loop for nCr then a comment like this will be helpful − ! loop to calculate nCr do i = 1,10 Indented code blocks to make various levels of code clear. Self-checking codes to ensure there will be no numerical errors like division by zero, square root of a negative real number or logarithm of a negative real number. Including codes that ensure variables do not take illegal or out of range values, i.e., input validation. Not putting checks where it would be unnecessary and slows down the execution. For example − real :: x x = sin(y) + 1.0 if (x >= 0.0) then z = sqrt(x) end if Clearly written code using appropriate algorithms. Splitting the long expressions using the continuation marker ‘&’. Making meaningful variable names. Print Page Previous Next Advertisements ”;
Fortran – Overview
Fortran – Overview ”; Previous Next Fortran, as derived from Formula Translating System, is a general-purpose, imperative programming language. It is used for numeric and scientific computing. Fortran was originally developed by IBM in the 1950s for scientific and engineering applications. Fortran ruled this programming area for a long time and became very popular for high performance computing, because. It supports − Numerical analysis and scientific computation Structured programming Array programming Modular programming Generic programming High performance computing on supercomputers Object oriented programming Concurrent programming Reasonable degree of portability between computer systems Facts about Fortran Fortran was created by a team, led by John Backus at IBM in 1957. Initially the name used to be written in all capital, but current standards and implementations only require the first letter to be capital. Fortran stands for FORmula TRANslator. Originally developed for scientific calculations, it had very limited support for character strings and other structures needed for general purpose programming. Later extensions and developments made it into a high level programming language with good degree of portability. Original versions, Fortran I, II and III are considered obsolete now. Oldest version still in use is Fortran IV, and Fortran 66. Most commonly used versions today are : Fortran 77, Fortran 90, and Fortran 95. Fortran 77 added strings as a distinct type. Fortran 90 added various sorts of threading, and direct array processing. Print Page Previous Next Advertisements ”;
Fortran – Environment Setup
Fortran – Environment Setup ”; Previous Next Setting up Fortran in Windows G95 is the GNU Fortran multi-architechtural compiler, used for setting up Fortran in Windows. The windows version emulates a unix environment using MingW under windows. The installer takes care of this and automatically adds g95 to the windows PATH variable. You can get the stable version of G95 from here How to use G95 During installation, g95 is automatically added to your PATH variable if you select the option “RECOMMENDED”. This means that you can simply open a new Command Prompt window and type “g95” to bring up the compiler. Find some basic commands below to get you started. Sr.No Command & Description 1 g95 –c hello.f90 Compiles hello.f90 to an object file named hello.o 2 g95 hello.f90 Compiles hello.f90 and links it to produce an executable a.out 3 g95 -c h1.f90 h2.f90 h3.f90 Compiles multiple source files. If all goes well, object files h1.o, h2.o and h3.o are created 4 g95 -o hello h1.f90 h2.f90 h3.f90 Compiles multiple source files and links them together to an executable file named ”hello” Command line options for G95 -c Compile only, do not run the linker. -o Specify the name of the output file, either an object file or the executable. Multiple source and object files can be specified at once. Fortran files are indicated by names ending in “.f”, “.F”, “.for”, “.FOR”, “.f90”, “.F90”, “.f95”, “.F95”, “.f03” and “.F03”. Multiple source files can be specified. Object files can be specified as well and will be linked to form an executable file. Print Page Previous Next Advertisements ”;
Fortran – Home
Fortran Tutorial PDF Version Quick Guide Resources Job Search Discussion Fortran was originally developed by a team at IBM in 1957 for scientific calculations. Later developments made it into a high level programming language. In this tutorial, we will learn the basic concepts of Fortran and its programming code. Audience This tutorial is designed for the readers who wish to learn the basics of Fortran. Prerequisites This tutorial is designed for beginners. A general awareness of computer programming languages is the only prerequisite to make the most of this tutorial. Print Page Previous Next Advertisements ”;
Fortran – Operators
Fortran – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Fortran provides the following types of operators − Arithmetic Operators Relational Operators Logical Operators Let us look at all these types of operators one by one. Arithmetic Operators Following table shows all the arithmetic operators supported by Fortran. Assume variable A holds 5 and variable B holds 3 then − Show Examples Operator Description Example + Addition Operator, adds two operands. A + B will give 8 – Subtraction Operator, subtracts second operand from the first. A – B will give 2 * Multiplication Operator, multiplies both operands. A * B will give 15 / Division Operator, divides numerator by de-numerator. A / B will give 1 ** Exponentiation Operator, raises one operand to the power of the other. A ** B will give 125 Relational Operators Following table shows all the relational operators supported by Fortran. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Equivalent Description Example == .eq. Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. /= .ne. Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > .gt. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < .lt. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= .ge. Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= .le. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. Logical Operators Logical operators in Fortran work only on logical values .true. and .false. The following table shows all the logical operators supported by Fortran. Assume variable A holds .true. and variable B holds .false. , then − Show Examples Operator Description Example .and. Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A .and. B) is false. .or. Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A .or. B) is true. .not. Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A .and. B) is true. .eqv. Called Logical EQUIVALENT Operator. Used to check equivalence of two logical values. (A .eqv. B) is false. .neqv. Called Logical NON-EQUIVALENT Operator. Used to check non-equivalence of two logical values. (A .neqv. B) is true. Operators Precedence in Fortran Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Show Examples Category Operator Associativity Logical NOT and negative sign .not. (-) Left to right Exponentiation ** Left to right Multiplicative * / Left to right Additive + – Left to right Relational < <= > >= Left to right Equality == /= Left to right Logical AND .and. Left to right Logical OR .or. Left to right Assignment = Right to left Print Page Previous Next Advertisements ”;
Fortran – Variables
Fortran – Variables ”; Previous Next A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable should have a specific type, which determines the size and layout of the variable”s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. A name in Fortran must follow the following rules − It cannot be longer than 31 characters. It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_). First character of a name must be a letter. Names are case-insensitive. Based on the basic types explained in previous chapter, following are the variable types − Sr.No Type & Description 1 Integer It can hold only integer values. 2 Real It stores the floating point numbers. 3 Complex It is used for storing complex numbers. 4 Logical It stores logical Boolean values. 5 Character It stores characters or strings. Variable Declaration Variables are declared at the beginning of a program (or subprogram) in a type declaration statement. Syntax for variable declaration is as follows − type-specifier :: variable_name For example integer :: total real :: average complex :: cx logical :: done character(len = 80) :: message ! a string of 80 characters Later you can assign values to these variables, like, total = 20000 average = 1666.67 done = .true. message = “A big Hello from Tutorials Point” cx = (3.0, 5.0) ! cx = 3.0 + 5.0i You can also use the intrinsic function cmplx, to assign values to a complex variable − cx = cmplx (1.0/2.0, -7.0) ! cx = 0.5 – 7.0i cx = cmplx (x, y) ! cx = x + yi Example The following example demonstrates variable declaration, assignment and display on screen − Live Demo program variableTesting implicit none ! declaring variables integer :: total real :: average complex :: cx logical :: done character(len=80) :: message ! a string of 80 characters !assigning values total = 20000 average = 1666.67 done = .true. message = “A big Hello from Tutorials Point” cx = (3.0, 5.0) ! cx = 3.0 + 5.0i Print *, total Print *, average Print *, cx Print *, done Print *, message end program variableTesting When the above code is compiled and executed, it produces the following result − 20000 1666.67004 (3.00000000, 5.00000000 ) T A big Hello from Tutorials Point Print Page Previous Next Advertisements ”;
Fortran – Numeric Precision
Fortran – Numeric Precision ”; Previous Next We have already discussed that, in older versions of Fortran, there were two real types: the default real type and double precision type. However, Fortran 90/95 provides more control over the precision of real and integer data types through the kind specifie. The Kind Attribute Different kind of numbers are stored differently inside the computer. The kind attribute allows you to specify how a number is stored internally. For example, real, kind = 2 :: a, b, c real, kind = 4 :: e, f, g integer, kind = 2 :: i, j, k integer, kind = 3 :: l, m, n In the above declaration, the real variables e, f and g have more precision than the real variables a, b and c. The integer variables l, m and n, can store larger values and have more digits for storage than the integer variables i, j and k. Although this is machine dependent. Example Live Demo program kindSpecifier implicit none real(kind = 4) :: a, b, c real(kind = 8) :: e, f, g integer(kind = 2) :: i, j, k integer(kind = 4) :: l, m, n integer :: kind_a, kind_i, kind_e, kind_l kind_a = kind(a) kind_i = kind(i) kind_e = kind(e) kind_l = kind(l) print *,”default kind for real is”, kind_a print *,”default kind for int is”, kind_i print *,”extended kind for real is”, kind_e print *,”default kind for int is”, kind_l end program kindSpecifier When you compile and execute the above program it produces the following result − default kind for real is 4 default kind for int is 2 extended kind for real is 8 default kind for int is 4 Inquiring the Size of Variables There are a number of intrinsic functions that allows you to interrogate the size of numbers. For example, the bit_size(i) intrinsic function specifies the number of bits used for storage. For real numbers, the precision(x) intrinsic function, returns the number of decimal digits of precision, while the range(x) intrinsic function returns the decimal range of the exponent. Example Live Demo program getSize implicit none real (kind = 4) :: a real (kind = 8) :: b integer (kind = 2) :: i integer (kind = 4) :: j print *,”precision of real(4) =”, precision(a) print *,”precision of real(8) =”, precision(b) print *,”range of real(4) =”, range(a) print *,”range of real(8) =”, range(b) print *,”maximum exponent of real(4) =” , maxexponent(a) print *,”maximum exponent of real(8) =” , maxexponent(b) print *,”minimum exponent of real(4) =” , minexponent(a) print *,”minimum exponent of real(8) =” , minexponent(b) print *,”bits in integer(2) =” , bit_size(i) print *,”bits in integer(4) =” , bit_size(j) end program getSize When you compile and execute the above program it produces the following result − precision of real(4) = 6 precision of real(8) = 15 range of real(4) = 37 range of real(8) = 307 maximum exponent of real(4) = 128 maximum exponent of real(8) = 1024 minimum exponent of real(4) = -125 minimum exponent of real(8) = -1021 bits in integer(2) = 16 bits in integer(4) = 32 Obtaining the Kind Value Fortran provides two more intrinsic functions to obtain the kind value for the required precision of integers and reals − selected_int_kind (r) selected_real_kind ([p, r]) The selected_real_kind function returns an integer that is the kind type parameter value necessary for a given decimal precision p and decimal exponent range r. The decimal precision is the number of significant digits, and the decimal exponent range specifies the smallest and largest representable number. The range is thus from 10-r to 10+r. For example, selected_real_kind (p = 10, r = 99) returns the kind value needed for a precision of 10 decimal places, and a range of at least 10-99 to 10+99. Example Live Demo program getKind implicit none integer:: i i = selected_real_kind (p = 10, r = 99) print *,”selected_real_kind (p = 10, r = 99)”, i end program getKind When you compile and execute the above program it produces the following result − selected_real_kind (p = 10, r = 99) 8 Print Page Previous Next Advertisements ”;
Fortran – Data Types
Fortran – Data Types ”; Previous Next Fortran provides five intrinsic data types, however, you can derive your own data types as well. The five intrinsic types are − Integer type Real type Complex type Logical type Character type Integer Type The integer types can hold only integer values. The following example extracts the largest value that can be held in a usual four byte integer − Live Demo program testingInt implicit none integer :: largeval print *, huge(largeval) end program testingInt When you compile and execute the above program it produces the following result − 2147483647 Note that the huge() function gives the largest number that can be held by the specific integer data type. You can also specify the number of bytes using the kind specifier. The following example demonstrates this − Live Demo program testingInt implicit none !two byte integer integer(kind = 2) :: shortval !four byte integer integer(kind = 4) :: longval !eight byte integer integer(kind = 8) :: verylongval !sixteen byte integer integer(kind = 16) :: veryverylongval !default integer integer :: defval print *, huge(shortval) print *, huge(longval) print *, huge(verylongval) print *, huge(veryverylongval) print *, huge(defval) end program testingInt When you compile and execute the above program, it produces the following result − 32767 2147483647 9223372036854775807 170141183460469231731687303715884105727 2147483647 Real Type It stores the floating point numbers, such as 2.0, 3.1415, -100.876, etc. Traditionally there are two different real types, the default real type and double precision type. However, Fortran 90/95 provides more control over the precision of real and integer data types through the kind specifier, which we will study in the chapter on Numbers. The following example shows the use of real data type − Live Demo program division implicit none ! Define real variables real :: p, q, realRes ! Define integer variables integer :: i, j, intRes ! Assigning values p = 2.0 q = 3.0 i = 2 j = 3 ! floating point division realRes = p/q intRes = i/j print *, realRes print *, intRes end program division When you compile and execute the above program it produces the following result − 0.666666687 0 Complex Type This is used for storing complex numbers. A complex number has two parts, the real part and the imaginary part. Two consecutive numeric storage units store these two parts. For example, the complex number (3.0, -5.0) is equal to 3.0 – 5.0i We will discuss Complex types in more detail, in the Numbers chapter. Logical Type There are only two logical values: .true. and .false. Character Type The character type stores characters and strings. The length of the string can be specified by len specifier. If no length is specified, it is 1. For example, character (len = 40) :: name name = “Zara Ali” The expression, name(1:4) would give the substring “Zara”. Implicit Typing Older versions of Fortran allowed a feature called implicit typing, i.e., you do not have to declare the variables before use. If a variable is not declared, then the first letter of its name will determine its type. Variable names starting with i, j, k, l, m, or n, are considered to be for integer variable and others are real variables. However, you must declare all the variables as it is good programming practice. For that you start your program with the statement − implicit none This statement turns off implicit typing. Print Page Previous Next Advertisements ”;