[Records and Files]   [Units and File Connection]   [Read Statement]   [Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]   [Data Statement]   [Debugging Tools]   [Example Programs]   [Summary]   [Problems]     

CHAPTER 2:  BASIC INPUT/OUTPUT



Input/output operations (i.e., reading/writing data) are avery important part of computer programming. This chapter describes basic input/output operations, beginning with the READ and WRITE statements.

The READ statement is an input statement; the WRITE statement is an output statement. The OPEN statement is used to open a file for reading or writing purposes. The CLOSE statement reverses the action of the OPEN state ment. The DATA statement is used to provide initial val ues for variables, or in place of input data.

There are two types of input/output operations: (1) unformatted, which do not follow a specific way of reading or writing, and (2) formatted, which follow a specific way. Unformatted input/output is much simpler than for matted. The emphasis of this chapter is on unformatted input/output. Chapter 6 describes formatted input/output in more detail.


2.1  RECORDS AND FILES

[Units and File Connection]   [Read Statement]   [Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]   [Data Statement]   [Debugging Tools]   [Example Programs]   [Summary]   [Problems]      [Top]  

A record is the basic unit of input/output operations. A record is a sequence of characters constituting one value, or a sequence of values forming one line. For instance, a line on a computer or terminal screen is usually considered to be a record. When entering data, pressing the carriage RETURN key signals the end of a record. In other words, the RETURN key is a record separator.

Records are of two types: (1) unformatted, and (2) formatted. Unformatted records do not follow a format specification and they may be read or written only by unformatted input/output statements. Formatted records follow a format specification and they may be read or written only by formatted input/output statements.

A file is a sequence of records forming an entity which can be addressed by the operating system. Files can be either external or internal. An external file is any file that exists independently of the executable program. An internal file is used for the purpose of transferring data from one location in (internal) storage to another location in (internal) storage.

Input statements transfer data from external media (an external file or the screen) or an internal file to internal storage. This process is called reading, and it is accomplished with the READ statement.

Output statements transfer data from internal storage to external media (an external file or the screen) or an internal file. This process is called writing and it is accomplished with the WRITE (or PRINT) statement.

Format specification is accomplished with a FORMAT statement. A programmer choosing unformatted input/ output does not need to specify FORMAT statements. In this case, the processor controls how input data is read and how output data is written.

A programmer choosing formatted input/output must use FORMAT statements to read and/or write data. In this case, the programmer retains control on how input data is read and how output data is written.

As a general rule, it is good programming practice to use unformatted records for input (reading) operations, and formatted records for output (writing) operations. Unformatted input frees the programmer or user from having to count columns and blank spaces on a data record. Formatted output has the advantage that it can be made to look exactly as desired.

Example: Unformatted and Formatted Input/Output

C234567890
C-----UNFORMATTED INPUT/OUTPUT
      READ(5,*) A,B,C
      WRITE(6,*) A,B,C
C-----FORMATTED INPUT/OUTPUT
      READ(5,10) A,B,C
      WRITE(6,20) A,B,C
 


2.2  UNITS AND FILE CONNECTION

[Read Statement]   [Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]   [Data Statement]   [Debugging Tools]   [Example Programs]   [Summary]   [Problems]      [Top]   [Records and Files]  

Processors use certain numbers called logical units to con nect to a file for input/output operations. Logical units can vary from 1 to 100, allowing the simultaneous connection of up to 100 files. The numbers 5 and 6 are the usual default logical units for interactive screen input and output, respectively. Other numbers in the range 1-100 can be arbitrarily chosen to connect to files.

The OPEN statement is used to connect a file to a unit. The CLOSE statement is used to disconnect a file from a unit. A file must not be connected to more than one unit at the same time. A unit must not be connected to more than one file at the same time.

Input data can either

  1. Reside in an input file, or

  2. Be entered directly to the screen every time the program is executed. This is called "interactive reading."

If the input data resides in an input file, the latter can be read every time the program is executed. If the input data does not reside in an input file, the data has to be entered anew every time the program is executed.

In general, a long input data stream (consisting of a large number of records, say, more than 10) should reside in an input file. On the other hand, a short input stream (say, a few records) may be entered directly to the screen every time the program is executed.

Output data can either

  1. Be written to an output file, or

  2. Be displayed directly on the screen every time the pro gram is executed.

