Fortran – Useful Resources

Fortran – Useful Resources ”; Previous Next The following resources contain additional information on Fortran. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Javascript Object oriented programming Course – Build Quiz App 61 Lectures 8 hours DigiFisk (Programming Is Fun) More Detail Industry 4.0 – Automation & Applications 35 Lectures 2.5 hours J Aatish Rao More Detail Java Courses in Tamil 188 Lectures 11.5 hours Programming Line More Detail Python for Beginners with Real world applications in Hindi 54 Lectures 8 hours Saurabh Dubey More Detail Data Science and Machine Learning with R from A-Z Course [Updated for 2021] 81 Lectures 28.5 hours Packt Publishing More Detail Internet of Things (IoT) Automation using Raspberry Pi 2 23 Lectures 39 mins Venkatesh Varadachari More Detail Print Page Previous Next Advertisements ”;

Fortran – Numbers

Fortran – Numbers ”; Previous Next Numbers in Fortran are represented by three intrinsic data types − Integer type Real type Complex type Integer Type The integer types can hold only integer values. The following example extracts the largest value that could be hold 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 Please 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 were 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 shortly. 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 The generic function cmplx() creates a complex number. It produces a result who’s real and imaginary parts are single precision, irrespective of the type of the input arguments. Live Demo program createComplex implicit none integer :: i = 10 real :: x = 5.17 print *, cmplx(i, x) end program createComplex When you compile and execute the above program it produces the following result − (10.0000000, 5.17000008) The following program demonstrates complex number arithmetic − Live Demo program ComplexArithmatic implicit none complex, parameter :: i = (0, 1) ! sqrt(-1) complex :: x, y, z x = (7, 8); y = (5, -7) write(*,*) i * x * y z = x + y print *, “z = x + y = “, z z = x – y print *, “z = x – y = “, z z = x * y print *, “z = x * y = “, z z = x / y print *, “z = x / y = “, z end program ComplexArithmatic When you compile and execute the above program it produces the following result − (9.00000000, 91.0000000) z = x + y = (12.0000000, 1.00000000) z = x – y = (2.00000000, 15.0000000) z = x * y = (91.0000000, -9.00000000) z = x / y = (-0.283783793, 1.20270276) The Range, Precision and Size of Numbers The range on integer numbers, the precision and the size of floating point numbers depends on the number of bits allocated to the specific data type. The following table displays the number of bits and range for integers − Number of bits Maximum value Reason 64 9,223,372,036,854,774,807 (2**63)–1 32 2,147,483,647 (2**31)–1 The following table displays the number of bits, smallest and largest value, and the precision for real numbers. Number of bits Largest value Smallest value Precision 64 0.8E+308 0.5E–308 15–18 32 1.7E+38 0.3E–38 6-9 The following examples demonstrate this − Live Demo program rangePrecision implicit none real:: x, y, z x = 1.5e+40 y = 3.73e+40 z = x * y print *, z end program rangePrecision When you compile and execute the above program it produces the following result − x = 1.5e+40 1 Error : Real constant overflows its kind at (1) main.f95:5.12: y = 3.73e+40 1 Error : Real constant overflows its kind at (1) Now let us use a smaller number − Live Demo program rangePrecision implicit none real:: x, y, z x = 1.5e+20 y = 3.73e+20 z = x * y print *, z z = x/y print *, z end program rangePrecision When you compile and execute the above program it produces the following result − Infinity 0.402144760 Now let’s watch underflow − Live Demo program rangePrecision implicit none real:: x, y, z x = 1.5e-30 y = 3.73e-60 z = x * y print *, z z = x/y print *, z end program rangePrecision When you compile and execute the above program it produces the following result − y = 3.73e-60 1 Warning : Real constant underflows its kind at (1) Executing the program…. $demo  0.00000000E+00 Infinity The Kind Specifier In scientific programming, one often needs to know the range and precision of data of the hardware platform on which the work is being done. The intrinsic function kind() allows you to query the details of the hardware’s data representations before running a program. Live Demo program kindCheck implicit none integer :: i real :: r complex :: cp print *,” Integer ”, kind(i) print *,” Real ”, kind(r) print *,” Complex ”, kind(cp) end program kindCheck When you compile and execute the above program it produces the following result − Integer 4 Real 4 Complex

Fortran – Characters

