Fortran and C

Source: Internet
Author: User

Http://asc.2dark.org/node/45
First, the most content of this article is I read Peng "Fortran 95 program Design" notes. Read only to the Nineth chapter, mainly 3~9 chapter, are the most basic usage (the original book a total of 16 chapters). Here the main excerpt from my reading process summed up some of the Fortran and C different places, mainly in the grammatical aspect. I hope this note can give some help to students who have studied C but have not contacted Fortran. To think more clearly, recommend looking at the original book, think the author is really well written, very clear, if there is a C language Foundation, read the first nine should be very fast, spend one or two days on the line. Feel that if the patience to read this article, the basic functions should also be used smoothly. Outside, because I have not used Fortran before, this time in order to catch the document reading and see very superficial, most things have not been and think carefully after reading, just according to the author's meaning to understand. So this note is still on the level of an armchair. If there is a wrong side, I hope you correct me. Thank you! The blue part of the text is the program code, and the following is a comment.
Ii. Overview 1, noun interpretation fortran=formula translator/translation A look will know what features: can be close to the mathematical language of the text translated into mechanical language. Indeed, from the outset, IBM was designed to facilitate numerical computation and scientific data processing. A powerful array operation is designed to achieve this goal. Ortran lays the foundation for advanced language development. Now Fortran is widely used in scientific research and machinery.
2, the main version of Fortran and the difference according to its development history, Fortran compiler version in fact a lot. It is now widely used in Fortran 77 and Fortran90. Ortran 90 adds a lot of functionality to the Fortran 77, and improves the 77 programming layout format, so it is recommended to use 90 for programming. Given that many of the ready-made programs are only 77 versions, it is necessary to know some basic knowledge of 77, at least to be able to see 77 programs. The following are some of the formatting differences between 77 and 90. Fortran: fixed format, program code extension:. F or. for (1) If a line starts with a c,c or a *, the line is treated as a comment, (2) the first six characters of each line cannot write the program code, can be empty, or 1~ The 5 characters indicate the line code in numbers (used as formatted input, etc.), the 7~72 is the program code writing area, 73 is ignored later, (3) is too long to be continued, the sixth character of the continuation line must be any character other than "0". Fortran: freeform (free format), extension:. F90 (1) with "!" Boot comments, (2) each line can be 132 characters, the line is placed at the front of each line, (3) with & continued, at the end of the line or the beginning of the downward. The following are all discussed in FORTRAN 90.
3, some characteristics of Fortran, and c Some of the differences in fact a lot, in the following specific aspects can be seen. Here are just a few things to mention. (1) no case (2) the end of each sentence does not have to write a semicolon (3) The program code between the command space is meaningless (4) Unlike C,fortran does not use {} (5) Data types are more complex and logical judgement type. For example, plural type complex:: A  ! A method that declares a complex number. The complex number obviously facilitates the scientific calculation, satisfies the engineering aspect demand a= (1.0,2.0)   ! a=1+i (6) More than the exponentiation operation (* *). The exponentiation can be a real number in addition to integers. Open Cube a=4.0**0.5,a=8.0** (1.0/3.0). (7) The array has some functions of the whole operation; it is easy to operate on some elements (8) In some cases it is possible to declare an array of size to be determined, a useful function
 4, the basic program structure of Fortran first look at the so-called "Hello Fortran" program.   Program Main! The procedure begins, and main is the name of programs, fully customizable write (*,*) "Hello"! Main program Stop! Terminate program end [Program[main]] !end is used to encapsulate code, which means that the code is written. The contents of [] may be omitted, hereinafter. Then look at a practical program, a bit of perceptual knowledge. The program is used to calculate the surface area of a cylinder, requiring the input base radius and. It shows some of the features of FORTRAN. The program was excerpted from Wiki. is actually a wiki page called Www.answers.com's online citation. Recommend to go to see! can find a lot of interesting things. Program Cylinder! Give the main function a name! Calculate the area of a cylinder.! Declare Variables and constants.! constants=pi! Variables=radius squared and heightimplicit none! Require all variables to be explicitly declared! this is generally written. This is explained further below. Integer:: ierrcharacter:: ynreal:: Radius, height, areareal, parameter:: PI = 3.1415926536! This is the declaration method of the constant Interactive_loo P:do!do Loop, the loop in Fortran can be tagged, such as the!interactive_loop in front of D is the label 