If the output data is written to an output file, it is effectively stored and can be referenced as many times as desired, until such time when it is no longer needed and can be deleted--i.e., erased from disk storage. If the output data is displayed directly on the screen, it is available for immediate examination, but it is not stored.

In general, a long output stream should be written to an output file, for immediate examination or long-term storage. On the other hand, a short output stream may be displayed directly on the screen, for immediate examination only.

The direct screen input/output mode is often referred to as interactive mode. Typically, in the absence of a specific instruction to the contrary, a processor will regard the interactive mode as the default input/output mode.

The numbers 5 and 6 are the usual default logical units for interactive screen input and output, respectively. Throughout this book, the units 5 and 6 will be taken in this context.


Things to watch for with regard to logical units:

  • Check your operating system's documentation for the default (logical) units to be used for interactive input/output.

  • Use these default units as appropriate in place of the default units indicated in Section


2.3  READ STATEMENT

[Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]   [Data Statement]   [Debugging Tools]   [Example Programs]   [Summary]   [Problems]      [Top]   [Records and Files]   [Units and File Connection]  

The READ statement is the data transfer input statement. It has the typical form:

READ(UNIT=5,FMT=12) A,B,C

Note that the READ statement keyword is followed by UNIT= 5 and FMT= 12, enclosed within parentheses, and separated by a comma. This statement will read the vari ables A, B, and C from the file that is connected to unit 5 following the format marked with the statement label 12. If interactive read is connected to unit 5 (the usual default setting), the input data is entered directly to the screen during program execution.

The above statement can also be written as:

READ(5,12) A,B,C

where the optional characters UNIT= and FMT= have been omitted for simplicity. If these characters are omitted, the following rules should be adhered to:

  • If UNIT= is omitted, the unit specifier must be the first item on the list enclosed in parenthesis; and

  • If FMT= is omitted, the format specifier must be the second item on the list enclosed in parenthesis, and the first item must be the unit specifier without the character UNIT=.

The form

READ(*,12) A,B,C

will read variables A, B, and C using direct screen input and following the format with statement label 12. The * in place of the unit specifier stands for direct screen input, i.e., interactive input.

The form

READ(5,*) A,B,C

will read variables A, B, and C from the file connected to unit 5 and use unformatted input. The * in place of the format label stands for unformatted input. An unformatted READ is also referred to as a list-directed READ.

The form

READ(7,*) A,B,C

will connect an input file to unit 7 and use unformatted in put. Since unit 7 is not normally used for interactive input, the connection to unit 7 is accomplished with an OPEN statement (see Section 2.5).

The unit specifier does not need to be a constant. The form

READ(LU,*) A,B,C

will connect to a variable logical unit LU and use unformatted input. The value of LU should be defined in the source program prior to the execution of this READ statement.

The READ statement has other specifiers, besides the unit and format specifiers.

The form

READ(7,15,ERR=80,END=90) A,B,C

will read variables A, B, and C from the file connected to unit 7, following format labeled 15. In addition:

  • An error condition during input operation will branch control to the statement labeled 80.

  • An end-of-file condition during input (i.e., no more records remaining to be read in the file) will branch control to statement 90.

The indicated statement labels (80 and 90) must exist elsewhere in the program unit. Either ERR or END or both may be specified in a READ statement. The characters ERR= and END= preceding the label specifiers are required and cannot be omitted.


2.4  WRITE STATEMENT

[Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]   [Data Statement]   [Debugging Tools]   [Example Programs]   [Summary]   [Problems]      [Top]   [Records and Files]   [Units and File Connection]   [Read Statements]  

The WRITE statement is the data transfer output state ment. Unlike the PRINT statement, which is permanently connected to direct screen output, the WRITE statement may also be used to write to a file. Therefore, the WRITE statament has more flexibility, and is preferred by most programmers.

The WRITE statement has the typical form:

WRITE(UNIT=6,FMT=15) X,Y,Z

This statement will write the variables X, Y, and Z to the file connected to unit 6 following the format labeled 15. When unit 6 is connected to interactive write (default value), the output data is displayed directly on the screen during program execution.

The above statement can also be written as:

WRITE(6,15) X,Y,Z

where the optional characters UNIT= and FMT= have been omitted for simplicity. In this case, the same rules as for the READ statement apply.

The form

WRITE(*,15) X,Y,Z

will write variables X, Y, and Z using direct screen output and following the format labeled 15. The * in place of the unit specifier stands for direct screen output (interactive output).

The form

WRITE(6,*) X,Y,Z