Fortran – Characters ”; Previous Next The Fortran language can treat characters as single character or contiguous strings. Characters could be any symbol taken from the basic character set, i.e., from the letters, the decimal digits, the underscore, and 21 special characters. A character constant is a fixed valued character string. The intrinsic data type character stores characters and strings. The length of the string can be specified by len specifier. If no length is specified, it is 1. You can refer individual characters within a string referring by position; the left most character is at position 1. Character Declaration Declaring a character type data is same as other variables − type-specifier :: variable_name For example, character :: reply, sex you can assign a value like, reply = ‘N’ sex = ‘F’ The following example demonstrates declaration and use of character data type − Live Demo program hello implicit none character(len = 15) :: surname, firstname character(len = 6) :: title character(len = 25)::greetings title = ”Mr. ” firstname = ”Rowan ” surname = ”Atkinson” greetings = ”A big hello from Mr. Bean” print *, ”Here is ”, title, firstname, surname print *, greetings end program hello When you compile and execute the above program it produces the following result − Here is Mr. Rowan Atkinson A big hello from Mr. Bean Concatenation of Characters The concatenation operator //, concatenates characters. The following example demonstrates this − Live Demo program hello implicit none character(len = 15) :: surname, firstname character(len = 6) :: title character(len = 40):: name character(len = 25)::greetings title = ”Mr. ” firstname = ”Rowan ” surname = ”Atkinson” name = title//firstname//surname greetings = ”A big hello from Mr. Bean” print *, ”Here is ”, name print *, greetings end program hello When you compile and execute the above program it produces the following result − Here is Mr.Rowan Atkinson A big hello from Mr.Bean Some Character Functions The following table shows some commonly used character functions along with the description − Sr.No Function & Description 1 len(string) It returns the length of a character string 2 index(string,sustring) It finds the location of a substring in another string, returns 0 if not found. 3 achar(int) It converts an integer into a character 4 iachar(c) It converts a character into an integer 5 trim(string) It returns the string with the trailing blanks removed. 6 scan(string, chars) It searches the “string” from left to right (unless back=.true.) for the first occurrence of any character contained in “chars”. It returns an integer giving the position of that character, or zero if none of the characters in “chars” have been found. 7 verify(string, chars) It scans the “string” from left to right (unless back=.true.) for the first occurrence of any character not contained in “chars”. It returns an integer giving the position of that character, or zero if only the characters in “chars” have been found 8 adjustl(string) It left justifies characters contained in the “string” 9 adjustr(string) It right justifies characters contained in the “string” 10 len_trim(string) It returns an integer equal to the length of “string” (len(string)) minus the number of trailing blanks 11 repeat(string,ncopy) It returns a string with length equal to “ncopy” times the length of “string”, and containing “ncopy” concatenated copies of “string” Example 1 This example shows the use of the index function − Live Demo program testingChars implicit none character (80) :: text integer :: i text = ”The intrinsic data type character stores characters and strings.” i=index(text,”character”) if (i /= 0) then print *, ” The word character found at position ”,i print *, ” in text: ”, text end if end program testingChars When you compile and execute the above program it produces the following result − The word character found at position 25 in text : The intrinsic data type character stores characters and strings. Example 2 This example demonstrates the use of the trim function − Live Demo program hello implicit none character(len = 15) :: surname, firstname character(len = 6) :: title character(len = 25)::greetings title = ”Mr.” firstname = ”Rowan” surname = ”Atkinson” print *, ”Here is”, title, firstname, surname print *, ”Here is”, trim(title),” ”,trim(firstname),” ”, trim(surname) end program hello When you compile and execute the above program it produces the following result − Here isMr. Rowan Atkinson Here isMr. Rowan Atkinson Example 3 This example demonstrates the use of achar function − Live Demo program testingChars implicit none character:: ch integer:: i do i = 65, 90 ch = achar(i) print*, i, ” ”, ch end do end program testingChars When you compile and execute the above program it produces the following result − 65 A 66 B 67 C 68 D 69 E 70 F 71 G 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W 88 X 89 Y 90 Z Checking Lexical Order of Characters The following functions determine the lexical sequence of characters − Sr.No Function & Description 1 lle(char, char) Compares whether the first character is lexically less than or equal to the second 2 lge(char, char) Compares whether the first character is lexically greater than or equal to the second 3 lgt(char, char) Compares whether the first character is lexically greater than the second 4 llt(char, char) Compares whether the first character is lexically less than the second Example 4 The following function demonstrates the use − Live Demo program testingChars implicit none character:: a, b, c a = ”A” b = ”a” c = ”B” if(lgt(a,b)) then print *, ”A is lexically greater than a” else print *, ”a is lexically greater than A” end if if(lgt(a,c)) then print *, ”A is lexically greater than B” else print *, ”B is lexically greater than A” end if if(llt(a,b)) then print *, ”A is lexically less than a” end if if(llt(a,c)) then print

