• Không có kết quả nào được tìm thấy

Introduction to Programming using Fortran 95/2003/2008

N/A
N/A
Nguyễn Gia Hào

Academic year: 2023

Chia sẻ "Introduction to Programming using Fortran 95/2003/2008"

Copied!
237
0
0

Loading.... (view fulltext now)

Văn bản

You must attribute the work to "Introduction to Fortran Programming, but not in a manner that suggests that the author endorses you or your use of the work). Any of the above terms may be waived if you obtain permission from the holder of the copyright.

Why Learn Programming

Fortran

Complete Fortran 95/2003/2008 Documentation

What Is A Program

Operating System

Architecture Overview

Compiler

Information Representation

Decimal Numbers

Binary Numbers

Character Representation

Exercises

Quiz Questions

Required Skills

Program Formats

  • Program Statement
  • Comments
  • Simple Output
  • Example – First Program

This includes a general procedure for creating a very simple program, compiling and running the program. This file, which is the input to the compiler, is usually called a source file.

Text Editor

For programming commands, the comments should include the programmer's name, command number, and a brief description of the program. All characters after the exclamation mark (!) are ignored by the compiler and are therefore comments, as shown in the following example.

Compiling

Advanced Compiler Options

Executing

To execute or run a program on a Unix- or MAC-based machine, type "./" and the name of the executable file. The output ('Hello World.' as displayed on the screen) will be the same for Windows, Unix or MAC based machines.

Exercises

Quiz Questions

It should be noted that the space before the "H" is not produced by the program, but is how the system displays the output. The output ('Hello World.' as shown on the screen) will be the same for Windows, Unix or MAC based machines. 6) What is the typical Fortran compiler output file or executable file extension (after the program is compiled).

Suggested Projects

Before you start writing programs, it is necessary to know some of the basic elements of the Fortran language.

Variables

Variable Names

Keywords

Data Types

  • Integer
  • Real
  • Complex
  • Character
  • Logical
  • Historical Data Typing

Real numbers, also called floating numbers, include both rational numbers and irrational numbers. It can be written in the form of a + bi, where a and b are real numbers and the i is the imaginary standard unit with the property that i2 = −1.0.

Declarations

Type Checking

Initialization

Constants

Comments

Continuation Lines

Example

Declarations, Extended Size Variables

Integers

In the unlikely event that a larger scope is required, a special declaration can be used to extend the scope. Both equivalent declarations use more space for variables (8 bytes instead of the usual 4) to provide a larger scope.

Real

Exercises

Quiz Questions

Suggested Projects

The previous chapter explained what variables are and summarized the five Fortran data types.

Literals

  • Integer Literals
  • Real Literals
    • E-Notation
  • Complex Literals
  • Character Literals
  • Logical Constants

A complex constant is denoted by a pair of constants (integer or real), separated by a comma and enclosed in parentheses.

Arithmetic Operations

Assignment

Addition

Subtraction

Multiplication

Division

Exponentiation

Order of Operations

Intrinsic Functions

Mathematical Intrinsic Functions

Conversion Functions

Summary

Mixed Mode

Examples

Exercises

Quiz Questions

Suggested Projects

Output – Write

Output – Print

As with the write statement, multiple variables and strings can be displayed with one print statement. The information within the quotes is displayed as is, including capitalization and any spelling errors.

Input – Read

Example

Exercises

Quiz Questions

Suggested Projects

The program should display an appropriate prompt, read the values, calculate the answer, and display the original input and the final result. To demonstrate this process in detail, these steps are applied to a simple problem to calculate and display the period of a pendulum.

Understand the Problem

As additional examples are presented in later chapters, they will be explained and presented using this methodology.

Create the Algorithm

Implement the Program

Test/Debug the Program

Error Terminology

  • Compiler Error
  • Run-time Error
  • Logic Error

If the program doesn't work, it helps to understand some basic terminology about where or what the error might be. If the program has a logic error, one way to find the error is to display intermediate values.

Exercises

Quiz Questions

Suggested Projects

Conditional Expressions

When writing a program, it may be necessary to perform some actions based on the result of comparing the values ​​of some variables. Which will result in a true or false result based on the value of the gameLives variable.

Logical Operators

IF Statements

IF THEN Statement

  • IF THEN Statement, Simple Form

In this form, only one statement is executed if the conditional expression evaluates to true.

IF THEN ELSE Statement