will write variables X, Y, and Z to the file connected to unit 6 and use unformatted output. The * in place of the format label stands for unformatted output. An unformatted WRITE is also referred to as a list-directed WRITE.

The form

WRITE(8,15) X,Y,Z

will connect to unit 8 and follow format 15. Since unit 8 is not normally used for interactive output, the connection to unit 8 is accomplished with an OPEN statement (see Section 2.5).

The unit specifier does not need to be a constant. The form

WRITE(LU,25) X,Y,Z

will connect to unit LU and follow format 25. The value of LU should be defined in the source program prior to the execution of this WRITE statement.

The form

WRITE(9,40,ERR=90) X,Y,Z

will write variables X, Y, and Z to the file connected to unit 9 following format labeled 40. An error condition during output operation will branch control to statement labeled 90. The indicated statement label (90) must exist elsewhere in the program unit.

Algebraic expressions can also be listed in a WRITE statement, as shown in the following example:

WRITE(6,20) 2*A,3.5*B

In this case, the first value written is equal to twice the value of A; the second is equal to 3.5 times B.

Example Program: READ and WRITE Statements

C234567890
      PROGRAM READ_WRITE
      READ(5,*) A,B
      READ(5,*,ERR=85) C
      X= A + B
      Y= B - C
      Z= A/C
      WRITE(6,*) 'X IS EQUAL TO ', X
      WRITE(6,*) 'Y IS EQUAL TO ', Y
      WRITE(6,*) 'Z IS EQUAL TO ', Z
   85 WRITE(6,*) 'ERROR WHILE READING C'
      END

In the above program, the variables A, B, and C are read directly into the screen (unit 5 specifier), the indicated operations are performed, and the results are printed directly onto the screen (unit 6 specifier). Assuming A = 10.8, B = 7.8, and C = 3.2, the output would look like this:

X IS EQUAL TO 18.6000
Y IS EQUAL TO 4.60000
Z IS EQUAL TO 3.37500

Note that if an error is encountered while reading C, the output would simply look like this:

ERROR WHILE READING C


2.5  UNFORMATTED INPUT/OUTPUT RULES

[Open Statement]   [Close Statement]   [Data Statement]   [Debugging Tools]   [Example Programs]   [Summary]   [Problems]      [Top]   [Records and Files]   [Units and File Connection]   [Read Statements]   [Write Statement]  

The following rules are for unformatted input/output:

  • An input value or values should have no embedded blank spaces (i.e., blanks in the middle), and should be separated among themselves either by:

    • a comma,

    • one or more blank spaces, or

    • a combination of one comma and one or more blank spaces in any order.

  • Character constants should be enclosed by apostrophes and separated among themselves in the same way as other values.

  • During input, the processor is directed to read as many values as variables are listed in the READ statement. This is why unformatted input is also referred to as list- directed READ.

    • If, within one input record, m (the number of values forming part of the record) matches n (the number of variables listed in the READ statement), n = m values will be read.

    • If, within one input record, m exceeds n, n values will be read from that record and the remaining values (m - n) will be ignored by the processor.

    • If, within one input record, n exceeds m, m values will be read from that record, and the remaining values (n - m) will be read from at least one addi tional record. The values, if any, remaining in the last record read will be ignored by the processor.

  • During output, values are written with spacing and char acteristics remaining under the control of the processor.

Things to watch for with regard to unformatted input:

  • You should try to match the number of variables listed in the READ statement with the number of values contained in the input record.

  • If the number of variables listed in the READ statement (see Section 2.3) does not match the number of values in the input record, you are in effect either (a) disregarding a trailing por tion of the input record, or (b) reading more than one record, and may be disregarding a trailing portion of the last record read.


2.6  OPEN STATEMENT

[Close Statement]   [Data Statement]   [Debugging Tools]   [Example Programs]   [Summary]   [Problems]      [Top]   [Records and Files]   [Units and File Connection]   [Read Statements]   [Write Statement]   [Unformatted Input/Output Rules]  

The OPEN statement initiates a connection between an external file and a specified unit. It has the typical form:

OPEN(UNIT=5,FILE='A.DAT',STATUS='UNKNOWN')

This statement will connect the external file A.DAT (an input data file) to unit 5. The character UNIT= is optional only if the unit specifier (5) is the first item on the list enclosed in parenthesis in the OPEN statement. In this case, the previous statement reduces to:

OPEN(5,FILE='A.DAT',STATUS='UNKNOWN')

The status specifier can be OLD, NEW, SCRATCH, REPLACE, or UNKNOWN. For some compilers, the status specifier may be optional.

  • If OLD is specified, the file must exist

  • If NEW is specified, the file must not previously exist; the file is created and the status is changed to OLD.

  • If REPLACE is specified and the file previously exists, the file is deleted, a new file is created, and the status is changed to OLD.

  • If SCRATCH is specified, the file is created, but it is deleted at the termination of program execution.

  • If UNKNOWN is specified, the status varies with the processor being used. Usually the processor tries status OLD first; if the file is not found, the processor then uses NEW, thereby creating a new file.

The file name specification can be omitted, as shown in the following example:

OPEN(7,STATUS='UNKNOWN')

In this case, a default file name which is processor depend ent (e.g., FOR007.DAT) is connected to unit 7.  

Another option is to include an error specifier in the OPEN statement, as in the following example:

OPEN(7,STATUS='UNKNOWN',ERR=97)  

If an error is encountered during the execution of this OPEN statement, control branches to the statement labeled 97.

Example: OPEN statement

C234567890
C-----OPEN STATEMENT
      OPEN(UNIT=5,FILE='P.DAT',STATUS='UNKNOWN')
      OPEN(UNIT=6,FILE='P.OUT',STATUS='UNKNOWN')
      READ(5,*) A,B,C
      WRITE(6,*) A,B,C
      OPEN(UNIT=7,FILE='Q.DAT',STATUS='UNKNOWN')
      OPEN(UNIT=8,FILE='Q.OUT',STATUS='UNKNOWN')
      READ(7,*) D,E
      WRITE(8,*) D,E
C-----END OF OPEN STATEMENT EXAMPLE

This example connects file P.DAT to unit 5, file P.OUT to unit 6, file Q.DAT to unit 7, and file Q.OUT to unit 8. It reads from P.DAT at least one (and at most three) record(s) containing values of variables A, B, and C. It writes to P.OUT the values A, B, and C. It reads from Q.DAT at least one (and at most two) record(s) containing values of variables D and E. It writes to Q.OUT the values D and E. Note that each OPEN statement physically precedes its respective READ or WRITE statement.


2.7  CLOSE STATEMENT

[Data Statement]   [Debugging Tools]   [Example Programs]   [Summary]   [Problems]      [Top]   [Records and Files]   [Units and File Connection]   [Read Statements]   [Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]  

The CLOSE statement disconnects an external file from a specified unit; therefore, it reverses the action of the OPEN statement.

After a unit has been disconnected from a file by the execution of a CLOSE statement, either may be connected again within the same executable program, either to the same unit or file or to another unit or file.

The CLOSE statement takes the form:

CLOSE(UNIT=5,STATUS='KEEP')

This statement disconnects unit 5 from a file name and keeps (i.e., saves) the file.

The status specifier can be KEEP or DELETE.

  • KEEP must not be specified for a file whose status prior to the execution of the CLOSE statement is SCRATCH.

  • If DELETE is specified, the file will be erased after the execution of the CLOSE statement.

  • If the status specifier is omitted, KEEP is assumed, un less the file status is SCRATCH, in which case DELETE is assumed.

The character UNIT= is optional if the unit specifier is the first item on the list enclosed in parenthesis in the CLOSE statement. In this case, the previous statement simplifies to:

CLOSE(5,STATUS='KEEP')

The form

CLOSE(5)

will disconnect unit 5 from a file name and keep the file (unless the file status is SCRATCH, see above).

If desired, an error specifier may be included in the CLOSE statement. For instance, in

CLOSE(5,ERR=98)

an error condition encountered during the execution of this CLOSE statement will branch control to the statement labeled 98.

At termination of program execution (for reasons other than an error condition), all connected units are automati cally closed. Therefore, it is usually not necessary to explicitly close units at the end of a source program.


2.8  DATA STATEMENT

[Debugging Tools]   [Example Programs]   [Summary]   [Problems]      [Top]   [Records and Files]   [Units and File Connection]   [Read Statements]   [Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]  

The DATA statement is used to provide initial values for variables. It takes the typical form:

DATA A,B,C /12.,23.4,-45./

This statement assigns to variables A, B, and C the initial values 12., 23.4, and -45., respectively. The slashes (/) de limiting (enclosing) the values are required, as well as the commas used to separate them. The number of values en compassed within the slashes (/) must equal the number of variables immediately following the keyword DATA.