Fortran – Decisions

Fortran – Decisions ”; Previous Next Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed, if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Fortran provides the following types of decision making constructs. Sr.No Statement & Description 1 If… then construct An if… then… end if statement consists of a logical expression followed by one or more statements. 2 If… then…else construct An if… then statement can be followed by an optional else statement, which executes when the logical expression is false. 3 if…else if…else Statement An if statement construct can have one or more optional else-if constructs. When the if condition fails, the immediately followed else-if is executed. When the else-if also fails, its successor else-if statement (if any) is executed, and so on. 4 nested if construct You can use one if or else if statement inside another if or else if statement(s). 5 select case construct A select case statement allows a variable to be tested for equality against a list of values. 6 nested select case construct You can use one select case statement inside another select case statement(s). Print Page Previous Next Advertisements ”;

Fortran – Discussion

Discuss Fortran ”; Previous Next 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. Print Page Previous Next Advertisements ”;

Fortran – Quick Guide

Fortran – Quick Guide ”; Previous Next Fortran – Overview 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. Fortran – Environment Setup 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. 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. Fortran – Basic Syntax A Fortran program is made of a collection of program units like a main program, modules, and external subprograms or procedures. Each program contains one main program and may or may not contain other program units. The syntax of the main program is as follows − program program_name implicit none ! type declaration statements ! executable statements end program program_name A Simple Program in Fortran Let’s write a program that adds two numbers and prints the result − Live Demo program addNumbers ! This simple program adds two numbers implicit none ! Type declarations real :: a, b, result ! Executable statements a = 12.0 b = 15.0 result = a + b print *, ”The total is ”, result end program addNumbers When you compile and execute the above program, it produces the following result − The total is 27.0000000 Please note that − All Fortran programs start with the keyword program and end with the keyword end program, followed by the name of the program. The implicit none statement allows the compiler to check that all your variable types are declared properly. You must always use implicit none at the start of every program. Comments in Fortran are started with the exclamation mark (!), as all characters after this (except in a character string) are ignored by the compiler. The print * command displays data on the screen. Indentation of code lines is a good practice for keeping a program readable. Fortran allows both uppercase and lowercase letters. Fortran is case-insensitive, except for string literals. Basics The basic character set of Fortran contains − the letters A … Z and a … z the digits 0 … 9 the underscore (_) character the special characters = : + blank – * / ( ) [ ] , . $ ” ! ” % & ; < > ? Tokens are made of characters in the basic character set. A token could be a keyword, an identifier, a constant, a string literal, or a symbol. Program statements are made of tokens. Identifier An identifier is a name used to identify a variable, procedure, or any other user-defined item. 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 Keywords Keywords are special words, reserved for the language. These reserved words cannot be used as identifiers or names. The following table, lists the Fortran keywords − The non-I/O keywords allocatable allocate assign assignment block data call case character common complex contains continue cycle data deallocate default do double precision else else if elsewhere end block data end do end function end if end interface end module end program end select end subroutine end type end where entry equivalence exit external function go to if implicit in inout integer intent interface intrinsic kind len logical module namelist nullify only

Fortran – Derived Data Types