On which the message "Still Alive, Keep Going!" if the value of gameLives is greater than 0 and display the message "Extra Life Granted". if the value of gameLives is less than or equal to 0.

IF THEN ELSE IF Statement

Example One

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

Once the program is written, tests must be performed to ensure that the program works. In this example, each of the three possible values ​​for the discriminant must be tested.

SELECT CASE Statement

But with a CASE DEFAULT you are sure that regardless of the value of the selector, one of the labels will be used. The calculation of the leap year is not complete, but is sufficient if the scope of the year is sufficiently limited.

Example Two

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

The program should be tested with a variety of data elements to ensure appropriate grading for each grade.

Exercises

Quiz Questions

You can assume that the values ​​for f, x, and y have already been declared as real values ​​and initialized.

Suggested Projects

If the Fahrenheit value is out of range, the program should display an error message, "Temperature out of range" and terminate. The program should display an appropriate message if an invalid or undefined channel is entered.

Counter Controlled Looping

When a series of Fortran statements must be repeated, it is referred to as a loop or do-loop. The first iteration multiplies factor by 1, the second iteration multiplies factor by 2, the third time by 3, .., the ith time by i and so on.

EXIT and CYCLE Statements

Counter Controlled Example

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program
  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum. Then we will loop from 1 to the N value and find both the sum of the squares and the square of the sum.

Exercises

Quiz Questions

For this problem, the testing will be to ensure that the results match the expected value. This will require entering a series of different dates and verifying that the displayed output is correct for the given input data.

Suggested Projects

Format

Format Specifiers

Integer Format Specifier

Real Format Specifier

Horizontal Positioning Specifiers

Logical Format Specifier

Character Format Specifier

For example, to display the string in variable message and the string "Goodbye cruel world". Note that for the first string variable, msg, only the first 9 characters of the 11 total characters are displayed since the A9 format is used.

Advance Clause

Example

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

Then the program can calculate the day of the week (based on the formula) and convert the resulting number (0-6) into a date string and display the result. Test the program on a series of different input values ​​and verify that the output is correct for those input values.

Exercises

Quiz Questions

The spacing and indentation is not required, but helps to make the program more readable. For this problem, testing would be to make sure the output format is correct.

Suggested Projects

Note the requirement that the three input variables be formatted on a single line. The program should understand the initial principal amount, the interest rate percentage and the term (number of years).

Character and String Constants

Character Variable Declaration

Character Variable Initialization

Character Constants

Character Assignment

Character Operators

Character Substrings

Character Comparisons

Intrinsic Character Operations

TRIM(STR) Returns string based on the string argument STR with any trailing spaces removed.

Example

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

Spacing and indentation are optional, but they help make the program more readable. Every lowercase letter has been converted to uppercase, while uppercase letters, space and punctuation have remained unchanged.

Exercises

Quiz Questions

Suggested Projects

The basic read and write statements for file operations are the same as before, with some additional information or clauses.

File Open

If the status variable is set to >0, an error has occurred and the operation failed.

File Write

Stop Statement

File Read

Rewind

Backspace

Close File

Example

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

For this issue, testing involves running the program with several input files and verifying that the line numbers are added correctly.

Exercises

Quiz Questions

What is the read statement required to get data1, data2 and data3 into integer variables num1, num2 and num3.

Suggested Projects

If the file cannot be opened, the program should display an appropriate error message and search again. The program should then request a read radius 1 (fixed circle), radius 2 (moving circle) and offset position (fixed arm length).

Array Declaration

Static Declaration

Static Array Declaration

Dynamic Array Declaration

  • Dynamic Array Allocation

Accessing Array Elements

Array Bounds

However, if boundary checking is enabled (as mentioned in Chapter 3), the error will be caught when the program is run. C:\fortran> gfortran -fcheck=bounds -o hw hw.f95 This command will tell the 'gfortran' compiler to include bounds checking.

Implied Do-Loop

However, if an array element is accessed that is outside the declared bounds, it is an error.

Intrinsic Functions

Initializing Arrays

Example

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

Then the program will loop to read the numbers from the file and store them in an array. The program will check for any read errors (status variable > 0) and for end of file (status variable < 0).

Arrays of Strings

Exercises

Quiz Questions

Suggested Projects

The column name, like A, B, C, etc., are the array columns and the number is like the row. The particular syntax requires an index or subscript to specify which element of the array to access.

Array Declaration

Static Declaration