!    Prompt the user for radius and height 
! and read them.
Write (*,*) ' Enter radius and height. ' Screen output
Read (*,*,iostat=ierr) radius,height! Keyboard input. The value of the Isotat is used to determine whether the input succeeded.
! If radius and height could not being read from input,
! Then cycle through the loop.
if (ierr/= 0) then
Write (*,*) ' Error, invalid input. '
Cycle Interactive_loop!cycle equivalent to the Continue
End If
in C! Compute area. The * * means "raise to a power."
Area = 2 * pi * (radius**2 + radius*height)! The exponential operation is more convenient than C
! Write the input variables (radius, height)
! and output (area) to the screen.
Write (*, ' (1x,a7,f6.2,5x,a7,f6.2,5x,a5,f6.2) ') &
!" & "means to continue the line. Also shown here is the formatted output ' radius= ', radius, ' height= ', height, ' area= ', Areayn = ' Yn_loop:do             ! An embedded another do loop write (*,*) ' Perform Another calculation? Y[n] ' Read (*, ' (A1) ') ynif (yn== ' y '. or. yn== ' y ') exit yn_loopif (yn== ' n '. or. yn== ' n '. or yn== ') exit Interactive_loopen D do yn_loop       ! End the inline do Loop end   do interactive_loop        The main structure of the cylinder FORTRAN program is this way. There are usually some module parts in front of the main function, the function after the main function.
 three, data type and basic input and output 1, data type, declaration and assignment of initial value (1) Integer: Short integer kind=2, long Integer kind=4 integer ([kind=]2):: A=3 if declared as an integer:: A, the default is long integer.! ": : "must be written when declaring and assigning an initial value, and must be preserved when there are adjectives following the type name::; Other things can be omitted!" the so-called adjective, you can look at this. For example, declare constant real,parameter:: pi=3.1415926. parameter is an adjective. (2) Real: Single precision kind=4 (default), double precision kind=8 Real ([kind=]8):: a=3.0 also has exponential form, such as 1E10 for single precision, 1D10 for double precision (3) complex single precision and double precision complex ([ki ND=]4) b (4) character character ([len=]10) c!len for maximum length (5) Logical logical*2:: D=.ture. (Equivalent to Logical (2)::d =.ture.) (6) Custom type: Similar to C in Structfortran 77 to assign the initial value of the variable to the common data command, you can assign a number of variables to the initial value of data A,B,STRING/1, 2.0, ' Fortran '/unlike C, In Fortran, variables are not declared and can be used, i.e. there is a default type (related to the implicit command). By default, variables beginning with i,j,k,l,m,n are defined as integers and the rest is real. Canceling this setting requires implicit none before the program declaration section. This statement is generally used by Peng recommendations. Another point about the declaration is that FORTRAN has an "equivalent declaration": An integer a,bequivalence (A, A, b) that uses the same piece of memory. This saves memory, and sometimes you can streamline the code. such as: equivalence (a variable of a very long name, such as an element of a three-dimensional array, a), then using a to write the program is much more concise. 