Fortran – Derived Data Types ”; Previous Next Fortran allows you to define derived data types. A derived data type is also called a structure, and it can consist of data objects of different types. Derived data types are used to represent a record. E.g. you want to keep track of your books in a library, you might want to track the following attributes about each book − Title Author Subject Book ID Defining a Derived data type To define a derived data type, the type and end type statements are used. . The type statement defines a new data type, with more than one member for your program. The format of the type statement is this − type type_name declarations end type Here is the way you would declare the Book structure − type Books character(len = 50) :: title character(len = 50) :: author character(len = 150) :: subject integer :: book_id end type Books Accessing Structure Members An object of a derived data type is called a structure. A structure of type Books can be created in a type declaration statement like − type(Books) :: book1 The components of the structure can be accessed using the component selector character (%) − book1%title = “C Programming” book1%author = “Nuha Ali” book1%subject = “C Programming Tutorial” book1%book_id = 6495407 Note that there are no spaces before and after the % symbol. Example The following program illustrates the above concepts − Live Demo program deriveDataType !type declaration type Books character(len = 50) :: title character(len = 50) :: author character(len = 150) :: subject integer :: book_id end type Books !declaring type variables type(Books) :: book1 type(Books) :: book2 !accessing the components of the structure book1%title = “C Programming” book1%author = “Nuha Ali” book1%subject = “C Programming Tutorial” book1%book_id = 6495407 book2%title = “Telecom Billing” book2%author = “Zara Ali” book2%subject = “Telecom Billing Tutorial” book2%book_id = 6495700 !display book info Print *, book1%title Print *, book1%author Print *, book1%subject Print *, book1%book_id Print *, book2%title Print *, book2%author Print *, book2%subject Print *, book2%book_id end program deriveDataType When the above code is compiled and executed, it produces the following result − C Programming Nuha Ali C Programming Tutorial 6495407 Telecom Billing Zara Ali Telecom Billing Tutorial 6495700 Array of Structures You can also create arrays of a derived type − type(Books), dimension(2) :: list Individual elements of the array could be accessed as − list(1)%title = “C Programming” list(1)%author = “Nuha Ali” list(1)%subject = “C Programming Tutorial” list(1)%book_id = 6495407 The following program illustrates the concept − Live Demo program deriveDataType !type declaration type Books character(len = 50) :: title character(len = 50) :: author character(len = 150) :: subject integer :: book_id end type Books !declaring array of books type(Books), dimension(2) :: list !accessing the components of the structure list(1)%title = “C Programming” list(1)%author = “Nuha Ali” list(1)%subject = “C Programming Tutorial” list(1)%book_id = 6495407 list(2)%title = “Telecom Billing” list(2)%author = “Zara Ali” list(2)%subject = “Telecom Billing Tutorial” list(2)%book_id = 6495700 !display book info Print *, list(1)%title Print *, list(1)%author Print *, list(1)%subject Print *, list(1)%book_id Print *, list(1)%title Print *, list(2)%author Print *, list(2)%subject Print *, list(2)%book_id end program deriveDataType When the above code is compiled and executed, it produces the following result − C Programming Nuha Ali C Programming Tutorial 6495407 C Programming Zara Ali Telecom Billing Tutorial 6495700 Print Page Previous Next Advertisements ”;

Fortran – Modules

Fortran – Modules ”; Previous Next A module is like a package where you can keep your functions and subroutines, in case you are writing a very big program, or your functions or subroutines can be used in more than one program. Modules provide you a way of splitting your programs between multiple files. Modules are used for − Packaging subprograms, data and interface blocks. Defining global data that can be used by more than one routine. Declaring variables that can be made available within any routines you choose. Importing a module entirely, for use, into another program or subroutine. Syntax of a Module A module consists of two parts − a specification part for statements declaration a contains part for subroutine and function definitions The general form of a module is − module name [statement declarations] [contains [subroutine and function definitions] ] end module [name] Using a Module into your Program You can incorporate a module in a program or subroutine by the use statement − use name Please note that You can add as many modules as needed, each will be in separate files and compiled separately. A module can be used in various different programs. A module can be used many times in the same program. The variables declared in a module specification part, are global to the module. The variables declared in a module become global variables in any program or routine where the module is used. The use statement can appear in the main program, or any other subroutine or module which uses the routines or variables declared in a particular module. Example The following example demonstrates the concept − Live Demo module constants implicit none real, parameter :: pi = 3.1415926536 real, parameter :: e = 2.7182818285 contains subroutine show_consts() print*, “Pi = “, pi print*, “e = “, e end subroutine show_consts end module constants program module_example use constants implicit none real :: x, ePowerx, area, radius x = 2.0 radius = 7.0 ePowerx = e ** x area = pi * radius**2 call show_consts() print*, “e raised to the power of 2.0 = “, ePowerx print*, “Area of a circle with radius 7.0 = “, area end program module_example When you compile and execute the above program, it produces the following result − Pi = 3.14159274 e = 2.71828175 e raised to the power of 2.0 = 7.38905573 Area of a circle with radius 7.0 = 153.938049 Accessibility of Variables and Subroutines in a Module By default, all the variables and subroutines in a module is made available to the program that is using the module code, by the use statement. However, you can control the accessibility of module code using the private and public attributes. When you declare some variable or subroutine as private, it is not available outside the module. Example The following example illustrates the concept − In the previous example, we had two module variables, e and pi. Let us make them private and observe the output − Live Demo module constants implicit none real, parameter,private :: pi = 3.1415926536 real, parameter, private :: e = 2.7182818285 contains subroutine show_consts() print*, “Pi = “, pi print*, “e = “, e end subroutine show_consts end module constants program module_example use constants implicit none real :: x, ePowerx, area, radius x = 2.0 radius = 7.0 ePowerx = e ** x area = pi * radius**2 call show_consts() print*, “e raised to the power of 2.0 = “, ePowerx print*, “Area of a circle with radius 7.0 = “, area end program module_example When you compile and execute the above program, it gives the following error message − ePowerx = e ** x 1 Error: Symbol ”e” at (1) has no IMPLICIT type main.f95:19.13: area = pi * radius**2 1 Error: Symbol ”pi” at (1) has no IMPLICIT type Since e and pi, both are declared private, the program module_example cannot access these variables anymore. However, other module subroutines can access them − Live Demo module constants implicit none real, parameter,private :: pi = 3.1415926536 real, parameter, private :: e = 2.7182818285 contains subroutine show_consts() print*, “Pi = “, pi print*, “e = “, e end subroutine show_consts function ePowerx(x)result(ePx) implicit none real::x real::ePx ePx = e ** x end function ePowerx function areaCircle(r)result(a) implicit none real::r real::a a = pi * r**2 end function areaCircle end module constants program module_example use constants implicit none call show_consts() Print*, “e raised to the power of 2.0 = “, ePowerx(2.0) print*, “Area of a circle with radius 7.0 = “, areaCircle(7.0) end program module_example When you compile and execute the above program, it produces the following result − Pi = 3.14159274 e = 2.71828175 e raised to the power of 2.0 = 7.38905573 Area of a circle with radius 7.0 = 153.938049 Print Page Previous Next Advertisements ”;

