Fortran – Loops

Fortran – Loops ”; Previous Next There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially : The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Fortran provides the following types of loop constructs to handle looping requirements. Click the following links to check their detail. Sr.No Loop Type & Description 1 do loop This construct enables a statement, or a series of statements, to be carried out iteratively, while a given condition is true. 2 do while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 3 nested loops You can use one or more loop construct inside any other loop construct. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Fortran supports the following control statements. Click the following links to check their detail. Sr.No Control Statement & Description 1 exit If the exit statement is executed, the loop is exited, and the execution of the program continues at the first executable statement after the end do statement. 2 cycle If a cycle statement is executed, the program continues at the start of the next iteration. 3 stop If you wish execution of your program to stop, you can insert a stop statement Print Page Previous Next Advertisements ”;

Fortran – Arrays

Fortran – Arrays ”; Previous Next Arrays can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Numbers(1) Numbers(2) Numbers(3) Numbers(4) … Arrays can be one- dimensional (like vectors), two-dimensional (like matrices) and Fortran allows you to create up to 7-dimensional arrays. Declaring Arrays Arrays are declared with the dimension attribute. For example, to declare a one-dimensional array named number, of real numbers containing 5 elements, you write, real, dimension(5) :: numbers The individual elements of arrays are referenced by specifying their subscripts. The first element of an array has a subscript of one. The array numbers contains five real variables –numbers(1), numbers(2), numbers(3), numbers(4), and numbers(5). To create a 5 x 5 two-dimensional array of integers named matrix, you write − integer, dimension (5,5) :: matrix You can also declare an array with some explicit lower bound, for example − real, dimension(2:6) :: numbers integer, dimension (-3:2,0:4) :: matrix Assigning Values You can either assign values to individual members, like, numbers(1) = 2.0 or, you can use a loop, do i =1,5 numbers(i) = i * 2.0 end do One-dimensional array elements can be directly assigned values using a short hand symbol, called array constructor, like, numbers = (/1.5, 3.2,4.5,0.9,7.2 /) please note that there are no spaces allowed between the brackets ‘( ‘and the back slash ‘/’ Example The following example demonstrates the concepts discussed above. Live Demo program arrayProg real :: numbers(5) !one dimensional integer array integer :: matrix(3,3), i , j !two dimensional real array !assigning some values to the array numbers do i=1,5 numbers(i) = i * 2.0 end do !display the values do i = 1, 5 Print *, numbers(i) end do !assigning some values to the array matrix do i=1,3 do j = 1, 3 matrix(i, j) = i+j end do end do !display the values do i=1,3 do j = 1, 3 Print *, matrix(i,j) end do end do !short hand assignment numbers = (/1.5, 3.2,4.5,0.9,7.2 /) !display the values do i = 1, 5 Print *, numbers(i) end do end program arrayProg When the above code is compiled and executed, it produces the following result − 2.00000000 4.00000000 6.00000000 8.00000000 10.0000000 2 3 4 3 4 5 4 5 6 1.50000000 3.20000005 4.50000000 0.899999976 7.19999981 Some Array Related Terms The following table gives some array related terms − Term Meaning Rank It is the number of dimensions an array has. For example, for the array named matrix, rank is 2, and for the array named numbers, rank is 1. Extent It is the number of elements along a dimension. For example, the array numbers has extent 5 and the array named matrix has extent 3 in both dimensions. Shape The shape of an array is a one-dimensional integer array, containing the number of elements (the extent) in each dimension. For example, for the array matrix, shape is (3, 3) and the array numbers it is (5). Size It is the number of elements an array contains. For the array matrix, it is 9, and for the array numbers, it is 5. Passing Arrays to Procedures You can pass an array to a procedure as an argument. The following example demonstrates the concept − Live Demo program arrayToProcedure implicit none integer, dimension (5) :: myArray integer :: i call fillArray (myArray) call printArray(myArray) end program arrayToProcedure subroutine fillArray (a) implicit none integer, dimension (5), intent (out) :: a ! local variables integer :: i do i = 1, 5 a(i) = i end do end subroutine fillArray subroutine printArray(a) integer, dimension (5) :: a integer::i do i = 1, 5 Print *, a(i) end do end subroutine printArray When the above code is compiled and executed, it produces the following result − 1 2 3 4 5 In the above example, the subroutine fillArray and printArray can only be called with arrays with dimension 5. However, to write subroutines that can be used for arrays of any size, you can rewrite it using the following technique − Live Demo program arrayToProcedure implicit none integer, dimension (10) :: myArray integer :: i interface subroutine fillArray (a) integer, dimension(:), intent (out) :: a integer :: i end subroutine fillArray subroutine printArray (a) integer, dimension(:) :: a integer :: i end subroutine printArray end interface call fillArray (myArray) call printArray(myArray) end program arrayToProcedure subroutine fillArray (a) implicit none integer,dimension (:), intent (out) :: a ! local variables integer :: i, arraySize arraySize = size(a) do i = 1, arraySize a(i) = i end do end subroutine fillArray subroutine printArray(a) implicit none integer,dimension (:) :: a integer::i, arraySize arraySize = size(a) do i = 1, arraySize Print *, a(i) end do end subroutine printArray Please note that the program is using the size function to get the size of the array. When the above code is compiled and executed, it produces the following result − 1 2 3 4 5 6 7 8 9 10 Array Sections So far we have referred to the whole array, Fortran provides an easy way to refer several elements, or a section of an array, using a single statement. To access an array section, you need to provide the lower and the upper bound of the section, as well as a stride (increment), for all the dimensions. This notation is called a subscript triplet: array ([lower]:[upper][:stride], …) When no lower and upper bounds are mentioned, it defaults to the extents you declared, and stride value defaults to 1. The following example demonstrates the concept − Live Demo program arraySubsection real, dimension(10) :: a, b integer:: i, asize, bsize a(1:7) = 5.0 ! a(1) to a(7) assigned 5.0 a(8:) = 0.0 !

Fortran – Constants

Fortran – Constants ”; Previous Next The constants refer to the fixed values that the program cannot alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, a complex constant, or a string literal. There are only two logical constants : .true. and .false. The constants are treated just like regular variables, except that their values cannot be modified after their definition. Named Constants and Literals There are two types of constants − Literal constants Named constants A literal constant have a value, but no name. For example, following are the literal constants − Type Example Integer constants 0 1 -1 300 123456789 Real constants 0.0 1.0 -1.0 123.456 7.1E+10 -52.715E-30 Complex constants (0.0, 0.0) (-123.456E+30, 987.654E-29) Logical constants .true. .false. Character constants “PQR” “a” “123”abc$%#@!” ” a quote “” “ ”PQR” ”a” ”123″abc$%#@!” ” an apostrophe ”” ” A named constant has a value as well as a name. Named constants should be declared at the beginning of a program or procedure, just like a variable type declaration, indicating its name and type. Named constants are declared with the parameter attribute. For example, real, parameter :: pi = 3.1415927 Example The following program calculates the displacement due to vertical motion under gravity. Live Demo program gravitationalDisp ! this program calculates vertical motion under gravity implicit none ! gravitational acceleration real, parameter :: g = 9.81 ! variable declaration real :: s ! displacement real :: t ! time real :: u ! initial speed ! assigning values t = 5.0 u = 50 ! displacement s = u * t – g * (t**2) / 2 ! output print *, “Time = “, t print *, ”Displacement = ”,s end program gravitationalDisp When the above code is compiled and executed, it produces the following result − Time = 5.00000000 Displacement = 127.374992 Print Page Previous Next Advertisements ”;

Fortran – Pointers

Fortran – Pointers ”; Previous Next In most programming languages, a pointer variable stores the memory address of an object. However, in Fortran, a pointer is a data object that has more functionalities than just storing the memory address. It contains more information about a particular object, like type, rank, extents, and memory address. A pointer is associated with a target by allocation or pointer assignment. Declaring a Pointer Variable A pointer variable is declared with the pointer attribute. The following examples shows declaration of pointer variables − integer, pointer :: p1 ! pointer to integer real, pointer, dimension (:) :: pra ! pointer to 1-dim real array real, pointer, dimension (:,:) :: pra2 ! pointer to 2-dim real array A pointer can point to − An area of dynamically allocated memory. A data object of the same type as the pointer, with the target attribute. Allocating Space for a Pointer The allocate statement allows you to allocate space for a pointer object. For example − Live Demo program pointerExample implicit none integer, pointer :: p1 allocate(p1) p1 = 1 Print *, p1 p1 = p1 + 4 Print *, p1 end program pointerExample When the above code is compiled and executed, it produces the following result − 1 5 You should empty the allocated storage space by the deallocate statement when it is no longer required and avoid accumulation of unused and unusable memory space. Targets and Association A target is another normal variable, with space set aside for it. A target variable must be declared with the target attribute. You associate a pointer variable with a target variable using the association operator (=>). Let us rewrite the previous example, to demonstrate the concept − Live Demo program pointerExample implicit none integer, pointer :: p1 integer, target :: t1 p1=>t1 p1 = 1 Print *, p1 Print *, t1 p1 = p1 + 4 Print *, p1 Print *, t1 t1 = 8 Print *, p1 Print *, t1 end program pointerExample When the above code is compiled and executed, it produces the following result − 1 1 5 5 8 8 A pointer can be − Undefined Associated Disassociated In the above program, we have associated the pointer p1, with the target t1, using the => operator. The function associated, tests a pointer’s association status. The nullify statement disassociates a pointer from a target. Nullify does not empty the targets as there could be more than one pointer pointing to the same target. However, emptying the pointer implies nullification also. Example 1 The following example demonstrates the concepts − Live Demo program pointerExample implicit none integer, pointer :: p1 integer, target :: t1 integer, target :: t2 p1=>t1 p1 = 1 Print *, p1 Print *, t1 p1 = p1 + 4 Print *, p1 Print *, t1 t1 = 8 Print *, p1 Print *, t1 nullify(p1) Print *, t1 p1=>t2 Print *, associated(p1) Print*, associated(p1, t1) Print*, associated(p1, t2) !what is the value of p1 at present Print *, p1 Print *, t2 p1 = 10 Print *, p1 Print *, t2 end program pointerExample When the above code is compiled and executed, it produces the following result − 1 1 5 5 8 8 8 T F T 0 0 10 10 Please note that each time you run the code, the memory addresses will be different. Example 2 Live Demo program pointerExample implicit none integer, pointer :: a, b integer, target :: t integer :: n t = 1 a => t t = 2 b => t n = a + b Print *, a, b, t, n end program pointerExample When the above code is compiled and executed, it produces the following result − 2 2 2 4 Print Page Previous Next Advertisements ”;

Fortran – Basic Input Output

Fortran – Basic Input Output ”; Previous Next We have so far seen that we can read data from keyboard using the read * statement, and display output to the screen using the print* statement, respectively. This form of input-output is free format I/O, and it is called list-directed input-output. The free format simple I/O has the form − read(*,*) item1, item2, item3… print *, item1, item2, item3 write(*,*) item1, item2, item3… However the formatted I/O gives you more flexibility over data transfer. Formatted Input Output Formatted input output has the syntax as follows − read fmt, variable_list print fmt, variable_list write fmt, variable_list Where, fmt is the format specification variable-list is a list of the variables to be read from keyboard or written on screen Format specification defines the way in which formatted data is displayed. It consists of a string, containing a list of edit descriptors in parentheses. An edit descriptor specifies the exact format, for example, width, digits after decimal point etc., in which characters and numbers are displayed. For example Print “(f6.3)”, pi The following table describes the descriptors − Descriptor Description Example I This is used for integer output. This takes the form ‘rIw.m’ where the meanings of r, w and m are given in the table below. Integer values are right justified in their fields. If the field width is not large enough to accommodate an integer then the field is filled with asterisks. print “(3i5)”, i, j, k F This is used for real number output. This takes the form ‘rFw.d’ where the meanings of r, w and d are given in the table below. Real values are right justified in their fields. If the field width is not large enough to accommodate the real number then the field is filled with asterisks. print “(f12.3)”,pi E This is used for real output in exponential notation. The ‘E’ descriptor statement takes the form ‘rEw.d’ where the meanings of r, w and d are given in the table below. Real values are right justified in their fields. If the field width is not large enough to accommodate the real number then the field is filled with asterisks. Please note that, to print out a real number with three decimal places a field width of at least ten is needed. One for the sign of the mantissa, two for the zero, four for the mantissa and two for the exponent itself. In general, w ≥ d + 7. print “(e10.3)”,123456.0 gives ‘0.123e+06’ ES This is used for real output (scientific notation). This takes the form ‘rESw.d’ where the meanings of r, w and d are given in the table below. The ‘E’ descriptor described above differs slightly from the traditional well known ‘scientific notation’. Scientific notation has the mantissa in the range 1.0 to 10.0 unlike the E descriptor which has the mantissa in the range 0.1 to 1.0. Real values are right justified in their fields. If the field width is not large enough to accommodate the real number then the field is filled with asterisks. Here also, the width field must satisfy the expressionw ≥ d + 7 print “(es10.3)”,123456.0 gives ‘1.235e+05’ A This is used for character output. This takes the form ‘rAw’ where the meanings of r and w are given in the table below. Character types are right justified in their fields. If the field width is not large enough to accommodate the character string then the field is filled with the first ‘w’ characters of the string. print “(a10)”, str X This is used for space output. This takes the form ‘nX’ where ‘n’ is the number of desired spaces. print “(5x, a10)”, str / Slash descriptor – used to insert blank lines. This takes the form ‘/’ and forces the next data output to be on a new line. print “(/,5x, a10)”, str Following symbols are used with the format descriptors − Sr.No Symbol & Description 1 c Column number 2 d Number of digits to right of the decimal place for real input or output 3 m Minimum number of digits to be displayed 4 n Number of spaces to skip 5 r Repeat count – the number of times to use a descriptor or group of descriptors 6 w Field width – the number of characters to use for the input or output Example 1 Live Demo program printPi pi = 3.141592653589793238 Print “(f6.3)”, pi Print “(f10.7)”, pi Print “(f20.15)”, pi Print “(e16.4)”, pi/100 end program printPi When the above code is compiled and executed, it produces the following result − 3.142 3.1415927 3.141592741012573 0.3142E-01 Example 2 program printName implicit none character (len = 15) :: first_name print *,” Enter your first name.” print *,” Up to 20 characters, please” read *,first_name print “(1x,a)”,first_name end program printName When the above code is compiled and executed, it produces the following result: (assume the user enters the name Zara) Enter your first name. Up to 20 characters, please Zara Example 3 Live Demo program formattedPrint implicit none real :: c = 1.2786456e-9, d = 0.1234567e3 integer :: n = 300789, k = 45, i = 2 character (len=15) :: str=”Tutorials Point” print “(i6)”, k print “(i6.3)”, k print “(3i10)”, n, k, i print “(i10,i3,i5)”, n, k, i print “(a15)”,str print “(f12.3)”, d print “(e12.4)”, c print ”(/,3x,”n = “,i6, 3x, “d = “,f7.4)”, n, d end program formattedPrint When the above code is compiled and executed, it produces the following result − 45 045 300789 45 2 300789 45 2 Tutorials Point 123.457 0.1279E-08 n = 300789 d = ******* The Format Statement The format statement allows you to mix and match character, integer and real output in one statement. The following example demonstrates this − Live Demo program productDetails implicit none character (len = 15) :: name integer :: id real :: weight name = ”Ardupilot” id = 1 weight = 0.08 print *,” The product details are” print 100 100 format (7x,”Name:”, 7x,

Fortran – Strings

Fortran – Strings ”; Previous Next The Fortran language can treat characters as single character or contiguous strings. A character string may be only one character in length, or it could even be of zero length. In Fortran, character constants are given between a pair of double or single quotes. 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. String Declaration Declaring a string is same as other variables − type-specifier :: variable_name For example, Character(len = 20) :: firstname, surname you can assign a value like, character (len = 40) :: name name = “Zara Ali” 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. Beans” 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 isMr. Rowan Atkinson A big hello from Mr. Bean String Concatenation The concatenation operator //, concatenates strings. 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. Beans” 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 Extracting Substrings In Fortran, you can extract a substring from a string by indexing the string, giving the start and the end index of the substring in a pair of brackets. This is called extent specifier. The following example shows how to extract the substring ‘world’ from the string ‘hello world’ − Live Demo program subString character(len = 11)::hello hello = “Hello World” print*, hello(7:11) end program subString When you compile and execute the above program it produces the following result − World Example The following example uses the date_and_time function to give the date and time string. We use extent specifiers to extract the year, date, month, hour, minutes and second information separately. Live Demo program datetime implicit none character(len = 8) :: dateinfo ! ccyymmdd character(len = 4) :: year, month*2, day*2 character(len = 10) :: timeinfo ! hhmmss.sss character(len = 2) :: hour, minute, second*6 call date_and_time(dateinfo, timeinfo) ! let’s break dateinfo into year, month and day. ! dateinfo has a form of ccyymmdd, where cc = century, yy = year ! mm = month and dd = day year = dateinfo(1:4) month = dateinfo(5:6) day = dateinfo(7:8) print*, ”Date String:”, dateinfo print*, ”Year:”, year print *,”Month:”, month print *,”Day:”, day ! let’s break timeinfo into hour, minute and second. ! timeinfo has a form of hhmmss.sss, where h = hour, m = minute ! and s = second hour = timeinfo(1:2) minute = timeinfo(3:4) second = timeinfo(5:10) print*, ”Time String:”, timeinfo print*, ”Hour:”, hour print*, ”Minute:”, minute print*, ”Second:”, second end program datetime When you compile and execute the above program, it gives the detailed date and time information − Date String: 20140803 Year: 2014 Month: 08 Day: 03 Time String: 075835.466 Hour: 07 Minute: 58 Second: 35.466 Trimming Strings The trim function takes a string, and returns the input string after removing all trailing blanks. Example Live Demo program trimString implicit none character (len = *), parameter :: fname=”Susanne”, sname=”Rizwan” character (len = 20) :: fullname fullname = fname//” “//sname !concatenating the strings print*,fullname,”, the beautiful dancer from the east!” print*,trim(fullname),”, the beautiful dancer from the east!” end program trimString When you compile and execute the above program it produces the following result − Susanne Rizwan , the beautiful dancer from the east! Susanne Rizwan, the beautiful dancer from the east! Left and Right Adjustment of Strings The function adjustl takes a string and returns it by removing the leading blanks and appending them as trailing blanks. The function adjustr takes a string and returns it by removing the trailing blanks and appending them as leading blanks. Example 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” greetings = ”A big hello from Mr. Beans” name = adjustl(title)//adjustl(firstname)//adjustl(surname) print *, ”Here is”, name print *, greetings name = adjustr(title)//adjustr(firstname)//adjustr(surname) print *, ”Here is”, name print *, greetings name = trim(title)//trim(firstname)//trim(surname) 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 Here is Mr. Rowan Atkinson A big hello from Mr. Bean Here is Mr.RowanAtkinson A big hello from Mr. Bean Searching for a Substring in a String The index function takes two strings and checks if the second string is a substring of the first string. If the second argument is a substring of the first argument, then it returns an integer which is the starting index of the second string in the first string, else it returns zero. Example Live Demo program hello implicit none character(len=30) :: myString character(len=10) :: testString myString = ”This is a test” testString = ”test” if(index(myString, testString) == 0)then print *, ”test is not found” else print *, ”test is found at index: ”, index(myString, testString) end if end program hello When you compile and execute the above program it produces the following result − test is found

Fortran – Debugging Program

Fortran – Debugging Program ”; Previous Next A debugger tool is used to search for errors in the programs. A debugger program steps through the code and allows you to examine the values in the variables and other data objects during execution of the program. It loads the source code and you are supposed to run the program within the debugger. Debuggers debug a program by − Setting breakpoints, Stepping through the source code, Setting watch points. Breakpoints specify where the program should stop, specifically after a critical line of code. Program executions after the variables are checked at a breakpoint. Debugger programs also check the source code line by line. Watch points are the points where the values of some variables are needed to be checked, particularly after a read or write operation. The gdb Debugger The gdb debugger, the GNU debugger comes with Linux operating system. For X windows system, gdb comes with a graphical interface and the program is named xxgdb. Following table provides some commands in gdb − Command Purpose break Setting a breakpoint run Starts execution cont Continues execution next Executes only the next line of source code, without stepping into any function call step Execute the next line of source code by stepping into a function in case of a function call. The dbx Debugger There is another debugger, the dbx debugger, for Linux. The following table provides some commands in dbx − Command Purpose stop[var] Sets a breakpoint when the value of variable var changes. stop in [proc] It stops execution when a procedure proc is entered stop at [line] It sets a breakpoint at a specified line. run Starts execution. cont Continues execution. next Executes only the next line of source code, without stepping into any function call. step Execute the next line of source code by stepping into a function in case of a function call. Print Page Previous Next Advertisements ”;

Fortran – Program Libraries

Fortran – Program Libraries ”; Previous Next There are various Fortran tools and libraries. Some are free and some are paid services. Following are some free libraries − RANDLIB, random number and statistical distribution generators BLAS EISPACK GAMS–NIST Guide to Available Math Software Some statistical and other routines from NIST LAPACK LINPACK MINPACK MUDPACK NCAR Mathematical Library The Netlib collection of mathematical software, papers, and databases. ODEPACK ODERPACK, a set of routines for ranking and ordering. Expokit for computing matrix exponentials SLATEC SPECFUN STARPAC StatLib statistical library TOMS Sorting and merging strings The following libraries are not free − The NAG Fortran numerical library The Visual Numerics IMSL library Numerical Recipes Print Page Previous Next Advertisements ”;

Fortran – Intrinsic Functions

Fortran – Intrinsic Functions ”; Previous Next Intrinsic functions are some common and important functions that are provided as a part of the Fortran language. We have already discussed some of these functions in the Arrays, Characters and String chapters. Intrinsic functions can be categorised as − Numeric Functions Mathematical Functions Numeric Inquiry Functions Floating-Point Manipulation Functions Bit Manipulation Functions Character Functions Kind Functions Logical Functions Array Functions. We have discussed the array functions in the Arrays chapter. In the following section we provide brief descriptions of all these functions from other categories. In the function name column, A represents any type of numeric variable R represents a real or integer variable X and Y represent real variables Z represents complex variable W represents real or complex variable Numeric Functions Sr.No Function & Description 1 ABS (A) It returns the absolute value of A 2 AIMAG (Z) It returns the imaginary part of a complex number Z 3 AINT (A [, KIND]) It truncates fractional part of A towards zero, returning a real, whole number. 4 ANINT (A [, KIND]) It returns a real value, the nearest integer or whole number. 5 CEILING (A [, KIND]) It returns the least integer greater than or equal to number A. 6 CMPLX (X [, Y, KIND]) It converts the real variables X and Y to a complex number X+iY; if Y is absent, 0 is used. 7 CONJG (Z) It returns the complex conjugate of any complex number Z. 8 DBLE (A) It converts A to a double precision real number. 9 DIM (X, Y) It returns the positive difference of X and Y. 10 DPROD (X, Y) It returns the double precision real product of X and Y. 11 FLOOR (A [, KIND]) It provides the greatest integer less than or equal to number A. 12 INT (A [, KIND]) It converts a number (real or integer) to integer, truncating the real part towards zero. 13 MAX (A1, A2 [, A3,…]) It returns the maximum value from the arguments, all being of same type. 14 MIN (A1, A2 [, A3,…]) It returns the minimum value from the arguments, all being of same type. 15 MOD (A, P) It returns the remainder of A on division by P, both arguments being of the same type (A-INT(A/P)*P) 16 MODULO (A, P) It returns A modulo P: (A-FLOOR(A/P)*P) 17 NINT (A [, KIND]) It returns the nearest integer of number A 18 REAL (A [, KIND]) It Converts to real type 19 SIGN (A, B) It returns the absolute value of A multiplied by the sign of P. Basically it transfers the of sign of B to A. Example Live Demo program numericFunctions implicit none ! define constants ! define variables real :: a, b complex :: z ! values for a, b a = 15.2345 b = -20.7689 write(*,*) ”abs(a): ”,abs(a),” abs(b): ”,abs(b) write(*,*) ”aint(a): ”,aint(a),” aint(b): ”,aint(b) write(*,*) ”ceiling(a): ”,ceiling(a),” ceiling(b): ”,ceiling(b) write(*,*) ”floor(a): ”,floor(a),” floor(b): ”,floor(b) z = cmplx(a, b) write(*,*) ”z: ”,z end program numericFunctions When you compile and execute the above program, it produces the following result − abs(a): 15.2344999 abs(b): 20.7688999 aint(a): 15.0000000 aint(b): -20.0000000 ceiling(a): 16 ceiling(b): -20 floor(a): 15 floor(b): -21 z: (15.2344999, -20.7688999) Mathematical Functions Sr.No Function & Description 1 ACOS (X) It returns the inverse cosine in the range (0, π), in radians. 2 ASIN (X) It returns the inverse sine in the range (-π/2, π/2), in radians. 3 ATAN (X) It returns the inverse tangent in the range (-π/2, π/2), in radians. 4 ATAN2 (Y, X) It returns the inverse tangent in the range (-π, π), in radians. 5 COS (X) It returns the cosine of argument in radians. 6 COSH (X) It returns the hyperbolic cosine of argument in radians. 7 EXP (X) It returns the exponential value of X. 8 LOG (X) It returns the natural logarithmic value of X. 9 LOG10 (X) It returns the common logarithmic (base 10) value of X. 10 SIN (X) It returns the sine of argument in radians. 11 SINH (X) It returns the hyperbolic sine of argument in radians. 12 SQRT (X) It returns square root of X. 13 TAN (X) It returns the tangent of argument in radians. 14 TANH (X) It returns the hyperbolic tangent of argument in radians. Example The following program computes the horizontal and vertical position x and y respectively of a projectile after a time, t − Where, x = u t cos a and y = u t sin a – g t2 / 2 Live Demo program projectileMotion implicit none ! define constants real, parameter :: g = 9.8 real, parameter :: pi = 3.1415927 !define variables real :: a, t, u, x, y !values for a, t, and u a = 45.0 t = 20.0 u = 10.0 ! convert angle to radians a = a * pi / 180.0 x = u * cos(a) * t y = u * sin(a) * t – 0.5 * g * t * t write(*,*) ”x: ”,x,” y: ”,y end program projectileMotion When you compile and execute the above program, it produces the following result − x: 141.421356 y: -1818.57861 Numeric Inquiry Functions These functions work with a certain model of integer and floating-point arithmetic. The functions return properties of numbers of the same kind as the variable X, which can be real and in some cases integer. Sr.No Function & Description 1 DIGITS (X) It returns the number of significant digits of the model. 2 EPSILON (X) It returns the number that is almost negligible compared to one. In other words, it returns the smallest value such that REAL( 1.0, KIND(X)) + EPSILON(X) is not equal to REAL( 1.0, KIND(X)). 3 HUGE (X) It returns the largest number of the model 4 MAXEXPONENT (X) It returns the maximum exponent of the model 5 MINEXPONENT (X) It returns the minimum exponent of the model 6 PRECISION (X) It returns the decimal precision 7

Fortran – Dynamic Arrays

Fortran – Dynamic Arrays ”; Previous Next A dynamic array is an array, the size of which is not known at compile time, but will be known at execution time. Dynamic arrays are declared with the attribute allocatable. For example, real, dimension (:,:), allocatable :: darray The rank of the array, i.e., the dimensions has to be mentioned however, to allocate memory to such an array, you use the allocate function. allocate ( darray(s1,s2) ) After the array is used, in the program, the memory created should be freed using the deallocate function deallocate (darray) Example The following example demonstrates the concepts discussed above. program dynamic_array implicit none !rank is 2, but size not known real, dimension (:,:), allocatable :: darray integer :: s1, s2 integer :: i, j print*, “Enter the size of the array:” read*, s1, s2 ! allocate memory allocate ( darray(s1,s2) ) do i = 1, s1 do j = 1, s2 darray(i,j) = i*j print*, “darray(“,i,”,”,j,”) = “, darray(i,j) end do end do deallocate (darray) end program dynamic_array When the above code is compiled and executed, it produces the following result − Enter the size of the array: 3,4 darray( 1 , 1 ) = 1.00000000 darray( 1 , 2 ) = 2.00000000 darray( 1 , 3 ) = 3.00000000 darray( 1 , 4 ) = 4.00000000 darray( 2 , 1 ) = 2.00000000 darray( 2 , 2 ) = 4.00000000 darray( 2 , 3 ) = 6.00000000 darray( 2 , 4 ) = 8.00000000 darray( 3 , 1 ) = 3.00000000 darray( 3 , 2 ) = 6.00000000 darray( 3 , 3 ) = 9.00000000 darray( 3 , 4 ) = 12.0000000 Use of Data Statement The data statement can be used for initialising more than one array, or for array section initialisation. The syntax of data statement is − data variable / list / … Example The following example demonstrates the concept − Live Demo program dataStatement implicit none integer :: a(5), b(3,3), c(10),i, j data a /7,8,9,10,11/ data b(1,:) /1,1,1/ data b(2,:)/2,2,2/ data b(3,:)/3,3,3/ data (c(i),i = 1,10,2) /4,5,6,7,8/ data (c(i),i = 2,10,2)/5*2/ Print *, ”The A array:” do j = 1, 5 print*, a(j) end do Print *, ”The B array:” do i = lbound(b,1), ubound(b,1) write(*,*) (b(i,j), j = lbound(b,2), ubound(b,2)) end do Print *, ”The C array:” do j = 1, 10 print*, c(j) end do end program dataStatement When the above code is compiled and executed, it produces the following result − The A array: 7 8 9 10 11 The B array: 1 1 1 2 2 2 3 3 3 The C array: 4 2 5 2 6 2 7 2 8 2 Use of Where Statement The where statement allows you to use some elements of an array in an expression, depending on the outcome of some logical condition. It allows the execution of the expression, on an element, if the given condition is true. Example The following example demonstrates the concept − Live Demo program whereStatement implicit none integer :: a(3,5), i , j do i = 1,3 do j = 1, 5 a(i,j) = j-i end do end do Print *, ”The A array:” do i = lbound(a,1), ubound(a,1) write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2)) end do where( a<0 ) a = 1 elsewhere a = 5 end where Print *, ”The A array:” do i = lbound(a,1), ubound(a,1) write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2)) end do end program whereStatement When the above code is compiled and executed, it produces the following result − The A array: 0 1 2 3 4 -1 0 1 2 3 -2 -1 0 1 2 The A array: 5 5 5 5 5 1 5 5 5 5 1 1 5 5 5 Print Page Previous Next Advertisements ”;