2. Basic input/Output input: Read (*,*) a           ! Reads the output from the keyboard    : Write (*,*) "text"! output on the screen. Fortran 77 with ' text '. Fortan 90 in general "" and "can print *," text "               ! can only be used for screen output (*,*) complete write as (unit=*,fmt=*). Where unit is the input/output position, such as screen, file, etc.; FMT is format. If these two items are written in *, then the default way, that is described above. The * at the back of print indicates output in the default format.
Iv. Process Control 1, operator (1) logical operator = =    /=    >    >=   <    <=        ! Fortran 90 usage. EQ.  NE.  . GT.  . GE.  . LT.  . LE.   ! Fortran 77 Usage (2) Sets of operators that involve interrelationships. and.  OR.  . Not:  EQV.  Neqv.  ! Only. not. Connect an expression, and the rest of the left and right side must have an expression (can be a variable of type logical)!. EQV.: When both sides of the logical operation value are true simultaneously. Neqv.: When both sides of the logical operation value are not true at the same time
2. IF

If (logic-judged) then
......

If then there is only one sentence, can be written as
if (logical judgment) ... ! Then and end if can be omitted
(2) Multiple judgments:
if (condition 1) Then
......
else if (condition 2) Then
......
else if (condition 3) Then
......
Else
......
End If
(3) Nesting:
If (logic-judged) then
If (logic-judged) then
If (logic-judged) then
else if (logical-judged) then
......
Else
......
End If
End If
End If
(4) Arithmetic judgment:
program Example
Implicit none
Real C
Write (*,*) "Input a number"
Read (*,*) c
if (c) 10,20,30!10,20 and 30 are line codes, according to C is less than/equal to/greater than 0, the thread that executes the 10/20/30 line
Ten Write (*,*) "A"
Goto !goto can be used to jump to any previous or subsequent line code, but with more damage to the program knot
Write (*,*) "B"
Goto 40
Write (*,*) "C"
Goto 40
Max Stop
End
3. SELECT case
A switch statement similar to C
Select Case (variable)
Case (value 1)! For example, Case (1:5) represents the 1<= variable <=5 executes the module
...... ! Case (1,3,5) means that the variable equals 1 or 3 or 5 executes the module
Case (value 2)! The value in parentheses can only be a integer,character or logical type constant, not a real type
...
Case default
......
End case
4, pause, continuepause suspend the program execution, press ENTER to continue execution continue seemingly useless, can be used as a token of the encapsulation program
V. 1, DOdo counter= initial value, final value, increment/decrement   of!counter values from initial to final value by increasing/decreasing quantity, ...           ! Counter each value corresponds to a loop. The increase/decrease amount does not write that 1      ... ......     ! The loop body is also not necessary to use {} ... end Dofortran 77 does not terminate with end do, but this looks like this: The line code of the last line of the Do Loop  counter= The initial value, the final values, the increase/decrease amount ...      Line code ...       ! This is the last line of do.
2, do whiledo while (logical operation)    ...    ... End do resembles the while (logical operation) in C {...}. In the beginning of the calculation of the cylindrical surface area of the program, it should be considered this category. However, it is controlled by the internal if statement. It seems to be okay, but I don't see it in this book. In fact, it should also be attributed to the following.
3, did not see and C inside the do{...} while (logical operation); The corresponding loop statement, but this can be done to ensure
At least do a loop:
Do while (. ture.)
......
......
The IF (logical operation) Exit !exit is like a break in C. Continue in C is a cycle in FORTRAN.
End do
4, a feature of Fortran: With the signature of the cycle can be so, not easy to error: outer: Do  i=1,3 inner: Do  j=1,3 ... end do innerend do outer can also do this, very convenient: loop 1:do I=1 , 3loop2:do j=1,3if (i==3) exit Loop1     !exit terminates the entire cycle loop1if (j==2) cycle loop2!cycle    jump out of this cycle of LOOP2, The next loop of the Loop2 write (*,*) i,jend do loop2end do LOOP1 also has some loops mainly used in the Fortran array operation, is specific to Fortran, very practical.
Six, array 1, the declaration of the array and C is different, the index value of the array element in Fortran is written in (), and the high dimension is only one (), such as an integer a (5)   ! Declares an integer one-dimensional array real:: B (3,6)  ! Declares that a real two-dimensional array type can be an integer, real, character, logical, or type. Can be up to 7 dimensions. The array size must be constant. However, unlike the C language, Fortran also has the option of using a variable size array, such as: Integer, allocatable:: A (:)  
Declare a small variable after a certain way to know the size of the desired array, use the following statement: Allocate (A (size))   ! After you configure the memory space, the array is exactly the same as the array declared by the general method. Unlike C, the FORTRAN index value defaults to 1, and can be changed at declaration time: integer A ( -3:1)   ! The index value is -3,-2,-1,0,1integer B (2:3,-1:3)!b (2~3,-1~3) is an element that can be used
2, the array in memory storage and C, the array in Fortran such as a (2,2) in memory in the order of a (), a (2,1), A (a), a (2,2). The principle is to put the elements of the lower dimension, and then the high-dimensional elements. This rule is called column major.
3, assign the initial value (1) The most common practice: Integer A (5) data  a  /1,2,3,4,5/or integer:: A (5) = (/1,2,3,4,5/) If integer:: A (5) = 5, 5 elements are 5 for integer:: A (2,2) = (/1,2,3,4/) is equivalent to the assignment of a () =1,a (2,1) =2,a (=3,a) depending on how the array element is stored in memory 4 (2) Take advantage of FORTRAN features: implicit loops. Look at the example and you understand. Integer A (5) integer idata (A (i), i=2,4)/2,3,4/    ! ( A (i), i=2,4) represents the I loop from 2 to 4, and the increment to the default value of 1 can also be this: integer Iinteger:: A (5) = (/1, (2,i=2,4), 5/)   ! Five elements are assigned 1,2,2,2,5integer:: B (5) = (/I, i=1,5/)        ! Five elements are assigned a value of 1,2,3,4, can also be nested data ((A (I,J), i=1,2), j=1,2) =/1,2,3,4/!a (total) =1,1 (2,1) =2,a (=3,a) =4
4, the operation of the entire array set A, B is the same type, dimension and size of the array a=5           ! All elements are assigned a value of 5a= (/1,2,3/)! This assumes a is a one-dimensional, a (1) =1,a (2) =2,a (3) =3a=b          ! The corresponding element assignment, requires a, B, C Dimension and size are the same, the same a=b+c  A=b-ca=b*ca=b/ca=sin (b)     ! Internal functions can be used this way
5, Operation part array element A is a one-dimensional array A (3:5) = (/3,4,5/)   !a (3) =3,a (4) =4,a (5) =5a (1:5:2) =3          !a (1) =3,a (3) =3,a (5) =3a (3:) =5              !a (3) and all subsequent elements are assigned a value of 5a (1:3) =b (4:6)      ! Similar to this requires that the number of elements in the left and right array is the same (:) =b (:, 2)         !a (1) =b (=b), A (2) 2,2
6. Wherewhere form is similar to if, but only used to set the array. There are two arrays of the same type, dimension, and size A,bwhere (a<3) b=a          ! A element of less than 3 is assigned to the element in the corresponding position of B, end where  again such as: where (A (1:3)/=0)  c=a  ! Omit the end where, because it only followed a line where can be embedded, also! You can have a signature tag like a Do loop.
7, ForAll kind of like a For loop in C: ForAll (Triplet1[,triplet2 [, Triplet3...]],mask) where the triplet shape, such as I=2:6:2, represents a loop, the last number is omitted the increment is 1 for example: ForAll (I=1:5,j=1:5,a (I,J) <10) A (i,j) =1end ForAll also such as: ForAll (I=1:5,j=1:5,a (i,j)/=0) A (i,j) =1/a (i,j) ForAll can also be nested in use, Like the nesting of for loops in C.
Functions in Fortran are divided into two categories: subroutines (subroutine) and custom functions (function). A custom function is essentially a function of learning, typically passing an argument to a custom function, returning the value of a function. Subroutines are not necessarily the case, and can have no return value. The pass parameter should pay attention to the correspondence of the type, which is the same as C. 1, sub-program purposes: A section of the regular use of a specific function of the program independent, can be easily called. It is customary to put the procedure at the end of the main program. Form: subroutine name (Parameter1, parameter2)! Give the subroutine a meaningful name. You can pass parameters so that you can have a return value. The parentheses can also be empty, and the generation will not pass parameters. Implicit none      integer:: parameter1, Parameter2   ! You need to define the type of the receive parameter. ......                               ! The next program is written with the main program without any. ... mreturn! Unlike C, where the subroutine executes and goes back to the place where it was called to proceed with the following program. Not necessarily put
! At the end. It can be placed elsewhere in the subroutine, and the part after return in the subroutine is not executed. End [subroutine name] invocation: Used directly with the call command, no declaration required. Write at invocation: Call subroutine name (PARAMETER1,PARAMETER2) Note: A. Subroutines can also be called to each other. A direct call is just like calling a subroutine in the main program. B. The principle of passing parameters differs from C. Fortran is a call by Address/reference, which is the same address used when passing parameters and parameters received in subroutines, although naming can be different. This way, if the subroutine executes a subroutine that receives the value of the parameter, the passed parameter changes accordingly. C. The variables defined internally by the subroutine are independent, similar to C. The individual line codes are also independent. Therefore, each subroutine main program has the same variable name, line code number, and does not affect each other. 
 2, a distinct difference between a custom function and a subroutine is that it needs to be declared in the main program before it can be used. There are also differences in invocation patterns. In addition, it is customary to use the function not to change the value of the argument. If you want to change the value of the passed parameter, it is customary to do it with a subroutine. Declaration method: Real, external:: Function_name General Custom functions are also placed after the main program. Form: function function_name (Parameter1, parameter2) implicit nonereal:: Parameter1, Parameter2! Declares the function parameter type, which is required by the real:: Function_name! Declares that a function returns a value type, which is required ... function_name= ..... The return value of the expression Returnend can also be directly declared return value type, concise: Real function function_name (parameter1, parameter2) implicit nonereal:: Parameter1, Parameter2! This is still necessary ... function_name= ...!!!!!! The return value expression Returnend called: function_name (PARAMETER1,PARAMETER2) does not require a call command. Custom functions can be called each other. The call must also be declared in advance. In summary, you need to make a declaration before calling the custom function, and calling the subroutine is not required. 
 3, about the variables in the function (1) Note the corresponding type. A numeric constant can even be passed in Fortran, but only if it corresponds to the type of the parameter defined by the function. For example, call Showreal (1.0) must be 1.0 instead of 1. (2) Passing array parameters, as well as C is the address, but not necessarily the first address of the array, but can be an array of a specified element address. For example, if there is an array a (5), call function (a) is called to pass the address of a (1), and call function (A (3)) is passed the address of a (3). (3) Multidimensional arrays as function parameters, in contrast to C, the last dimension can not be written, the other dimensions must be written. This is determined by the way in which the array element column major is stored in FORTRAN. (4) In a function, if the array is a parameter to be received, the variable can be assigned its size when declared, and can even be specified without a small value. For example: subroutine Array (num,size) implicit noneinteger:: Sizeinteger num (size)! You can define an array whose size is determined by the parameters passed. This is very practical ... returnend (5) Save command: The value of the variable in the function is preserved after the call, and the value of the variable is the last value that was saved the next time the function is called. Just add save when you define it: Integer, Save:: A=1 (6) Transfer functions (including custom functions, library functions, subroutines are all possible). A function pointer similar to c needs to declare a function passed as a parameter in both the main program and the function that invokes the function. Like real, external:: Function! Custom function real, intrinsic:: Sin! library function External Sub! subroutine (7) function using interface (interface) : A section of the program module. The following conditions are required: A. function return value is an array B. Specifies the parameter position to pass the parameter when C. The number of function arguments that are called is not fixed d. When the indicator parameter is entered, the function returns the value as a pointer. The specific usage is easy to understand with examples. Examples are very long. Read it. 