Fortran – Procedures

Fortran – Procedures ”; Previous Next A procedure is a group of statements that perform a well-defined task and can be invoked from your program. Information (or data) is passed to the calling program, to the procedure as arguments. There are two types of procedures − Functions Subroutines Function A function is a procedure that returns a single quantity. A function should not modify its arguments. The returned quantity is known as function value, and it is denoted by the function name. Syntax Syntax for a function is as follows − function name(arg1, arg2, ….) [declarations, including those for the arguments] [executable statements] end function [name] The following example demonstrates a function named area_of_circle. It calculates the area of a circle with radius r. Live Demo program calling_func real :: a a = area_of_circle(2.0) Print *, “The area of a circle with radius 2.0 is” Print *, a end program calling_func ! this function computes the area of a circle with radius r function area_of_circle (r) ! function result implicit none ! dummy arguments real :: area_of_circle ! local variables real :: r real :: pi pi = 4 * atan (1.0) area_of_circle = pi * r**2 end function area_of_circle When you compile and execute the above program, it produces the following result − The area of a circle with radius 2.0 is 12.5663710 Please note that − You must specify implicit none in both the main program as well as the procedure. The argument r in the called function is called dummy argument. The result Option If you want the returned value to be stored in some other name than the function name, you can use the result option. You can specify the return variable name as − function name(arg1, arg2, ….) result (return_var_name) [declarations, including those for the arguments] [executable statements] end function [name] Subroutine A subroutine does not return a value, however it can modify its arguments. Syntax subroutine name(arg1, arg2, ….) [declarations, including those for the arguments] [executable statements] end subroutine [name] Calling a Subroutine You need to invoke a subroutine using the call statement. The following example demonstrates the definition and use of a subroutine swap, that changes the values of its arguments. Live Demo program calling_func implicit none real :: a, b a = 2.0 b = 3.0 Print *, “Before calling swap” Print *, “a = “, a Print *, “b = “, b call swap(a, b) Print *, “After calling swap” Print *, “a = “, a Print *, “b = “, b end program calling_func subroutine swap(x, y) implicit none real :: x, y, temp temp = x x = y y = temp end subroutine swap When you compile and execute the above program, it produces the following result − Before calling swap a = 2.00000000 b = 3.00000000 After calling swap a = 3.00000000 b = 2.00000000 Specifying the Intent of the Arguments The intent attribute allows you to specify the intention with which arguments are used in the procedure. The following table provides the values of the intent attribute − Value Used as Explanation in intent(in) Used as input values, not changed in the function out intent(out) Used as output value, they are overwritten inout intent(inout) Arguments are both used and overwritten The following example demonstrates the concept − Live Demo program calling_func implicit none real :: x, y, z, disc x = 1.0 y = 5.0 z = 2.0 call intent_example(x, y, z, disc) Print *, “The value of the discriminant is” Print *, disc end program calling_func subroutine intent_example (a, b, c, d) implicit none ! dummy arguments real, intent (in) :: a real, intent (in) :: b real, intent (in) :: c real, intent (out) :: d d = b * b – 4.0 * a * c end subroutine intent_example When you compile and execute the above program, it produces the following result − The value of the discriminant is 17.0000000 Recursive Procedures Recursion occurs when a programming languages allows you to call a function inside the same function. It is called recursive call of the function. When a procedure calls itself, directly or indirectly, is called a recursive procedure. You should declare this type of procedures by preceding the word recursive before its declaration. When a function is used recursively, the result option has to be used. Following is an example, which calculates factorial for a given number using a recursive procedure − program calling_func implicit none integer :: i, f i = 15 Print *, “The value of factorial 15 is” f = myfactorial(15) Print *, f end program calling_func ! computes the factorial of n (n!) recursive function myfactorial (n) result (fac) ! function result implicit none ! dummy arguments integer :: fac integer, intent (in) :: n select case (n) case (0:1) fac = 1 case default fac = n * myfactorial (n-1) end select end function myfactorial Internal Procedures When a procedure is contained within a program, it is called the internal procedure of the program. The syntax for containing an internal procedure is as follows − program program_name implicit none ! type declaration statements ! executable statements . . . contains ! internal procedures . . . end program program_name The following example demonstrates the concept − Live Demo program mainprog implicit none real :: a, b a = 2.0 b = 3.0 Print *, “Before calling swap” Print *, “a = “, a Print *, “b = “, b call swap(a, b) Print *, “After calling swap” Print *, “a = “, a Print *, “b = “, b contains subroutine swap(x, y) real :: x, y, temp temp = x x = y y = temp end subroutine swap end program mainprog When you compile and execute the above program, it produces the following result − Before calling swap a = 2.00000000 b = 3.00000000 After calling swap a = 3.00000000 b = 2.00000000 Print Page