Another way to write a DATA statement is the following:

DATA A,B,C /3*10./

All three variables A, B, and C have been initialized with the value 10. using a repeat factor (3 in this case). The repeat factor must be a positive integer. The above statement is equivalent to:

DATA A,B,C /10., 10., 10./

DATA statements are used:

  • to assign initial values to variables whose values will be later modified during program execution, or

  • to assign the proper values to constants that will not vary from one program application to the next.

DATA statements can be interspersed among executable statements (see Figure 1.1). However, it is good pro gramming practice, for easy reference, to place all DATA statements together, immediately preceding the executable portion of the source program or subprogram.

Things to watch for with regard to DATA statements:

  • Make sure that the number of variables matches the number of assigned values.

  • Be sure to include two slashes (/), one preceding and another following the listed values.

  • Be sure to separate the variables and values with commas. 

  • If you use a repeat factor, confirm that it is a positive integer, and that the number of values (including those repeated with a repeat factor) matches the number of variables.

  • For easy reference, consider placing all DATA statements together, preferably immediately preceding the executable statements.


2.9  DEBUGGING TOOLS

[Example Programs]   [Summary]   [Problems]      [Top]   [Records and Files]   [Units and File Connection]   [Read Statements]   [Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]   [Data Statement]  

This section introduces the programmer to debugging and debugging tools. This section should be used as a continu ing reference. However, effective debugging is learned by compiling and running many programs successfully. Al though initially a slow process, debugging skills improve with practice.

All Fortran programs need to be debugged before they can be used effectively. Debugging refers to the process of re moving errors, whatever their source. Success in programming depends on how fast and how thoroughly the pro grammer is able to identify and correct errors that may arise in the course of normal program development.

Debugging is both an art and a science, and experience is essential to success. However, thorugh a careful study of the nature of these errors, and of the strategies to correct them, the programmer can acquire the tools and develop the confidence to effectively debug Fortran programs.

Errors in Fortran program development and execution can be categorized into four classes:

  • Class I: Errors in statement spelling and/or syntax.

  • Class II: Errors in compatibility in input/output opera tions.

  • Class III: Errors in logic and compatibility within and between program units.

  • Class IV: Errors in input values.

Class I errors are common during the early stages of program development, and are relatively easy to debug. During compilation, Fortran compilers generate a list file which is available to the user upon demand. A list file has the same name as the Fortran file, but a different file extension. For example, the list file for MYPROG.FOR is MYPROG.LIS. (MYPROG.LST for some compilers). The list file lists the source program and flags the line(s) which contain spelling or syntax errors, e.g., a missing closing parenthesis. Usually, the error is to be found within the flagged line, but sometimes, it is found in the line immediately preceding or following. Careful examination of the flagged lines and their immediate vicinity should take care of most if not all Class I errors.

Class II errors are a little harder to debug than Class I errors. In formatted input/output (Chapter 6), the processor is extremely unforgiving, and will not tolerate incompatibilities between READ/WRITE and FORMAT state ments. For instance, the most common Class II error results from an attempt to read a real variable using an integer format, or viceversa. Fortunately, Class II errors produce runtime error messages which generally point the programmer in the right direction as far as error diagnosis is concerned. In unformatted input/output, the processor is more forgiving, but the drawback here is that some errors may go undetected.

Class III errors are more difficult to debug than either Class I or Class II errors. A Class III error could be one of logic or compatibility. During runtime, the processor will usually flag a Class III logic error, helping the user to di agnose it. A typical example of a Class III logic error is an attempt to divide by zero. The best way to debug this type of error is to identify the problem line and the source of the error, and to fix it. The WRITE statement and the D_LINES Fortran command qualifier (see Section 1.1) should be used freely to help identify the problem line.

Unlike a Class III logic error, the processor will usually not flag a Class III compatibility error. In other words, a program could be compiled, linked, and run, apparently successfully, with the processor being unable to discern and flag a Class III compatibility error. An example of this type of error is that associated with the im proper addressing of storage locations, e.g., errors in subprogram argument lists or in COMMON statements. The best way to debug a Class III compatibility error is to test the program against a "benchmark," i.e., a problem for which the solution is known beforehand. The user should also ask himself is the result is reasonable. If the answer to this question is NO, a compatibility error may be at work. While short programs (say, up to 100 source lines) can be readily tested for Class III compatibility errors, long programs may not. This is why long programs should be segmented into subprograms (Chapter 9), and the subprograms tested separately.