A static declaration means that the size or dimension of the array must be defined initially (before the program is compiled). When both numbers are specified, minor and major index, the dimension of the array will vary between the minor integer and the major integer.

Dynamic Declaration

In this example, the range for each dimension is 100, which means that each of the indices of the two dimensions will range from 1 to 100. Either or both ranges can be changed by specifying the ranges as:. smaller-integer: larger-integer, smaller-integer: larger-integer).

Dynamic Array Allocation

If the status variable is set to >0, an error occurred and the assignment failed. The variable allstat will be set to 0 if the allocation is successful and >0 if the allocation failed.

Accessing Array Elements

The size, 100 by 100 in this example, can be a parameter or variable, but must be an integer.

Example

Understand the Problem

Create the Algorithm

For this problem, testing will involve running the program using a range of different count values ​​and ensuring that the π estimate is reasonable and improves with higher count values.

Exercises

Quiz Questions

Suggested Projects

If a move takes you above the top row in the jth column, move to the bottom of the jth column and place the integer there. If a move takes you outside, to the right of the square in the ith row, place the integer in the ith row on the left.

Subprogram Types

When developing larger programs, it becomes necessary to break the larger programs into multiple, smaller, more manageable parts. And, for very large projects, many people can work on different parts of the program simultaneously.

Program Layout

Internal Routines

External Routines

Arguments

Argument Intent

Variable Scope

Using Functions and Subroutines

Argument Passing

If an actual argument is an expression, it is evaluated and passed to the corresponding formal argument. The arguments in the call are matched to the arguments in the function/subroutine by position.

Functions

Intrinsic Functions

User-Defined Functions

  • Side Effects

Subroutines

Variables declared in a function or subroutine are not the same as variables in the calling routine.

Example

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

The program will display an initial title and receive the number of games to play. Specifically, we will need to query the game count and verify that the count is between 2 and arbitrarily chosen).

Exercises

Quiz Questions

For this problem, the testing will involve running the program using a file with a set of numbers where the correct results are either known ahead of time or can be calculated by hand to verify that the results are accurate. A variable that will be passed into a subroutine, updated and returned to the calling routine.

Suggested Projects

The routine must request and read (x, y, z) and ensure that the values ​​of x, y, and z are between 0 and 100 (inclusive). The main program should call the subroutine three times and display the results for each call.

Definition

By using a derived data type, these separate pieces of information can be more easily grouped together. The details of defining, declaring, and using derived data types are provided in the following sections.

Declaration

Accessing Components

All components can be assigned to another variable of the same derived data type. This will copy all the components from the student1 variable to the student2 variable (since both student1 and student2 are of the same derived data type).

Example One

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

For this example, there are three parts; main, the read time subroutine, and the time summary subroutine. If the program does not work initially, the functionality of each subroutine should be checked.

Arrays of Derived Data

This code fragment will copy all components from the fifth array element (of type student) into a temporary variable (also of type student). Then the eleventh array element can be copied to the fifth array element (thereby overwriting all previous values).

Example Two

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

And finally, the eleventh array element can be set to the original values ​​of the fifth array element, which is held in the temporary variable. When determining the final degree, the nearest integer intrinsic function, nint(), can be used to perform the appropriate rounding.

Exercises

Quiz Questions

If the program does not work at first, the comments can help determine the problem. Additionally, write the necessary statement to declare two variables named earth and mars of type planet.

Suggested Projects

Test on multiple sets of input values ​​and verify that the output is correct for the given input values. Test on multiple sets of input values ​​and verify that the output is correct for the given input.

Module Declaration

Furthermore, modules can then be used more easily in other, different programs ensuring that the code can be easily reused. This section provides a description of the formatting requirements and an example of how to configure the modules.

Use Statement

Updated Compilation Commands

Once all the modules are compiled and the .o and .mod files are available, the main file can be compiled. This step reads the .o and .mod files for each module and builds the final executable.

Module Example Program

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
    • Main Program
    • Module Routines
  • Compile the Program
  • Test/Debug the Program

The name of the module, sphereRoutines in this example, must be the name of the secondary source file. If the program does not produce the correct results, each of the functions and subroutines can be verified individually.

Exercises

Quiz Questions

The second will read the files modmain.f95 and sphereroutines.o and then create the executable modmain.exe file. Once identified, some additional write statements inside the subroutine can be used to help identify the specific problem.

Suggested Projects