Fortran – Basic Syntax

Fortran – Basic Syntax ”; Previous Next A Fortran program is made of a collection of program units like a main program, modules, and external subprograms or procedures. Each program contains one main program and may or may not contain other program units. The syntax of the main program is as follows − program program_name implicit none ! type declaration statements ! executable statements end program program_name A Simple Program in Fortran Let’s write a program that adds two numbers and prints the result − Live Demo program addNumbers ! This simple program adds two numbers implicit none ! Type declarations real :: a, b, result ! Executable statements a = 12.0 b = 15.0 result = a + b print *, ”The total is ”, result end program addNumbers When you compile and execute the above program, it produces the following result − The total is 27.0000000 Please note that − All Fortran programs start with the keyword program and end with the keyword end program, followed by the name of the program. The implicit none statement allows the compiler to check that all your variable types are declared properly. You must always use implicit none at the start of every program. Comments in Fortran are started with the exclamation mark (!), as all characters after this (except in a character string) are ignored by the compiler. The print * command displays data on the screen. Indentation of code lines is a good practice for keeping a program readable. Fortran allows both uppercase and lowercase letters. Fortran is case-insensitive, except for string literals. Basics The basic character set of Fortran contains − the letters A … Z and a … z the digits 0 … 9 the underscore (_) character the special characters = : + blank – * / ( ) [ ] , . $ ” ! ” % & ; < > ? Tokens are made of characters in the basic character set. A token could be a keyword, an identifier, a constant, a string literal, or a symbol. Program statements are made of tokens. Identifier An identifier is a name used to identify a variable, procedure, or any other user-defined item. 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 Keywords Keywords are special words, reserved for the language. These reserved words cannot be used as identifiers or names. The following table, lists the Fortran keywords − The non-I/O keywords allocatable allocate assign assignment block data call case character common complex contains continue cycle data deallocate default do double precision else else if elsewhere end block data end do end function end if end interface end module end program end select end subroutine end type end where entry equivalence exit external function go to if implicit in inout integer intent interface intrinsic kind len logical module namelist nullify only operator optional out parameter pause pointer private program public real recursive result return save select case stop subroutine target then type type() use Where While The I/O related keywords backspace close endfile format inquire open print read rewind Write Print Page Previous Next Advertisements ”;