Class IV errors could be the most difficult to detect, because no help can be expected to come from the proces sor. This type of error occurs when a value entered into storage is, due to an oversight, not what it was intended. For example, assume a variable has a value of 3.92. By mistake, the value is entered as 3.29. This type of error can only be corrected through careful scrutiny of the input file.


2.10  EXAMPLE PROGRAMS

[Summary]   [Problems]      [Top]   [Records and Files]   [Units and File Connection]   [Read Statements]   [Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]   [Data Statement]   [Debugging Tools]  

Example Program 1: Use of DATA Statement and Connection to an Output File (for later printing)

The following program uses a DATA statement to assign specific values (3. and 4.) to the two sides of a right trian gle. Then it proceeds to calculate the hypotenuse using the intrinsic function SQRT(X) and to write all three values to an output file named SIDE_C.OUT. (An intrinsic function is a commonly used function that is supplied as part of the FORTRAN library. For a list, refer to Section 5.4). Note that this is only an example. Normally, input would not be performed with a DATA statement, but rather, via an input file (Example 2) or directly to the screen (Example 3).

The optional PROGRAM statement is at the top; the END statement is at the bottom. The DATA statement precedes all executable statements for the sake of improved readability. The OPEN statement connects unit 6 to file SIDE_C.OUT and precedes all WRITE statements. All WRITE statements are unformatted.

Using operating system commands, the output file (SIDE_C.OUT) can be examined by editing it, typing it (to the screen), or printing it (obtaining a hard copy).

Example Program 1: Data Statement And Output File

C234567890
      PROGRAM HYPOTENUSE_1
      DATA SIDEA,SIDEB /3.,4./
      OPEN(6,FILE='SIDE_C.OUT',STATUS='UNKNOWN')
      X= SIDEA**2 + SIDEB**2
      SIDEC= SQRT(X)
      WRITE(6,*)'SIDE A IS EQUAL TO ',SIDEA
      WRITE(6,*)'SIDE B IS EQUAL TO ',SIDEB
      WRITE(6,*)'SIDE C IS EQUAL TO ',SIDEC
      END

Example Program 2: Connection to Input and Output Files

The following program reads the values of the two sides of a right triangle from an input file SIDES.DAT. It proceeds to calculate the hypotenuse using the intrinsic function SQRT(X) and to write the value of the hypotenuse to an output file SIDE_C.OUT.

Note the order of statements in this program. The PROGRAM statement is at the top. The END statement is at the bottom. An OPEN statement connects unit 5 to input file SIDES.DAT and precedes the READ statement. An other OPEN statement connects unit 6 to output file SIDE_C.OUT and precedes the WRITE statement. Both READ and WRITE statements are unformatted. There is no need for STOP or CLOSE statements in this example.

Using an editor, the input file (SIDES.DAT) should be created before running this program. Otherwise, the vari ables SIDEA and SIDEB would be undefined at running time. After running the program, the generated output file (SIDE_C.OUT) can be examined by editing it, typing it (to the screen), or printing it (obtaining a hard copy).

Example Program 2: Connection to Input and Output Files

C234567890
      PROGRAM HYPOTENUSE_2
      OPEN(5,FILE='SIDES.DAT',STATUS='UNKNOWN')
      OPEN(6,FILE='SIDES.OUT',STATUS='UNKNOWN')
      READ(5,*) SIDEA, SIDEB
      X= SIDEA**2 + SIDEB**2
      SIDEC= SQRT(X)
      WRITE(6,*)'SIDE C IS EQUAL TO ',SIDEC
      END

Example Program 3: Direct Screen Input and Output

The following program reads the values of the two sides of a right triangle directly from the screen (direct screen or interactive input). It proceeds to calculate the hypotenuse using the intrinsic function SQRT(X) and to write the value of the hypotenuse directly to the screen (direct screen or interactive output).

Note the following features of this program:

  • The PROGRAM statement is at the top; the END state ment is at the bottom.

  • Each of the two READ statements is immediately pre ceded by a WRITE statement containing an input prompt, which is a character constant displayed on the screen to prompt the user to enter the requested input data.

  • This program generates its own input prompts by means of an unformatted WRITE.

Example Program 3: Direct Screen Input and Output