What statements are used in the secondary source file to define and name the module?. The examples in this section will not by themselves be sufficient for the reader to obtain recursive relief.

Recursive Subroutines

The goal of this section is to provide an introduction to the concept of recursion.

Recursive Print Binary Example

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

The main program ensures that the recursive routine is not called on invalid values ​​(ie, values ​​£ 0). If the program does not produce the correct results, the input to the recursive subroutine must be verified (by writing statements).

Recursive Functions

For this problem, testing involves running the program and entering a series of decimal values ​​to ensure that the results are correct. Then some additional write statements can be added in the recursive subroutine to provide insight into what is being done for each call.

Recursive Factorial Example

  • Understand the Problem
  • Create the Algorithm
  • Implement the Program
  • Test/Debug the Program

If the program does not return the correct result, the input to the recursive function must be verified (by writing statements). Then, some additional write statements in the recursive function can be added to give an overview of what is being done for each call.

Recursive Factorial Function Call Tree

It should also be noted that the height of the recursive tree is directly related to the amount of memory used by the recursive function. For problems where the recursion tree is very large, this can negatively affect the overall performance of the recursive routine.

Exercises

Quiz Questions

Suggested Projects

The function accepts a start coordinate (row,column) and an end coordinate (row,column). 6) The Tower of Hanoi is a mathematical puzzle consisting of three pegs and a number of discs of different sizes that can slide on each peg. Create a main program to read and validate the number of disks, n, from the user and make sure it is between 1 and 10.

Character String to Numeric Conversion

Basically, the read or write functions and associated format statements can be used to perform basic conversions. But the character string "3.1z4" could not be converted because 'z' is not a legal numeric value.

Numeric to Character String Conversion

The multiplication by 2 for each of the numeric values ​​was performed as an example only, since multiplication can only be performed on numeric data types (ie integer, real, or complex). Once the numeric values ​​are converted to strings, the character functions and character operations can be used as needed.

Exercises

Quiz Questions

Suggested Projects

The string should be concatenated with the "Amount is" string and displayed in the terminal using a single character string variable. Other system services include getting the date and/or time from the operating system and receiving command line arguments (if any).

Date and Time

  • Date and Time Options
  • Date and Time Example Program
  • Get Arguments
  • Command Line Arguments, Example Program

The handling of the command line arguments is entirely the responsibility of the program and not the operating system. Below is an example of the output for this program with valid command line arguments.

Exercises

Quiz Questions

You can assume that the variables for the command line argument (character) called args, length (integer) called arg3length, and status (integer) called arg3stat are already properly declared.

Suggested Projects

Specifically, there should be no extra spaces between the words or numbers (including the date value, 2 in the example). The filename should be created based on the current date in the following format .. file.txt”.

Working Files

Obtaining The Compiler

Windows Download and Install

MacOS Download and Install

Windows Compilation

Command Prompt Window

Device and Directory

Compiler Installation Verification

Compilation

Executing

Example

MacOS Compilation

Terminal Window

Device and Directory

Compiler Installation Verification

Compilation

Executing

Example

Initialization

Generating Random Number

Example

Example

Conversion Functions

Integer Functions

Real Functions

Character Functions

Complex Functions

Array Functions

System Information Functions

Obtaining GNUplot

Formatting Plot Files

Header

Footer

Plotting Files

Example

Plot Program

Plot File

Plot Output

Quiz Question Answers, Chapter 1

Quiz Question Answers, Chapter 2

Quiz Question Answers, Chapter 3

Quiz Question Answers, Chapter 4

Quiz Question Answers, Chapter 5

Quiz Question Answers, Chapter 6

Quiz Question Answers, Chapter 7

Quiz Question Answers, Chapter 8

Quiz Question Answers, Chapter 9

Quiz Question Answers, Chapter 10

Quiz Question Answers, Chapter 11

Quiz Question Answers, Chapter 12

Quiz Question Answers, Chapter 13

Quiz Question Answers, Chapter 14

Quiz Question Answers, Chapter 15

Quiz Question Answers, Chapter 16

Quiz Question Answers, Chapter 17

Quiz Question Answers, Chapter 18

Quiz Question Answers, Chapter 19

Quiz Question Answers, Chapter 20

Hình ảnh

Illustration 1: Computer ArchitectureScreen / Keyboard /
Illustration 2: Fortran 95/2003/2008 Compile Process

Tài liệu tham khảo