4. Global variables
function is needless to say. Principle: Based on the relative position of the declaration when used, different from C in accordance with the variable name.
If defined in the main program:
Integer:: A, b
Common A, B! That's how you define global variables.
Defined in a subroutine or custom function:
Integer:: c,d
Common C,d
Then A and C share the same memory, and B and D share the same memory.
Too much of a global variable can be cumbersome. They can be categorized as if they were defined by adding interval names to the common.
。 Such as
common/groupe1/a, common/group2/b. This makes it unnecessary to use all global variables
are listed, and then declare that COMMON/GROUPE1/C can use a, C global variables.
You can use the Block Data program module. The data command mentioned above cannot be used directly in the main program and function to give full
The local variable assigns the initial value. They can be assigned an initial value, if you want to use the data command:
Block data [name]
Implicit none
Integer a,b,c
Real D,e
Common a B C
Common/group1/d,e
Data a,b,c,d,e/1,2,3,4.0,5.0/
end [block data [name]]
5, Modulemodule is not a function. It is used to encapsulate the program module, which usually encapsulates functions and variables with related functions. The use is simple, but can provide a lot of convenience, so that the program becomes concise, such as the use of global variables do not have to declare a long string each time, write in Odule call on the line. The module is generally written before the main program begins. Form: module Module_name............end [module [module_name]] use: When used in the main program or function, you need to write a line before the declaration: use module_name. The module must have a function after the contains command (that is, write on a line contains and then start writing the number below, and all functions are written after this contains). and the variables defined in module can be used directly in the function in module, and can be called directly between functions, and even the custom functions in the module are not declared before being called.
6. Include anywhere you need to insert additional files (must be in the same directory). Such as:
Include ' Funcion.f90 '
Viii. files 1, text files in Fortran there are two ways to read files, corresponding to two file sequential reads: For text file Direct read: For binary files here only extracts about the text file read. The general pattern is as follows. Character (len=20):: filenamein= "In.txt", filenameout= "out.txt"! File name logical aliveinteger::fileidin=10,fileidout=20! 10,20 is the number of the file, except for the 1,2,5,6 positive integer, because 2, 6 is the default output location (screen), 1, 5 is the default input location (keyboard) integer::errorreal::in,out! The following paragraph is used to confirm the existence of a file of the specified name inquire (File=filenamein, exist=alive)! If present, alive is assigned a value of 0if (. Not. Alive) Thenwrite (*,*) trim (Filenamein), "doesn ' t exist." Trim is used to delete the Filenamein string! Trailing stop extra space, the output is good looking at the end ifopen ([Unit=]fileidin, File=filenamein, status= "old") open ([unit=] Fileidout,file=filenameout[,status= "new"])!unit Specify the position of the input/output. Open existing file must use status= "old"; open new file with status= "new"; no status is specified, default status= "Unknown", overwrite existing file or open new file ... read ([Unit=]fileidin, [ Fmt=]100,iostat=error) in!error=0 indicates that the data is read correctly. Format (1x,f6.3)! Enter the output in a format that can be written separately and specify the line code, or write directly in Read/write (([Unit=]fileidout, "(1x,f6.3)") out Close (f Ileidin) Close (fileidout)!1x represents a space. F6.3 represents 6 characters (including decimal points) for real data, with three digits after the decimal point. There are also I3 used for integer data, three characters in total, A8, character type, 8 characters. The read of the newline/binary file is different. No longer listed.
2, internal file another very useful read and write function is the internal file (internal files). Take a look at this example to understand. Integer::a=1,b=2character (len=20):: Stringwrite (unit=string,fmt= "(I2, ' + ', I2, ' = ', I2)") A,b,a+bwrite (*,*) The string results in an output of 1+2=3. The reverse is also possible: the integer Acharacter (len=20):: string= "123" read (string,*) awrite (*,*) A is output 123.
! End of the full text.

Fortran and C

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.