C234567890
      PROGRAM HYPOTENUSE_3
      WRITE(6,*) 'ENTER SIDE A: '
      READ(5,*) SIDEA
      WRITE(6,*) 'ENTER SIDE B: '
      READ(5,*) SIDEB
      X= SIDEA**2 + SIDEB**2
      SIDEC= SQRT(X)
      WRITE(6,*)'SIDE C IS EQUAL TO ',SIDEC
      END

Example Program 4: Direct Screen Input with Formatted Input Prompts

The only difference between this example and the previous one is that the input prompts have been formatted to per mit the input data to follow the input prompt on the same line. Although formally treated in Chapter 6, this example serves the purpose of introducing the student to some sim ple and useful formatting techniques.

The input prompts are generated with a special formatted WRITE containing (1) an edit descriptor 1X, to properly specify carriage control, (2) a character field descriptor A, which specifies that the value to be written is a character constant, and (3) an edit descriptor $, which suppresses the normal carriage return, thereby permitting the input data to follow the input prompt on the same line.

Example Program 4: Direct Screen Input with Formatted Input Prompts 

C234567890
      PROGRAM HYPOTENUSE_4
      WRITE(6,'(1X,A,$)') 'ENTER SIDE A: '
      READ(5,*) SIDEA
      WRITE(6,'(1X,A,$)') 'ENTER SIDE B: '
      READ(5,*) SIDEB
      X= SIDEA**2 + SIDEB**2
      SIDEC= SQRT(X)
      WRITE(6,*)'SIDE C IS EQUAL TO ',SIDEC
      END


2.11 SUMMARY

[Problems]      [Top]   [Records and Files]   [Units and File Connection]   [Read Statements]   [Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]   [Data Statement]   [Debugging Tools]   [Example Programs]  

  • This chapter introduces five basic and important state ments: READ, WRITE, OPEN, CLOSE, and DATA.

  • These are all executable statements; therefore, they should follow all nonexecutable statements in a program unit.

  • The READ and WRITE statements are used for input and output, respectively.

  • >The OPEN and CLOSE statements are used to connect and disconnect files to and from units, respectively, and to prepare them for input and output operations.

  • There is no need to need to explicitly disconnect files at the end of a source program.

  • The DATA statement is used to provide initial values for variables, either because initial values are needed, or because these values are intended to remain constant throughout the execution of the source program.

  • It is good programming practice to place all DATA statements together, immediately preceding the executable portion of the source program.


PROBLEMS

   [Top]   [Records and Files]   [Units and File Connection]   [Read Statements]   [Write Statement]   [Unformatted Input/Output Rules]   [Open Statement]   [Close Statement]   [Data Statement]   [Debugging Tools]   [Example Programs]   [Summary]  

  1. Write an interactive program (direct screen input and output) to calcu late the volume of a cylinder of diameter DIA= 2 in., and height HEI= 3 in. Use input prompts as needed. Output should include the following label: THE VOLUME OF THE CYLINDER IS, followed by the actual volume, in turn followed by the label CUBIC INCHES.

  2. Write an interactive program (direct screen input and output) to calcu late the volume of a cone of base diameter DIA= 3.5 cm and height HEI= 5.5 cm. (The volume of a cone is V= πr2h/3). Use input prompts as needed. Output should include the following label: THE VOLUME OF THE CONE IS, followed by the actual volume, in turn followed by the label CUBIC CENTIMETERS. [Hint: Use 0.3333333 to express the factor 1/3 to an accuracy of 7 significant digits, typical of most computers].

  3. Write an interactive program to calculate the volume of a sphere of ra dius RADIUS= 0.6 ft. (The volume of a sphere is V= 4πr3/3). Use an input prompt as needed. Output should include the following label: THE VOLUME OF THE SPHERE IS, followed by the actual volume, in turn followed by the label CUBIC FEET. [Hint: Use 1.333333 to ex press the factor 4/3 to an accuracy of 7 significant digits, typical of most computers].

  4. Using your screen editor, type the program of Example 1 in Section 2.10 using instead the following data: SIDEA= 15., SIDEB= 20. Run the program and look at the contents of the output file SIDE_C.OUT. Then, modify the program to write the results using only one WRITE state ment (instead of three). [Hint: Use the continuation field]. Run the program and compare the new output with the previous output. What can you conclude about the unformatted WRITE?

  5. Using your screen editor, type the program of Example 2 in Section 2.10. Run the program with the following input data: SIDEA= 48., SIDEB= 62. Then, modify the program to calculate the square root without resorting to the intrinsic function SQRT. [Hint: Use C= (A2 + B2)0.5]. Run the modified program and note the difference in the result, if any.

  6. Using your screen editor, type the program of Example 3 in Section 2.10. Run the program with the following input data: SIDEA= 134., SIDEB= 258. Then, modify the program by omitting the edit descriptor 1X and run the program again. Observe what happens this time: The first letter of the input prompt has disappeared! Can you fix this with out putting back the edit descriptor? [Hint: Include a leading blank space as part of the character constant defining the prompt]. What can you conclude about the purpose of the edit descriptor?

  7. Repeat Problem 1 instead connecting to input and output files. Before running the program, create the input file and use your screen editor to enter the data. After running the program, look at the output file to examine your results.

  8. Repeat Problem 2 instead connecting to input and output files. Before running the program, create the input file and use your screen editor to enter the data. After running the program, look at the output file to examine your results.

  9. Repeat Problem 3 instead connecting to input and output files. Before running the program, create the input file and use your screen editor to enter the data. After running the program, look at the output file to examine your results.

  10. Write an interactive program to convert air temperature in degrees Farenheit to degrees Celsius [ToC= (ToF - 32)/1.8]. Use the variable names TDFAR for input and TDCEL for output, and the following input prompt: PLEASE ENTER AIR TEMPERATURE (IN DEGREES FARENHEIT): . Use the edit descriptor $ to suppress carriage return after the input prompt. Precede the output with the following label: THE AIR TEMPERATURE (IN DEGREES CELSIUS) IS: . Run your program first with TDFAR= 103, and then, with TDFAR= 104. What can you conclude about the unformatted WRITE?

  11. Write a program to calculate the value of eγ, where e is the natural log base and γ is Euler's constant (γ = 0.5772157). Use the intrinsic function EXP(X) from Table 5.4. Write the result to an output file connected to unit 8, preceded by the label THE VALUE OF E**GAMMA IS: . Use an OPEN statement that omits the file name specification. Type the default file name for examination; for example, the file FOR008.DAT.

  12. Write an interactive program (direct screen input and output) to convert a given trigonometric angle in degrees to radians. Use the variable names DEGREE for input and RADIAN for output, and the following input prompt: PLEASE ENTER TRIGONOMETRIC ANGLE (IN DEGREES):. Use the edit descriptor $ to suppress carriage return after the input prompt. Precede the output with the following label: THE ANGLE (IN RADIANS) IS: . Run your program first with DEGREE= 355, and then, with DEGREE= 360.

  13. The volume V of a spherical cap of radius r and height h is equal to: V= (1/3) πh2(3r - h). Write an interactive program to perform this calculation. Run your program with RAD= 3 inches, and HEI= 1.4 inches. Output should include the following label: THE VOLUME OF THE SPHERICAL CAP IS, followed by the actual volume, in turn followed by the label CUBIC INCHES. [Hint: Use 0.3333333 to express 1/3 to an accuracy of 7 significant digits, typical of most computers].

  14. Repeat Problem 13 disregarding the hint and using 1/3 instead. What happens in this case? What can you surmise from this exercise? How can you fix it?

  15. The area of a regular polygon of n sides, each of length b, is equal to: A= (1/4) nb2cot (π/n). Write an interactive program to perform this calculation. Run your program using NSIDES= 6 and BLENGT= 4 cm. Output should include the following label: THE AREA OF THE REGULAR POLYGON IS, followed by the actual area, in turn fol lowed by the label SQUARE CENTIMETERS. [Hint: Use 0.25 instead of 1/4, and express the cotangent in terms of the intrinsic functions SIN(X) and COS(X) of Table 5.4].


http://fortran.sdsu.edu
140616 14:30

Documents in Portable Document Format (PDF) require Adobe Acrobat Reader 5.0 or higher to view; download Adobe Acrobat Reader.

Open-channel hydraulics, Victor M. Ponce, San Diego State University, Copyright © 2014, All rights reserved.


FORTRAN FOR SCIENTISTS AND ENGINEERS

VICTOR M. PONCE

•  ONLINE EDITION  •

Contents

Chapter 01

Chapter 02

Chapter 03

Chapter 04

Chapter 05

Chapter 06

Chapter 07

Chapter 08

Chapter 09

Chapter 10

Chapter 11

Copyright © 2014 • Victor M. Ponce • All rights reserved.