Credits-
Dr. C.-K. Shene
Professor
Department of Computer Science
Michigan Technological University
This presentation was downloaded from this link- http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/F90-Basics.pdf
Fortran is a high-level programming language that has been used for over half a century for computationally intensive applications like modeling, simulation, and engineering. It remains dominant in these fields. The document introduces Fortran, explains why it is still important to learn, and covers basic concepts like program structure, variables, input/output, and subroutines. It aims to provide an introduction to the Fortran programming language.
The document provides an overview of the FORTRAN programming language. It discusses the history and origins of FORTRAN as one of the oldest programming languages developed in 1957. Key features of FORTRAN include being machine independent, having a natural way to express mathematical functions, and efficient execution for number crunching applications in science and engineering. The document also demonstrates the basic structure of a FORTRAN program with declarations, execution, and termination sections. It shows a simple example program that reads input, performs a calculation, and outputs the result.
loops play a vital role in any programming language, they allow the programmer to write more readable and effective code. The looping concept also allows us to reduce the number of lines.
Problem Solving Techniques and Introduction to CPrabu U
This document provides an overview of problem solving techniques, programs, and the program development cycle. It discusses:
1. The steps of problem solving techniques include defining the problem, formulating a mathematical model, developing an algorithm using a flowchart or pseudocode, writing code, and testing the program.
2. A program consists of a series of instructions and fixed data to perform required operations. The program development cycle involves problem analysis, design, coding, compilation and execution, debugging and testing, and documentation.
3. An algorithm is a finite sequence of steps to solve a problem. Flowcharts use graphical symbols to represent the steps of an algorithm and show the program logic through connections between these symbols.
This document discusses decision making and loops in Python. It begins with an introduction to decision making using if/else statements and examples of checking conditions. It then covers different types of loops - for, while, and do-while loops. The for loop is used when the number of iterations is known, while the while loop is used when it is unknown. It provides examples of using range() with for loops and examples of while loops.
Get more from www.programmingcampus.com
Operators in c programming
-definition of operator
-types of operators
1.Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment & decrement operators.
a. pre and post increment operator
b. pre and post increment operator
6. Conditional operators.
7. Bitwise operators.
8. Special operators
The document discusses flowcharts, which are graphical representations of algorithms and programming logic. It provides examples of common flowchart symbols like terminals, inputs/outputs, processes, decisions, and connectors. It also outlines the typical steps for programming practices and techniques, which include defining requirements, creating a flowchart, dry running the flowchart to check for errors, writing source code, debugging, and documentation. Finally, it provides examples of flowcharts for simple programs like printing a message, calculating the sum of two numbers, and checking if a number is even or odd.
1) Newton Raphson method is a numerical technique used to find roots of algebraic and transcendental equations. It uses successive approximations, starting from an initial guess, to find better approximations for the roots of the equations.
2) The method involves calculating the derivative of the function f(x) and determining the next approximation using the formula xn+1 = xn - f(xn)/f'(xn).
3) An example of finding the root of x3 - 2x - 5 = 0 is shown, starting from an initial guess of 2.5 and iteratively applying the Newton Raphson formula to obtain the root as 2.094551482.
Fortran is a high-level programming language that has been used for over half a century for computationally intensive applications like modeling, simulation, and engineering. It remains dominant in these fields. The document introduces Fortran, explains why it is still important to learn, and covers basic concepts like program structure, variables, input/output, and subroutines. It aims to provide an introduction to the Fortran programming language.
The document provides an overview of the FORTRAN programming language. It discusses the history and origins of FORTRAN as one of the oldest programming languages developed in 1957. Key features of FORTRAN include being machine independent, having a natural way to express mathematical functions, and efficient execution for number crunching applications in science and engineering. The document also demonstrates the basic structure of a FORTRAN program with declarations, execution, and termination sections. It shows a simple example program that reads input, performs a calculation, and outputs the result.
loops play a vital role in any programming language, they allow the programmer to write more readable and effective code. The looping concept also allows us to reduce the number of lines.
Problem Solving Techniques and Introduction to CPrabu U
This document provides an overview of problem solving techniques, programs, and the program development cycle. It discusses:
1. The steps of problem solving techniques include defining the problem, formulating a mathematical model, developing an algorithm using a flowchart or pseudocode, writing code, and testing the program.
2. A program consists of a series of instructions and fixed data to perform required operations. The program development cycle involves problem analysis, design, coding, compilation and execution, debugging and testing, and documentation.
3. An algorithm is a finite sequence of steps to solve a problem. Flowcharts use graphical symbols to represent the steps of an algorithm and show the program logic through connections between these symbols.
This document discusses decision making and loops in Python. It begins with an introduction to decision making using if/else statements and examples of checking conditions. It then covers different types of loops - for, while, and do-while loops. The for loop is used when the number of iterations is known, while the while loop is used when it is unknown. It provides examples of using range() with for loops and examples of while loops.
Get more from www.programmingcampus.com
Operators in c programming
-definition of operator
-types of operators
1.Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment & decrement operators.
a. pre and post increment operator
b. pre and post increment operator
6. Conditional operators.
7. Bitwise operators.
8. Special operators
The document discusses flowcharts, which are graphical representations of algorithms and programming logic. It provides examples of common flowchart symbols like terminals, inputs/outputs, processes, decisions, and connectors. It also outlines the typical steps for programming practices and techniques, which include defining requirements, creating a flowchart, dry running the flowchart to check for errors, writing source code, debugging, and documentation. Finally, it provides examples of flowcharts for simple programs like printing a message, calculating the sum of two numbers, and checking if a number is even or odd.
1) Newton Raphson method is a numerical technique used to find roots of algebraic and transcendental equations. It uses successive approximations, starting from an initial guess, to find better approximations for the roots of the equations.
2) The method involves calculating the derivative of the function f(x) and determining the next approximation using the formula xn+1 = xn - f(xn)/f'(xn).
3) An example of finding the root of x3 - 2x - 5 = 0 is shown, starting from an initial guess of 2.5 and iteratively applying the Newton Raphson formula to obtain the root as 2.094551482.
Linear differential equation with constant coefficientSanjay Singh
The document discusses linear differential equations with constant coefficients. It defines the order, auxiliary equation, complementary function, particular integral and general solution. It provides examples of determining the complementary function and particular integral for different types of linear differential equations. It also discusses Legendre's linear equations, Cauchy-Euler equations, and solving simultaneous linear differential equations.
The document discusses Lagrange's equations for describing the motion of particles and systems with constraints. It provides an example of using generalized coordinates to derive the equation of motion for a simple pendulum in terms of the angular coordinate φ. The Lagrangian approach eliminates constraint forces and allows problems to be solved in any coordinate system using Lagrange's equations.
After the end of lesson you will be able to learn Python basics-What Python is? Its releases. Where we can use Python? Python Features. Tokens, comments variables etc... In out next PPT you will learn how to input and get output in Python
Theory of automata and formal language lab manualNitesh Dubey
The document describes several experiments related to compiler design including lexical analysis, parsing, and code generation.
Experiment 1 involves writing a program to identify if a given string is an identifier or not using a DFA. Experiment 2 simulates a DFA to check if a string is accepted by the given automaton. Experiment 3 checks if a string belongs to a given grammar using a top-down parsing approach. Experiment 4 implements recursive descent parsing to parse expressions based on a grammar. Experiment 5 computes FIRST and FOLLOW sets and builds a LL(1) parsing table for a given grammar. Experiment 6 implements shift-reduce parsing to parse strings. Experiment 7 generates intermediate code like Polish notation, 3-address code, and quadruples
This document discusses the Schrodinger wave equation for hydrogen atoms. It begins by presenting the time-independent 3D Schrodinger wave equation and explains how it is converted to polar coordinates due to the radial symmetry of hydrogen atoms. The wave function is assumed to separate into three parts, leading to three equations involving the principal, azimuthal, and magnetic quantum numbers. Quantum numbers and their relationships to orbital shapes are also described. Finally, atomic orbitals are defined as regions of high probability of finding electrons based on the Schrodinger wave equation solution.
Pointer is a variable that stores the address of another variable. Pointers in C are used to allocate memory dynamically at runtime and can point to data of any type such as int, float, char, etc. Pointers are declared with a * before the variable name and are initialized using the address operator &. Pointers can be used to pass arguments to functions by reference and can also point to elements within structures.
BoltzTraP is a software tool that uses linearized Boltzmann transport theory to calculate electronic transport properties from first-principles band structures. It can calculate properties like electrical conductivity, Seebeck coefficient, and electronic thermal conductivity. The document discusses applications of BoltzTraP to analyze transport properties of metals and thermoelectric materials. Key applications highlighted include analyzing anisotropy, resistivity temperature dependence, and optimizing the electronic structure of materials for high thermoelectric performance.
The document discusses the design and analysis of a D-flip flop. It begins by introducing flip flops and their use for storing state information. It then discusses the need for a D-flip flop due to limitations in the basic SR flip flop. A D-flip flop overcomes these limitations using a gated SR flip flop with an inverter between the S and R inputs, allowing a single data input. The circuit and working of the D-flip flop are shown, noting it will store and output the data input while the clock is high.
This document provides an overview of nuclear chemistry and radioactivity. It defines nuclear chemistry as the study of reactions involving changes in atomic nuclei. It describes the basics of atomic structure and the components of the nucleus. It then covers various nuclear reactions like radioactive decay, and types of radiation emitted. Key concepts discussed include radioactive half-life, rate of decay, and factors affecting nuclear stability. Classification of nuclides and various nuclear reactions like alpha, beta, and gamma decays are also summarized.
A recurrence relation defines a sequence based on a rule that gives the next term as a function of previous terms. There are three main methods to solve recurrence relations: 1) repeated substitution, 2) recursion trees, and 3) the master method. Repeated substitution repeatedly substitutes the recursive function into itself until it is reduced to a non-recursive form. Recursion trees show the successive expansions of a recurrence using a tree structure. The master method provides rules to determine the time complexity of divide and conquer recurrences.
This document discusses sequences and series. It provides definitions of key terms like sequence, finite sequence, infinite sequence, convergent sequence, divergent sequence, monotonic sequence, and geometric progression. It then goes on to solve 4 example problems:
1) It shows that the sequence 2n^2+n/n^2+1 is convergent by taking the limit as n approaches infinity.
2) It uses the ratio test to show that the sequence n!/n^n is convergent.
3) It proves that the sequence 1/1! + 1/2! +...+ 1/n! is convergent by showing it is increasing and bounded.
4) It shows that the sequence
The Reason Why we use master slave JK flip flop instead of simple level triggered flip flop is Racing condition which can be successfully avoided using two SR latches fed with inverted clocks.
This document provides an overview of the C programming language. It begins with an outline of topics covered, then defines C as a structured, high-level, machine-independent language that follows a top-down approach. The document traces the history and evolution of C from earlier languages like ALGOL and BCPL. It describes key features of C like portability, speed, and simplicity. It also explains the roles of compilers and linkers and includes flowcharts, sample programs, and discussions of variables, data types, operators, and control statements in C like if/else statements and switch cases.
1. Oscillations and waves can be free, damped, or forced. Free oscillations follow the differential equation of motion for simple harmonic motion.
2. Springs can be connected in series or parallel configurations. Springs in series have an equivalent spring constant that is the reciprocal of the sum of the reciprocals of the individual spring constants. Springs in parallel have an equivalent spring constant equal to the sum of the individual spring constants.
3. Complex notation can represent oscillations using a complex number with real and imaginary parts or using polar coordinates with magnitude and phase angle, providing an alternative representation of simple harmonic motion.
The document outlines an agenda for a workshop on programming errors in C language. It includes:
1. A warm up quiz, presentation on types of errors, and an activity on data types.
2. Using computers and writing a program in code blocks to practice.
3. An exit ticket at the end.
Types of errors discussed are syntax, logical, and runtime errors. Homework assignments are provided to have participants write programs in C to calculate efficiency, interior angles of polygons, and draw polygons to avoid errors. Testing programs is emphasized to avoid errors.
This presentation covers logical operators, precedence rules for operators, and other control statements in programming. It discusses the AND, OR, and NOT logical operators and provides examples. It also presents a summary of operator precedence from highest to lowest. Finally, it briefly explains the break, continue, and goto statements in code with examples for break and continue.
This document provides an overview of Python programming concepts including what Python is, variables, data types, operators, conditional statements, loops, functions, exceptions, lists, dictionaries, tuples and more. Some key points covered include:
- Python is an interpreted, object-oriented programming language that can be used for many different application types.
- Variables, constants, operators, and control flow structures like conditionals and loops are introduced as the basic building blocks of Python programs.
- Common data types like strings, lists, dictionaries and tuples are described along with their characteristics and functions.
- Other concepts explained are functions, exceptions, formatting, modules and more.
This document discusses various aspects of Fortran 77 programming including:
1. Variable names consist of letters and digits but are not case sensitive. Common declarations include integer and real variables.
2. Fortran 77 uses a fixed format with strict column rules for statements and labels. Comments can start in column 1.
3. A basic Fortran program structure includes the main program name, declarations, statements, and stop/end lines. Subprograms can also be included.
This document provides an overview of Fortran 77 programming concepts including input/output statements, format specifiers, and the OPEN statement. Key points covered include:
- READ and WRITE statements are used for formatted and list-directed input/output. FORMAT defines the format for READ/WRITE.
- Common format specifiers include I, F, E for integers, reals, and scientific notation. A is for characters.
- The OPEN statement makes a file available for input/output using READ and WRITE and assigns a unit number for file access.
Linear differential equation with constant coefficientSanjay Singh
The document discusses linear differential equations with constant coefficients. It defines the order, auxiliary equation, complementary function, particular integral and general solution. It provides examples of determining the complementary function and particular integral for different types of linear differential equations. It also discusses Legendre's linear equations, Cauchy-Euler equations, and solving simultaneous linear differential equations.
The document discusses Lagrange's equations for describing the motion of particles and systems with constraints. It provides an example of using generalized coordinates to derive the equation of motion for a simple pendulum in terms of the angular coordinate φ. The Lagrangian approach eliminates constraint forces and allows problems to be solved in any coordinate system using Lagrange's equations.
After the end of lesson you will be able to learn Python basics-What Python is? Its releases. Where we can use Python? Python Features. Tokens, comments variables etc... In out next PPT you will learn how to input and get output in Python
Theory of automata and formal language lab manualNitesh Dubey
The document describes several experiments related to compiler design including lexical analysis, parsing, and code generation.
Experiment 1 involves writing a program to identify if a given string is an identifier or not using a DFA. Experiment 2 simulates a DFA to check if a string is accepted by the given automaton. Experiment 3 checks if a string belongs to a given grammar using a top-down parsing approach. Experiment 4 implements recursive descent parsing to parse expressions based on a grammar. Experiment 5 computes FIRST and FOLLOW sets and builds a LL(1) parsing table for a given grammar. Experiment 6 implements shift-reduce parsing to parse strings. Experiment 7 generates intermediate code like Polish notation, 3-address code, and quadruples
This document discusses the Schrodinger wave equation for hydrogen atoms. It begins by presenting the time-independent 3D Schrodinger wave equation and explains how it is converted to polar coordinates due to the radial symmetry of hydrogen atoms. The wave function is assumed to separate into three parts, leading to three equations involving the principal, azimuthal, and magnetic quantum numbers. Quantum numbers and their relationships to orbital shapes are also described. Finally, atomic orbitals are defined as regions of high probability of finding electrons based on the Schrodinger wave equation solution.
Pointer is a variable that stores the address of another variable. Pointers in C are used to allocate memory dynamically at runtime and can point to data of any type such as int, float, char, etc. Pointers are declared with a * before the variable name and are initialized using the address operator &. Pointers can be used to pass arguments to functions by reference and can also point to elements within structures.
BoltzTraP is a software tool that uses linearized Boltzmann transport theory to calculate electronic transport properties from first-principles band structures. It can calculate properties like electrical conductivity, Seebeck coefficient, and electronic thermal conductivity. The document discusses applications of BoltzTraP to analyze transport properties of metals and thermoelectric materials. Key applications highlighted include analyzing anisotropy, resistivity temperature dependence, and optimizing the electronic structure of materials for high thermoelectric performance.
The document discusses the design and analysis of a D-flip flop. It begins by introducing flip flops and their use for storing state information. It then discusses the need for a D-flip flop due to limitations in the basic SR flip flop. A D-flip flop overcomes these limitations using a gated SR flip flop with an inverter between the S and R inputs, allowing a single data input. The circuit and working of the D-flip flop are shown, noting it will store and output the data input while the clock is high.
This document provides an overview of nuclear chemistry and radioactivity. It defines nuclear chemistry as the study of reactions involving changes in atomic nuclei. It describes the basics of atomic structure and the components of the nucleus. It then covers various nuclear reactions like radioactive decay, and types of radiation emitted. Key concepts discussed include radioactive half-life, rate of decay, and factors affecting nuclear stability. Classification of nuclides and various nuclear reactions like alpha, beta, and gamma decays are also summarized.
A recurrence relation defines a sequence based on a rule that gives the next term as a function of previous terms. There are three main methods to solve recurrence relations: 1) repeated substitution, 2) recursion trees, and 3) the master method. Repeated substitution repeatedly substitutes the recursive function into itself until it is reduced to a non-recursive form. Recursion trees show the successive expansions of a recurrence using a tree structure. The master method provides rules to determine the time complexity of divide and conquer recurrences.
This document discusses sequences and series. It provides definitions of key terms like sequence, finite sequence, infinite sequence, convergent sequence, divergent sequence, monotonic sequence, and geometric progression. It then goes on to solve 4 example problems:
1) It shows that the sequence 2n^2+n/n^2+1 is convergent by taking the limit as n approaches infinity.
2) It uses the ratio test to show that the sequence n!/n^n is convergent.
3) It proves that the sequence 1/1! + 1/2! +...+ 1/n! is convergent by showing it is increasing and bounded.
4) It shows that the sequence
The Reason Why we use master slave JK flip flop instead of simple level triggered flip flop is Racing condition which can be successfully avoided using two SR latches fed with inverted clocks.
This document provides an overview of the C programming language. It begins with an outline of topics covered, then defines C as a structured, high-level, machine-independent language that follows a top-down approach. The document traces the history and evolution of C from earlier languages like ALGOL and BCPL. It describes key features of C like portability, speed, and simplicity. It also explains the roles of compilers and linkers and includes flowcharts, sample programs, and discussions of variables, data types, operators, and control statements in C like if/else statements and switch cases.
1. Oscillations and waves can be free, damped, or forced. Free oscillations follow the differential equation of motion for simple harmonic motion.
2. Springs can be connected in series or parallel configurations. Springs in series have an equivalent spring constant that is the reciprocal of the sum of the reciprocals of the individual spring constants. Springs in parallel have an equivalent spring constant equal to the sum of the individual spring constants.
3. Complex notation can represent oscillations using a complex number with real and imaginary parts or using polar coordinates with magnitude and phase angle, providing an alternative representation of simple harmonic motion.
The document outlines an agenda for a workshop on programming errors in C language. It includes:
1. A warm up quiz, presentation on types of errors, and an activity on data types.
2. Using computers and writing a program in code blocks to practice.
3. An exit ticket at the end.
Types of errors discussed are syntax, logical, and runtime errors. Homework assignments are provided to have participants write programs in C to calculate efficiency, interior angles of polygons, and draw polygons to avoid errors. Testing programs is emphasized to avoid errors.
This presentation covers logical operators, precedence rules for operators, and other control statements in programming. It discusses the AND, OR, and NOT logical operators and provides examples. It also presents a summary of operator precedence from highest to lowest. Finally, it briefly explains the break, continue, and goto statements in code with examples for break and continue.
This document provides an overview of Python programming concepts including what Python is, variables, data types, operators, conditional statements, loops, functions, exceptions, lists, dictionaries, tuples and more. Some key points covered include:
- Python is an interpreted, object-oriented programming language that can be used for many different application types.
- Variables, constants, operators, and control flow structures like conditionals and loops are introduced as the basic building blocks of Python programs.
- Common data types like strings, lists, dictionaries and tuples are described along with their characteristics and functions.
- Other concepts explained are functions, exceptions, formatting, modules and more.
This document discusses various aspects of Fortran 77 programming including:
1. Variable names consist of letters and digits but are not case sensitive. Common declarations include integer and real variables.
2. Fortran 77 uses a fixed format with strict column rules for statements and labels. Comments can start in column 1.
3. A basic Fortran program structure includes the main program name, declarations, statements, and stop/end lines. Subprograms can also be included.
This document provides an overview of Fortran 77 programming concepts including input/output statements, format specifiers, and the OPEN statement. Key points covered include:
- READ and WRITE statements are used for formatted and list-directed input/output. FORMAT defines the format for READ/WRITE.
- Common format specifiers include I, F, E for integers, reals, and scientific notation. A is for characters.
- The OPEN statement makes a file available for input/output using READ and WRITE and assigns a unit number for file access.
This document discusses modern Fortran programming languages including Fortran90/95/2003/2008. It provides an outline covering motivation for using modern languages, an overview of features in modern Fortran like free format, attributes, implicit none, loops, and arrays. It discusses how modern Fortran fixes flaws in older versions by allowing allocatable arrays and using structures and derived types.
1) The document is a presentation for a Grade 1 Mandarin Chinese curriculum night that introduces the Chinese program to parents.
2) It outlines what students will learn through 5 units, language skills, assessment methods, homework policies, and ways for parents to support learning at home.
3) Resources mentioned include textbooks, online materials, reading programs, and ways for parents to contact the teachers for support.
Warner Bros has had several parent companies over the years, starting as an independent studio from 1918-1967 and then becoming a subsidiary to various companies until becoming owned by Time Warner from 1990 onward. As a subsidiary, Warner Bros also functions as a conglomerate itself, owning numerous other entertainment subsidiaries. Independent film companies have smaller budgets than major studios, making it harder to access resources, but they have more creative freedom and profit potential. Global companies like Time Warner that own film studios provide larger budgets but less autonomy over production decisions. Monopolies control entire markets while oligopolies see a few dominant companies, like the major six film studios, share market control.
This document promotes eMaps2day, a website that offers electronic maps of Africa to tourists and travelers. The maps can be easily used on computers and mobile devices and have finger swipe and zoom functions. Downloading the maps promotes green technology and raises funds for conservation projects across Southern Africa that protect ecosystems. Specifically, money is raised to support the Endangered Wildlife Trust and its projects focused on rhino poaching prevention and saving endangered species. The website also sells other electronic products to support additional conservation and ecotourism projects throughout Africa.
What brand journalism can do for your companySmartwords
This document discusses the role of brand journalism and how it differs from traditional journalism and marketing communications. It notes that brand journalists search for information from multiple sources, conduct interviews, and tell stories about a company or brand while maintaining editorial independence. Their goal is to build trust and provide an insider's perspective on a brand to help attract customers and prospects. The key is for brand journalists to abide by journalism ethics and not act as a mouthpiece for marketing while also addressing issues that could impact the brand.
This document discusses the importance of character education in schools. It proposes several methods to teach character education, including using a webquest to teach voting, having students make PSAs about bullying, creating podcasts about respect, and making QR codes and posters with videos modeling proper manners. The document emphasizes that both parents and educators share the duty of instructing children to become responsible, respectful adults through character education alongside academic lessons.
The document discusses Java's primitive data types including their ranges and literal constants. It covers char, boolean, byte, short, int, long, float, and double data types. It also discusses variables, symbolic constants, and arithmetic operators.
The document defines various tokens in the C programming language including keywords, identifiers, constants, string literals, operators, data types, and variables. It discusses the basic data types like integers, floating point numbers, and characters. It also covers topics like declarations, global and local variables, type conversions, precedence and order of evaluation, and various operators used in C.
What is the general format for a Try-Catch block Assume that amt l .docxajoy21
The document discusses command line arguments in C/C++ programs. It explains that command line arguments allow providing input to a program through command line instead of user input. The main() function needs to be defined as int main(int argc, char *argv[]) to access command line arguments. The argc parameter indicates number of arguments, while argv is an array containing the arguments as strings. Functions like atoi() and atof() are used to convert argument strings to int and double as arguments are received as char* by default. Examples demonstrate how to iterate through argv and access individual arguments.
This document provides an overview of Java programming basics, including application structure, data types, variables, expressions, operators, and comments. Key points include: all Java programs must contain at least one class; variables are used to store and name data; the basic data types are byte, short, int, long, float, double, char, and boolean; expressions use operators to manipulate data; and comments are used to explain code to others.
The document provides an introduction to PHP including its history, features, syntax, variables, data types, operators, conditional statements, loops, functions and string operations. It discusses how to install PHP, integrate it with Apache and use PHP tags to distinguish code from HTML. It also covers declaring variables, constants, arithmetic, relational and logical operators, conditional statements like if/else, loops like for and while, math and string functions.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, functions, and objects. It discusses JavaScript's origins, misunderstandings, dynamic and loosely typed nature, use of prototypes for inheritance rather than classes, and treatment of arrays and objects.
The JavaScript programming language is a multi-paradigm language that is misunderstood due to its name, design errors in early implementations, and use in web browsers. It is a functional language that uses objects, prototypes, and closures. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The JavaScript programming language is a functional language that is commonly misunderstood due to its name, mispositioning, design errors in early implementations, and use in web browsers. It was created in the 1990s and standardized as ECMAScript. JavaScript uses dynamic typing, loose typing, objects as general containers, and prototypal inheritance. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The JavaScript programming language is a multi-paradigm language that is misunderstood due to its name, design errors in early implementations, and use in web browsers. It is a functional language that uses objects, prototypes, and closures. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It discusses JavaScript's misunderstood nature due to its name, design errors in early implementations, and use in browsers. Some key points made include: JavaScript is a functional language; it uses prototypal inheritance instead of classes; all values are objects except for primitive values; and functions are first-class objects that can be assigned and passed around.
The JavaScript Programming Language document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It notes that JavaScript is a multi-paradigm scripting language that is misunderstood as only for web development. The document outlines JavaScript's core data types, objects, functions, and prototypal inheritance model.
This document provides an overview of various tokens and data types in the C programming language. It discusses keywords, identifiers, constants, strings, operators, variables, declarations, type conversions, and precedence rules. The key topics covered are:
- The basic tokens in C including keywords, identifiers, constants, strings, and white spaces.
- Integral and floating point data types such as int, char, float, and double.
- Rules for naming variables and declaring variables globally or locally.
- Arithmetic, relational, and logical operators in C and their precedence.
- Automatic and explicit type conversions between different data types.
OpenGurukul : Language : C ProgrammingOpen Gurukul
C is a general-purpose programming language that has been widely used since the early 1970s. Some key points about C programming covered in the document include:
- C was developed in the early 1970s and has since become widely popular for system and application software development due to its portability, efficiency, and ability to access hardware.
- C programs are typically structured using functions, header files, type definitions, and main functions. Input/output is handled using functions like printf and scanf.
- C supports basic data types like integers, floats, characters and strings. Variables must be declared before use and can be initialized.
- The document provides examples of C programs and covers basic concepts like constants
This document discusses various fundamental concepts in C programming such as flowcharts, pseudocode, control structures, variables, data types, operators, functions, arrays, structures, and input/output functions. It provides definitions and examples for each concept. Control structures covered include conditional statements like if-else and switch-case, as well as loops like while, do-while and for. Data types discussed are integer, floating point, character and string constants. Key concepts like variables, arrays, structures, functions and their declarations are also summarized.
The document discusses various components of the C language including variables, data types, operators, and input/output functions. It defines variables as memory locations identified by names that can store values. It describes different variable naming conventions and data types including primitive, derived, and user-defined types. The document also explains various arithmetic, relational, logical, and increment/decrement operators used to manipulate variable values. It provides examples of using printf() and scanf() functions for input and output.
The document provides an overview of key concepts in C++ programming, including:
- Functions break programs into small pieces that perform specific tasks.
- Variables store and represent data that can change, like integers and characters.
- Comments are used to explain source code and are ignored by the compiler.
- Data types like int, float, char and bool determine what kind of data a variable can hold.
- Operators perform actions like arithmetic calculations and assignment.
- Libraries contain precompiled functions that can be used across programs.
The document discusses various topics related to tokens, variables, data types, and operators in C programming. It defines tokens as the smallest elements identified by the compiler, such as keywords, identifiers, string literals, and operators. It describes different variable types like local variables, global variables, and static variables. It also explains various data types in C like integer, float, char, etc and their sizes and ranges. Finally, it discusses various arithmetic, relational, logical, and assignment operators in C and their precedence.
The document discusses input and output functions in C language like getchar, putchar, scanf, printf, gets and puts. It explains that these functions allow transfer of data between computer and standard input/output devices. Specifically, it describes the getchar and putchar functions for single character input/output, and the scanf and printf functions for transferring various data types including integers, floats and strings. It also briefly explains the gets and puts functions for string input/output.
Chapter-2 is for tokens in C programmingz9819898203
The document discusses tokens in the C programming language including keywords, identifiers, constants, string literals, operators, and white spaces. It also summarizes basic data types in C like integral types (char, short, int, long), floating point numbers (float, double), and how they are represented. It then covers numerical constants, character/string constants, variables, declarations of global and local variables, and arithmetic, relational, and logical operators in C.
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
How to Add Chatter in the odoo 17 ERP ModuleCeline George
In Odoo, the chatter is like a chat tool that helps you work together on records. You can leave notes and track things, making it easier to talk with your team and partners. Inside chatter, all communication history, activity, and changes will be displayed.
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
How to Fix the Import Error in the Odoo 17Celine George
An import error occurs when a program fails to import a module or library, disrupting its execution. In languages like Python, this issue arises when the specified module cannot be found or accessed, hindering the program's functionality. Resolving import errors is crucial for maintaining smooth software operation and uninterrupted development processes.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
1. Fortran 90 BasicsFortran 90 Basics
I don’t know what the programming languageI don t know what the programming language
of the year 2000 will look like, but I know it
will be called FORTRAN.
1
Charles Anthony Richard Hoare
Fall 2010
2. F90 Program StructureF90 Program Structure
A Fortran 90 program has the following form:A Fortran 90 program has the following form:
program-name is the name of that program
specification-part execution-part andspecification part, execution part, and
subprogram-part are optional.
Although IMPLICIT NONE is also optional, this isg p ,
required in this course to write safe programs.
PROGRAM program-name
IMPLICIT NONE
[ ifi ti t][specification-part]
[execution-part]
[subprogram-part]
2
[subprogram part]
END PROGRAM program-name
3. Program CommentsProgram Comments
Comments start with a !Comments start with a !
Everything following ! will be ignored
This is similar to // in C/C++This is similar to // in C/C++
! This is an example
!
PROGRAM Comment
..........
READ(*,*) Year ! read in the value of Year
....................
Year = Year + 1 ! add 1 to Year
..........
END PROGRAM Comment
3
END PROGRAM Comment
4. Continuation LinesContinuation Lines
Fortran 90 is not completely format-free!Fortran 90 is not completely format free!
A statement must starts with a new line.
If t t t i t l t fit li it hIf a statement is too long to fit on one line, it has
to be continued.
The continuation character is &, which is not
part of the statement.
Total = Total + &
Amount * Payments
! Total = Total + Amount*Payments! Total = Total + Amount*Payments
PROGRAM &
i i i
4
ContinuationLine
! PROGRAM ContinuationLine
5. AlphabetsAlphabets
Fortran 90 alphabets include the following:Fortran 90 alphabets include the following:
Upper and lower cases letters
Di itDigits
Special characters
space
' "
( ) * + - / : =
_ ! & $ ; < >
% ? , .
5
6. Constants: 1/6Constants: 1/6
A Fortran 90 constant may be an integer, real,A Fortran 90 constant may be an integer, real,
logical, complex, and character string.
We will not discuss complex constantsWe will not discuss complex constants.
An integer constant is a string of digits with an
optional sign: 12345 345 +789 +0optional sign: 12345, -345, +789, +0.
6
7. Constants: 2/6Constants: 2/6
A real constant has two forms, decimal andA real constant has two forms, decimal and
exponential:
In the decimal form a real constant is aIn the decimal form, a real constant is a
string of digits with exactly one decimal
point A real constant may include anpoint. A real constant may include an
optional sign. Example: 2.45, .13, 13.,
-0 12 - 120.12, .12.
7
8. Constants: 3/6Constants: 3/6
A real constant has two forms, decimal andA real constant has two forms, decimal and
exponential:
In the exponential form a real constantIn the exponential form, a real constant
starts with an integer/real, followed by a E/e,
followed by an integer (i e the exponent)followed by an integer (i.e., the exponent).
Examples:
12E3 (12 103) 12e3 ( 12 103)12E3 (12 103), -12e3 (-12 103),
3.45E-8 (3.45 10-8), -3.45e-8
( 3 45 10-8)(-3.45 10-8).
0E0 (0 100=0). 12.34-5 is wrong!
8
9. Constants: 4/6Constants: 4/6
A logical constant is either .TRUE. or .FALSE.g S
Note that the periods surrounding TRUE and
FALSE are required!FALSE are required!
9
10. Constants: 5/6Constants: 5/6
A character string or character constant is aA character string or character constant is a
string of characters enclosed between two
double quotes or two single quotes. Examples:double quotes or two single quotes. Examples:
“abc”, ‘John Dow’, “#$%^”, and ‘()()’.
The content of a character string consists of allThe content of a character string consists of all
characters between the quotes. Example: The
content of ‘John Dow’ is John Dowcontent of John Dow is John Dow.
The length of a string is the number of
h t b t th t Th l th fcharacters between the quotes. The length of
‘John Dow’is 8, space included.
10
11. Constants: 6/6Constants: 6/6
A string has length zero (i.e., no content) is ang g ( , )
empty string.
If single (or double) quotes are used in a string,g ( ) q g,
then use double (or single) quotes as delimiters.
Examples: “Adam’s cat” and ‘I said
“go away”’.
Two consecutive quotes are treated as one!
‘Lori’’s Apple’ is Lori’s Apple
“double quote””” is double quote”
`abc’’def”x’’y’ is abc’def”x’y
“abc””def’x””y” is abc”def’x”y
11
abc def x y is abc def x y
12. Identifiers: 1/2Identifiers: 1/2
A Fortran 90 identifier can have no more thanA Fortran 90 identifier can have no more than
31 characters.
The first one must be a letter The remainingThe first one must be a letter. The remaining
characters, if any, may be letters, digits, or
underscoresunderscores.
Fortran 90 identifiers are CASE INSENSITIVE.
Examples: A, Name, toTAL123, System_,
myFile_01, my_1st_F90_program_X_.
Identifiers Name, nAmE, naME and NamE are
the same.
12
13. Identifiers: 2/2Identifiers: 2/2
Unlike Java, C, C++, etc, Fortran 90 does not, , , ,
have reserved words. This means one may use
Fortran keywords as identifiers.
Therefore, PROGRAM, end, IF, then, DO, etc
may be used as identifiers. Fortran 90
compilers are able to recognize keywords from
their “positions” in a statement.
Yes, end = program + if/(goto –
while) is legal!
However, avoid the use of Fortran 90 keywords
as identifiers to minimize confusion.
13
14. Declarations: 1/3Declarations: 1/3
Fortran 90 uses the following for variableFortran 90 uses the following for variable
declarations, where type-specifier is one
of the following keywords: INTEGER, REAL,g y , ,
LOGICAL, COMPLEX and CHARACTER, and
list is a sequence of identifiers separated byq p y
commas.
type-specifier :: listtype specifier :: list
Examples:
INTEGER :: Zip, Total, counter
REAL :: AVERAGE, x, Difference
LOGICAL :: Condition, OK
14
COMPLEX :: Conjugate
15. Declarations: 2/3Declarations: 2/3
Character variables require additionalCharacter variables require additional
information, the string length:
Keyword CHARACTER must be followed byKeyword CHARACTER must be followed by
a length attribute (LEN = l) , where l is
the length of the stringthe length of the string.
The LEN= part is optional.
If the length of a string is 1, one may use
CHARACTER without length attribute.
Other length attributes will be discussed
later.
15
16. Declarations: 3/3Declarations: 3/3
Examples:Examples:
CHARACTER(LEN=20) :: Answer, Quote
Variables Answer and Quote can holdVariables Answer and Quote can hold
strings up to 20 characters.
CHARACTER(20) :: Answer, Quote is
the same as above.
CHARACTER :: Keypress means variable
Keypress can only hold ONE character (i.e.,
length 1).
16
17. The PARAMETER Attribute: 1/4The PARAMETER Attribute: 1/4
A PARAMETER identifier is a name whose value
cannot be modified. In other words, it is a
named constant.named constant.
The PARAMETER attribute is used after the type
keywordkeyword.
Each identifier is followed by a = and followed
b l f th t id tifiby a value for that identifier.
INTEGER PARAMETER :: MAXIMUM = 10INTEGER, PARAMETER :: MAXIMUM = 10
REAL, PARAMETER :: PI = 3.1415926, E = 2.17828
LOGICAL, PARAMETER :: TRUE = .true., FALSE = .false.
17
18. The PARAMETER Attribute: 2/4The PARAMETER Attribute: 2/4
Since CHARACTER identifiers have a lengthg
attribute, it is a little more complex when used
with PARAMETER.
Use (LEN = *) if one does not want to count
the number of characters in a PARAMETERthe number of characters in a PARAMETER
character string, where = * means the length of
this string is determined elsewherethis string is determined elsewhere.
CHARACTER(LEN=3), PARAMETER :: YES = “yes” ! Len = 3y
CHARACTER(LEN=2), PARAMETER :: NO = “no” ! Len = 2
CHARACTER(LEN=*), PARAMETER :: &
PROMPT = “What do you want?” ! Len = 17
18
19. The PARAMETER Attribute: 3/4The PARAMETER Attribute: 3/4
Since Fortran 90 strings are of fixed length, oneSince Fortran 90 strings are of fixed length, one
must remember the following:
If a string is longer than the PARAMETERIf a string is longer than the PARAMETER
length, the right end is truncated.
If a string is shorter than the PARAMETERIf a string is shorter than the PARAMETER
length, spaces will be added to the right.
CHARACTER(LEN=4), PARAMETER :: ABC = “abcdef”
CHARACTER(LEN=4), PARAMETER :: XYZ = “xy”
a b c dABC = x yXYZ =
19
a b c dABC yXYZ
20. The PARAMETER Attribute: 4/4The PARAMETER Attribute: 4/4
By convention, PARAMETER identifiers use ally ,
upper cases. However, this is not mandatory.
For maximum flexibility constants other than 0For maximum flexibility, constants other than 0
and 1 should be PARAMETERized.
A PARAMETER is an alias of a value and is not aA PARAMETER is an alias of a value and is not a
variable. Hence, one cannot modify the content of
a PARAMETER identifiera PARAMETER identifier.
One can may a PARAMETER identifier anywhere
in a program. It is equivalent to replacing the
identifier with its value.
20
The value part can use expressions.
21. Variable Initialization: 1/2Variable Initialization: 1/2
A variable receives its value withA variable receives its value with
Initialization: It is done once before the
program runsprogram runs.
Assignment: It is done when the program
t i t t t texecutes an assignment statement.
Input: It is done with a READ statement.
21
22. Variable Initialization: 2/2Variable Initialization: 2/2
Variable initialization is very similar to what weVariable initialization is very similar to what we
learned with PARAMETER.
A variable name is followed by a = followed byA variable name is followed by a =, followed by
an expression in which all identifiers must be
constants or PARAMETERs defined previouslyconstants or PARAMETERs defined previously.
Using an un-initialized variable may cause un-
t d ti di t ltexpected, sometimes disastrous results.
REAL :: Offset = 0.1, Length = 10.0, tolerance = 1.E-7
CHARACTER(LEN=2) :: State1 = "MI", State2 = "MD“
INTEGER, PARAMETER :: Quantity = 10, Amount = 435
INTEGER, PARAMETER :: Period = 3
22
INTEGER :: Pay = Quantity*Amount, Received = Period+5
23. Arithmetic OperatorsArithmetic Operators
There are four types of operators in Fortran 90:There are four types of operators in Fortran 90:
arithmetic, relational, logical and character.
The following shows the first three types:The following shows the first three types:
Type Operator Associativity
Arithmetic
** right to left
* / left to right
+ - left to right+ - left to right
Relational < <= > >= == /= none
.NOT. right to left
Logical
g f
.AND. left to right
.OR. left to right
23
.EQV. .NEQV. left to right
24. Operator PriorityOperator Priority
** is the highest; * and / are the next, followedg ; / ,
by + and -. All relational operators are next.
Of the 5 logical operators EQV and NEQVOf the 5 logical operators, .EQV. and .NEQV.
are the lowest.
Type Operator Associativity hi hType Operator Associativity
Arithmetic
** right to left
* / left to right
highest
priority
+ - left to right
Relational < <= > >= == /= none
Logical
.NOT. right to left
.AND. left to right
.OR. left to right
24
.OR. left to right
.EQV. .NEQV. left to right
25. Expression EvaluationExpression Evaluation
Expressions are evaluated from left to right.Expressions are evaluated from left to right.
If an operator is encountered in the process of
evaluation its priority is compared with that ofevaluation, its priority is compared with that of
the next one
if th t i l l t th tif the next one is lower, evaluate the current
operator with its operands;
if the next one is equal to the current, the
associativity laws are used to determine
which one should be evaluated;
if the next one is higher, scanning continues
25
26. Single Mode ExpressionSingle Mode Expression
A single mode arithmetic expression is anA single mode arithmetic expression is an
expression all of whose operands are of the
same type.same type.
If the operands are INTEGERs (resp., REALs),
the result is also an INTEGER (resp REAL)the result is also an INTEGER (resp., REAL).
1.0 + 2.0 * 3.0 / ( 6.0*6.0 + 5.0*44.0) ** 0.25
--> 1.0 + 6.0 / (6.0*6.0 + 5.0*44.0) ** 0.25
--> 1.0 + 6.0 / (36.0 + 5.0*44.0) ** 0.25
--> 1.0 + 6.0 / (36.0 + 220.0) ** 0.25
1 0 6 0 / 256 0 ** 0 25--> 1.0 + 6.0 / 256.0 ** 0.25
--> 1.0 + 6.0 / 4.0
--> 1.0 + 1.5
> 2 5
26
--> 2.5
27. Mixed Mode Expression: 1/2Mixed Mode Expression: 1/2
If operands have different types, it is mixedIf operands have different types, it is mixed
mode.
INTEGER and REAL yields REAL and theINTEGER and REAL yields REAL, and the
INTEGER operand is converted to REAL before
evaluation Example: 3 5*4 is converted toevaluation. Example: 3.5 4 is converted to
3.5*4.0 becoming single mode.
Exception: x**INTEGER: x**3 is x*x*x andException: x**INTEGER: x**3 is x*x*x and
x**(-3) is 1.0/(x*x*x).
i l d i h dx**REAL is evaluated with log() and exp().
Logical and character cannot be mixed with
27
arithmetic operands.
28. Mixed Mode Expression: 2/2Mixed Mode Expression: 2/2
Note that a**b**c is a**(b**c) instead of( )
(a**b)**c, and a**(b**c) (a**b)**c.
This can be a big trap!This can be a big trap!
5 * (11.0 - 5) ** 2 / 4 + 9
--> 5 * (11.0 - 5.0) ** 2 / 4 + 9
--> 5 * 6.0 ** 2 / 4 + 9
/--> 5 * 36.0 / 4 + 9
--> 5.0 * 36.0 / 4 + 9
--> 180.0 / 4 + 9
> 180 0 / 4 0 + 9
6.0**2 is evaluated as 6.0*6.0
rather than converted to 6.0**2.0!
--> 180.0 / 4.0 + 9
--> 45.0 + 9
--> 45.0 + 9.0
> 54 0
28
--> 54.0
red: type conversion
29. The Assignment Statement: 1/2The Assignment Statement: 1/2
The assignment statement has a form ofThe assignment statement has a form of
variable = expression
If the type of ariable and e pression areIf the type of variable and expression are
identical, the result is saved to variable.
If the type of variable and expression are
not identical, the result of expression is
fconverted to the type of variable.
If expression is REAL and variable is
INTEGER, the result is truncated.
29
30. The Assignment Statement: 2/2The Assignment Statement: 2/2
The left example uses an initialized variableThe left example uses an initialized variable
Unit, and the right uses a PARAMETER PI.
INTEGER :: Total, Amount
INTEGER :: Unit = 5
REAL, PARAMETER :: PI = 3.1415926
REAL :: Area
INTEGER :: Radius
Amount = 100.99
Total = Unit * Amount
INTEGER :: Radius
Radius = 5
Area = (Radius ** 2) * PI
This one is equivalent to Radius ** 2 * PI
30
31. Fortran Intrinsic Functions: 1/4Fortran Intrinsic Functions: 1/4
Fortran provides many commonly usedFortran provides many commonly used
functions, referred to as intrinsic functions.
To use an intrinsic function we need to know:To use an intrinsic function, we need to know:
Name and meaning of the function (e.g.,
SQRT() for square root)SQRT() for square root)
Number of arguments
The type and range of each argument (e.g.,
the argument of SQRT() must be non-
negative)
The type of the returned function value.
31
e ype o e e u ed u c o v ue.
32. Fortran Intrinsic Functions: 2/4Fortran Intrinsic Functions: 2/4
Some mathematical functions:Some mathematical functions:
Function Meaning Arg. Type Return Type
b l l f
INTEGER INTEGER
ABS(x) absolute value of x
REAL REAL
SQRT(x) square root of x REAL REAL
SIN(x) sine of x radian REAL REAL
COS(x) cosine of x radian REAL REAL
TAN(x) tangent of x radian REAL REALTAN(x) tangent of x radian REAL REAL
ASIN(x) arc sine of x REAL REAL
ACOS(x) arc cosine of x REAL REAL
ATAN(x) arc tangent of x REAL REAL
EXP(x) exponential ex REAL REAL
32
LOG(x) natural logarithm of x REAL REAL
LOG10(x) is the common logarithm of x!
33. Fortran Intrinsic Functions: 3/4Fortran Intrinsic Functions: 3/4
Some conversion functions:Some conversion functions:
Function Meaning Arg. Type Return Type
INT(x) truncate to integer part x REAL INTEGERINT(x) truncate to integer part x REAL INTEGER
NINT(x) round nearest integer to x REAL INTEGER
FLOOR(x) greatest integer less than or equal to x REAL INTEGER
FRACTION(x) the fractional part of x REAL REAL
REAL(x) convert x to REAL INTEGER REAL
INT(-3.5) -3
NINT(3.5) 4Examples:
NINT(-3.4) -3
FLOOR(3.6) 3
FLOOR(-3.5) -4
C O (12 3) 0 3
33
FRACTION(12.3) 0.3
REAL(-10) -10.0
34. Fortran Intrinsic Functions: 4/4Fortran Intrinsic Functions: 4/4
Other functions:Other functions:
Function Meaning Arg. Type Return Type
INTEGER INTEGER
MAX(x1, x2, ..., xn) maximum of x1, x2, ... xn
INTEGER INTEGER
REAL REAL
MIN(x1 x2 xn) minimum of x1 x2 xn
INTEGER INTEGER
MIN(x1, x2, ..., xn) minimum of x1, x2, ... xn
REAL REAL
MOD(x,y) remainder x - INT(x/y)*y
INTEGER INTEGER
REAL REAL
34
35. Expression EvaluationExpression Evaluation
Functions have the highest priority.
Function arguments are evaluated first.
The returned function value is treated as aThe returned function value is treated as a
value in the expression.
REAL :: A = 1.0, B = -5.0, C = 6.0, RREAL :: A 1.0, B 5.0, C 6.0, R
R = (-B + SQRT(B*B - 4.0*A*C))/(2.0*A)
/
R gets 3.0
(-B + SQRT(B*B - 4.0*A*C))/(2.0*A)
--> (5.0 + SQRT(B*B - 4.0*A*C))/(2.0*A)
--> (5.0 + SQRT(25.0 - 4.0*A*C))/(2.0*A)
--> (5.0 + SQRT(25.0 - 4.0*C))/(2.0*A)(5.0 SQRT(25.0 4.0 C))/(2.0 A)
--> (5.0 + SQRT(25.0 - 24.0))/(2.0*A)
--> (5.0 + SQRT(1.0))/(2.0*A)
--> (5.0 + 1.0)/(2.0*A)
6 0/(2 0* )
35
--> 6.0/(2.0*A)
--> 6.0/2.0
--> 3.0
36. What is IMPLICIT NONE?What is IMPLICIT NONE?
Fortran has an interesting tradition: allg
variables starting with i, j, k, l, m and n, if
not declared, are of the INTEGER type by
default.
This handy feature can cause serious
consequences if it is not used with care.
IMPLICIT NONE means all names must be
declared and there is no implicitly assumed
INTEGER type.
All programs in this class must use IMPLICIT
NONE. Points will be deducted if you do not use itPoints will be deducted if you do not use it!
36
37. List-Directed READ: 1/5List Directed READ: 1/5
Fortran 90 uses the READ(*,*) statement to( , )
read data into variables from keyboard:
READ(* *) v1 v2 vnREAD( , ) v1, v2, …, vn
READ(*,*)
The second form has a special meaning that will
be discussed later.
INTEGER :: Age
REAL :: Amount, Rate
CHARACTER(LEN=10) :: Name
READ(*,*) Name, Age, Rate, Amount
37
38. List-Directed READ: 2/5List Directed READ: 2/5
Data Preparation GuidelinesData Preparation Guidelines
READ(*,*) reads data from keyboard by
default although one may use inputdefault, although one may use input
redirection to read from a file.
If READ(* *) has n variables there mustIf READ(*,*) has n variables, there must
be n Fortran constants.
Each constant must have the type of the
corresponding variable. Integers can be
d i i bl b iread into REAL variables but not vice versa.
Data items are separated by spaces and may
38
spread into multiple lines.
39. List-Directed READ: 3/5List Directed READ: 3/5
The execution of READ(*,*) always starts withf ( , ) y
a new line!
Then it reads each constant into theThen, it reads each constant into the
corresponding variable.
CHARACTER(LEN=5) :: Name
REAL :: height, length
INTEGER :: count, MaxLength
READ(*,*) Name, height, count, length, MaxLength
"Smith" 100.0 25 123.579 10000Input:
39
put:
40. List-Directed READ: 4/5List Directed READ: 4/5
Be careful when input items are on multiple lines.Be careful when input items are on multiple lines.
INTEGER :: I,J,K,L,M,N
Input:
READ(*,*) I, J
READ(*,*) K, L, M
READ(*,*) N
100 200
300 400 500
600
INTEGER :: I,J,K,L,M,N
ignored!
READ(*,*) I, J, K
READ(*,*) L, M, N
100 200 300 400
500 600 700 800
900
READ(*,*) always starts with a new line
40
41. List-Directed READ: 5/5List Directed READ: 5/5
Since READ(*,*) always starts with a new line,( , ) y ,
a READ(*,*) without any variable means
skipping the input line!skipping the input line!
INTEGER :: P, Q, R, SINTEGER :: P, Q, R, S
READ(*,*) P, Q
READ(*,*)
100 200 300
400 500 600( , )
READ(*,*) R, S
400 500 600
700 800 900
41
42. List-Directed WRITE: 1/3List Directed WRITE: 1/3
Fortran 90 uses the WRITE(*,*) statement to( , )
write information to screen.
WRITE(* *) has two forms where exp1WRITE( , ) has two forms, where exp1,
exp2, …, expn are expressions
WRITE(* *) e p1 e p2 e pnWRITE(*,*) exp1, exp2, …, expn
WRITE(*,*)
WRITE(*,*) evaluates the result of each
expression and prints it on screen.
WRITE(*,*) always starts with a new line!
42
43. List-Directed WRITE: 2/3List Directed WRITE: 2/3
Here is a simple example:Here is a simple example:
INTEGER :: Target
means length is determined by actual count
REAL :: Angle, Distance
CHARACTER(LEN=*), PARAMETER :: &
Time = "The time to hit target “, &
IS = " is “, &
UNIT = " sec."
ti ti li Output:Target = 10
Angle = 20.0
Distance = 1350.0
WRITE(* *) 'A l ' A l
continuation lines Output:
Angle = 20.0
Distance = 1350.0
The time to hit target 10 is 27000.0 sec.
WRITE(*,*) 'Angle = ', Angle
WRITE(*,*) 'Distance = ', Distance
WRITE(*,*)
WRITE(* *) Time Target IS &
The time to hit target 10 is 27000.0 sec.
43
WRITE(*,*) Time, Target, IS, &
Angle * Distance, UNIT
print a blank line
44. List-Directed WRITE: 3/3List Directed WRITE: 3/3
The previous example used LEN=* , whichp p ,
means the length of a CHARACTER constant is
determined by actual count.
WRITE(*,*) without any expression advances
to the next line, producing a blank one.
A Fortran 90 compiler will use the best way to
print each value. Thus, indentation and
alignment are difficult to achieve with
WRITE(*,*).
One must use the FORMAT statement to produce
good looking output.
44
45. Complete Example: 1/4Complete Example: 1/4
This program computes the position (x and yp g p p ( y
coordinates) and the velocity (magnitude and direction)
of a projectile, given t, the time since launch, u, the
i i i i ilaunch velocity, a, the initial angle of launch (in degree),
and g=9.8, the acceleration due to gravity.
The horizontal and vertical displacements, x and y, are
computed as follows:
x u a tcos( )
g t2
y u a t
g t
sin( )
2
45
2
46. Complete Example: 2/4Complete Example: 2/4
The horizontal and vertical components of the velocityp y
vector are computed as
cos( )V u acos( )xV u a
sin( )yV u a g t
The magnitude of the velocity vector is
( )y g
V V V2 2
The angle between the ground and the velocity vector is
V V Vx y
2 2
tan( )
V
V
x
46
Vy
47. Complete Example: 3/4Complete Example: 3/4
Write a program to read in the launch angle a, the timep g g ,
since launch t, and the launch velocity u, and compute
the position, the velocity and the angle with the ground.
PROGRAM Projectile
IMPLICIT NONE
REAL, PARAMETER :: g = 9.8 ! acceleration due to gravity
REAL, PARAMETER :: PI = 3.1415926 ! you know this. don't you?
REAL :: Angle ! launch angle in degree
REAL :: Time ! time to flight
REAL :: Theta ! direction at time in degreeREAL :: Theta ! direction at time in degree
REAL :: U ! launch velocity
REAL :: V ! resultant velocity
REAL :: Vx ! horizontal velocity
REAL :: Vy ! vertical velocity
REAL :: X ! horizontal displacement
REAL :: Y ! vertical displacement
Other executable statements
47
…… Other executable statements ……
END PROGRAM Projectile
48. Complete Example: 4/4Complete Example: 4/4
Write a program to read in the launch angle a, the timep g g ,
since launch t, and the launch velocity u, and compute
the position, the velocity and the angle with the ground.
READ(*,*) Angle, Time, U
Angle = Angle * PI / 180.0 ! convert to radianAngle Angle PI / 180.0 ! convert to radian
X = U * COS(Angle) * Time
Y = U * SIN(Angle) * Time - g*Time*Time / 2.0
Vx = U * COS(Angle)g
Vy = U * SIN(Angle) - g * Time
V = SQRT(Vx*Vx + Vy*Vy)
Theta = ATAN(Vy/Vx) * 180.0 / PI ! convert to degree
WRITE(*,*) 'Horizontal displacement : ', X
WRITE(*,*) 'Vertical displacement : ', Y
48
WRITE(*,*) 'Resultant velocity : ', V
WRITE(*,*) 'Direction (in degree) : ', Theta
49. CHARACTER Operator //CHARACTER Operator //
Fortran 90 uses // to concatenate two strings.// g
If strings A and B have lengths m and n, the
concatenation A // B is a string of length m+nconcatenation A // B is a string of length m+n.
CHARACTER(LEN=4) :: John = "John", Sam = "Sam"
CHARACTER(LEN=6) :: Lori = "Lori", Reagan = "Reagan"
CHARACTER(LEN=10) :: Ans1, Ans2, Ans3, Ans4
Ans1 = John // Lori ! Ans1 = “JohnLori ”
Ans2 = Sam // Reagan ! Ans2 = “Sam Reagan”
Ans3 = Reagan // Sam ! Ans3 = “ReaganSam ”
Ans4 = Lori // Sam ! Ans4 = “Lori Sam ”
49
50. CHARACTER Substring: 1/3CHARACTER Substring: 1/3
A consecutive portion of a string is a substring.p g g
To use substrings, one may add an extent
specifier to a CHARACTER variable.p f
An extent specifier has the following form:
( integer-exp1 : integer-exp2 )( integer-exp1 : integer-exp2 )
The first and the second expressions indicate
the start and end: (3:8) means 3 to 8the start and end: (3:8) means 3 to 8,
If A = “abcdefg” , then A(3:5) means A’s
substring from position 3 to position 5 (i esubstring from position 3 to position 5 (i.e.,
“cde” ).
50
51. CHARACTER Substring: 2/3CHARACTER Substring: 2/3
In (integer-exp1:integer-exp2), if the( g p g p ),
first exp1 is missing, the substring starts from
the first character, and if exp2 is missing, the, p g,
substring ends at the last character.
If A = “12345678” then A(:5) is “12345”If A = 12345678 , then A(:5) is 12345
and A(3+x:) is “5678” where x is 2.
A d i ti i lAs a good programming practice, in general,
the first expression exp1 should be no less than
1 and the second expression exp2 should be no1, and the second expression exp2 should be no
greater than the length of the string.
51
52. CHARACTER Substring: 3/3CHARACTER Substring: 3/3
Substrings can be used on either side of theg
assignment operator.
Suppose LeftHand = “123456789”pp
(length is 10) .
LeftHand(3:5) = "abc” yields LeftHand =
“12abc67890”
LeftHand(4:) = "lmnopqr” yields
LeftHand = "123lmnopqr“LeftHand = "123lmnopqr“
LeftHand(3:8) = "abc” yields LeftHand =
"12abc 90“
LeftHand(4:7) = "lmnopq” yields
LeftHand = "123lmno890"
52
53. Example: 1/5Example: 1/5
This program uses the DATE AND TIME()p g _ _ ()
Fortran 90 intrinsic function to retrieve the
system date and system time. Then, it convertssystem date and system time. Then, it converts
the date and time information to a readable
format. This program demonstrates the use offormat. This program demonstrates the use of
concatenation operator // and substring.
System date is a string ccyymmdd where cc =System date is a string ccyymmdd, where cc
century, yy = year, mm = month, and dd = day.
System time is a string hhmmss.sss, where hh
= hour, mm = minute, and ss.sss = second.
53
54. Example: 2/5Example: 2/5
The following shows the specification part.g p p
Note the handy way of changing string length.
PROGRAM DateTime
IMPLICIT NONE
CHARACTER(LEN = 8) :: DateINFO ! ccyymmdd
CHARACTER(LEN = 4) :: Year, Month*2, Day*2
CHARACTER(LEN = 10) :: TimeINFO, PrettyTime*12 ! hhmmss.sss
CHARACTER(LEN = 2) :: Hour, Minute, Second*6
CALL DATE_AND_TIME(DateINFO, TimeINFO)
…… other executable statements ……
END PROGRAM DateTime
54
This is a handy way of changing string length
55. Example: 3/5Example: 3/5
Decompose DateINFO into year, month andp y ,
day. DateINFO has a form of ccyymmdd,
where cc = century, yy = year, mm = month,y, yy y , ,
and dd = day.
Year = DateINFO(1:4)
Month = DateINFO(5:6)
Day = DateINFO(7:8)
WRITE(* *) 'Date information -> ' DateINFOWRITE(*,*) Date information -> , DateINFO
WRITE(*,*) ' Year -> ', Year
WRITE(*,*) ' Month -> ', Month
WRITE(*,*) ' Day -> ', Day
Date information -> 19970811
Year -> 1997
Output:
55
Year -> 1997
Month -> 08
Day -> 11
56. Example: 4/5Example: 4/5
Now do the same for time:Now do the same for time:
Hour = TimeINFO(1:2)
Minute = TimeINFO(3:4)Minute = TimeINFO(3:4)
Second = TimeINFO(5:10)
PrettyTime = Hour // ':' // Minute // ':' // Second
WRITE(*,*)
WRITE(*,*) 'Time Information -> ', TimeINFO
WRITE(*,*) ' Hour -> ', Hour
WRITE(*,*) ' Minute -> ', Minute
WRITE(*,*) ' Second -> ', SecondWRITE( , ) Second > , Second
WRITE(*,*) ' Pretty Time -> ', PrettyTime
Time Information -> 010717.620
Hour -> 01
Minute -> 07
S d 17 620
Output:
56
Second -> 17.620
Pretty Time -> 01:07:17.620
57. Example: 5/5Example: 5/5
We may also use substring to achieve the samey g
result:
PrettyTime = “ “ ! Initialize to all blanks
PrettyTime( :2) = Hour
PrettyTime(3:3) = ':'PrettyTime(3:3) = ':'
PrettyTime(4:5) = Minute
PrettyTime(6:6) = ':'
PrettyTime(7: ) = SecondPrettyTime(7: ) = Second
WRITE(*,*)
WRITE(*,*) ' Pretty Time -> ', PrettyTimeWRITE( , ) Pretty Time > , PrettyTime
57
58. What KIND Is It?What KIND Is It?
Fortran 90 has a KIND attribute for selectingg
the precision of a numerical constant/variable.
The KIND of a constant/variable is a positiveThe KIND of a constant/variable is a positive
integer (more on this later) that can be attached
to a constantto a constant.
Example:
i i f126_3 : 126 is an integer of KIND 3
3.1415926_8 : 3.1415926 is a real of
KIND 8
58
59. What KIND Is It (INTEGER)? 1/2What KIND Is It (INTEGER)? 1/2
Function SELECTED_INT_KIND(k) selects the_ _
KIND of an integer, where the value of k, a
positive integer, means the selected integer
k kKIND has a value between -10k and 10k.
Thus, the value of k is approximately the
number of digits of that KIND. For example,
SELECTED_INT_KIND(10) means an integer
KIND of no more than 10 digitsKIND of no more than 10 digits.
If SELECTED_INT_KIND() returns -1, this
th h d d t t thmeans the hardware does not support the
requested KIND.
59
60. What KIND Is It (INTEGER)? 2/2What KIND Is It (INTEGER)? 2/2
SELECTED_INT_KIND() is usually used in the_ _ y
specification part like the following:
INTEGER, PARAMETER :: SHORT = SELECTED_INT_KIND(2)_ _
INTEGER(KIND=SHORT) :: x, y
The above declares an INTEGER PARAMETER
SHORT with SELECTED_INT_KIND(2), which is
the KIND of 2-digit integers.
Then, the KIND= attribute specifies that INTEGER
variables x and y can hold 2-digit integers.
In a program, one may use -12_SHORT and
9_SHORT to write constants of that KIND.
60
61. What KIND Is It (REAL)? 1/2What KIND Is It (REAL)? 1/2
Use SELECTED REAL KIND(k,e) to specify aS _ _ ( , ) p y
KIND for REAL constants/variables, where k is
the number of significant digits and e is thethe number of significant digits and e is the
number of digits in the exponent. Both k and e
must be positive integers.must be positive integers.
Note that e is optional.
SELECTED REAL KIND(7 3) selects a REALSELECTED_REAL_KIND(7,3) selects a REAL
KIND of 7 significant digits and 3 digits for the
t 0 10 yyyexponent: 0.xxxxxxx 10 yyy
61
62. What KIND Is It (REAL)? 2/2What KIND Is It (REAL)? 2/2
Here is an example:Here is an example:
INTEGER, PARAMETER :: &
SINGLE=SELECTED REAL KIND(7,2), &SINGLE=SELECTED_REAL_KIND(7,2), &
DOUBLE=SELECTED_REAL_KIND(15,3)
REAL(KIND=SINGLE) :: x
REAL(KIND=DOUBLE) :: Sum
123 4x = 123.45E-5_SINGLE
Sum = Sum + 12345.67890_DOUBLE
62
63. Why KIND, etc? 1/2Why KIND, etc? 1/2
Old Fortran used INTEGER*2, REAL*8,, ,
DOUBLE PRECISION, etc to specify the
“precision” of a variable. For example,
REAL*8 means the use of 8 bytes to store a real
value.
This is not very portable because some
computers may not use bytes as their basic
t it hil th t 2storage unit, while some others cannot use 2
bytes for a short integer (i.e., INTEGER*2).
M l t t h d fiMoreover, we also want to have more and finer
precision control.
63
64. Why KIND, etc? 2/2Why KIND, etc? 2/2
Due to the differences among computerDue to the differences among computer
hardware architectures, we have to be careful:
The requested KIND may not be satisfiedThe requested KIND may not be satisfied.
For example, SELECTED_INT_KIND(100)
may not be realistic on most computersmay not be realistic on most computers.
Compilers will find the best way good enough
(i e larger) for the requested KIND(i.e., larger) for the requested KIND.
If a “larger” KIND value is stored to a
“ ll ” i bl di bl“smaller” KIND variable, unpredictable
result may occur.
64
Use KIND carefully for maximum portability.
65. Fortran 90 Control StructuresFortran 90 Control Structures
Computer programming is an art form,
like the creation of poetry or music.
1
Donald Ervin Knuth
Fall 2010
66. LOGICAL VariablesLOGICAL Variables
A LOGIAL variable can only hold either .TRUE.y
or .FALSE. , and cannot hold values of any
other type.other type.
Use T or F for LOGICAL variable READ(*,*)
WRITE(* *) prints T or F for TRUEWRITE(*,*) prints T or F for .TRUE.
and .FALSE., respectively.
LOGICAL, PARAMETER :: Test = .TRUE.
LOGICAL :: C1, C2
C1 = .true. ! correct
C2 = 123 ! Wrong
READ(*,*) C1, C2
2
C2 = .false.
WRITE(*,*) C1, C2
67. Relational Operators: 1/4Relational Operators: 1/4
Fortran 90 has six relational operators: <, <=,p , ,
>, >=, ==, /=.
Each of these six relational operators takes twop
expressions, compares their values, and
yields .TRUE. or .FALSE.
Thus, a < b < c is wrong, because a < b is
LOGICAL and c is REAL or INTEGER.
COMPLEX values can only use == and /=
LOGICAL values should use .EQV. or .NEQV.
for equal and not-equal comparison.
3
68. Relational Operators: 2/4Relational Operators: 2/4
Relational operators have lower priority thanRelational operators have lower priority than
arithmetic operators, and //.
Thus 3 + 5 > 10 is FALSE and “a” //Thus, 3 + 5 > 10 is .FALSE. and a //
“b” == “ab” is .TRUE.
Ch t l d d Diff tCharacter values are encoded. Different
standards (e.g., BCD, EBCDIC, ANSI) have
diff t didifferent encoding sequences.
These encoding sequences may not be
compatible with each other.
4
69. Relational Operators: 3/4Relational Operators: 3/4
For maximum portability, only assume thep y, y
following orders for letters and digits.
Thus, “A” < “X”, ‘f’ <= “u”, and “2” <, , ,
“7” yield .TRUE. But, we don’t know the
results of “S” < “s” and “t” >= “%”.
However, equal and not-equal such as “S” /=
“s” and “t” == “5” are fine.
A < B < C < D < E < F < G < H < I < J < K < L < M < N
< O < P < Q < R < S < T < U < V < W < X < Y < Z
a < b < c < d < e < f < g < h < i < j < k < l < m < n
< o < p < q < r < s < t < u < v < w < x < y < z
5
0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9
70. Relational Operators: 4/4Relational Operators: 4/4
String comparison rules:g p
Start scanning from the first character.
If the current two are equal go for the nextIf the current two are equal, go for the next
If there is no more characters to compare, the
strings are equal (e.g., “abc” == “abc”)
If one string has no more character, the shorter
string is smaller (e.g., “ab” < “abc”
is TRUE )is .TRUE.)
If the current two are not equal, the string
has the smaller character is smaller (e ghas the smaller character is smaller (e.g.,
“abcd” is smaller than “abct”).
6
71. LOGICAL Operators: 1/2LOGICAL Operators: 1/2
There are 5 LOGICAL operators in Fortranp
90: .NOT., .OR., .AND., .EQV. and .NEQV.
NOT is the highest followed by OR.NOT. is the highest, followed by .OR.
and .AND., .EQV. and .NEQV. are the lowest.
Recall that NOT is evaluated from right to leftRecall that .NOT. is evaluated from right to left.
If both operands of .EQV. (equivalence) are the
isame, .EQV. yields .TRUE..
.NEQV. is the opposite of .EQV. (not equivalence).
If the operands of .NEQV. have different
values, .NEQV. yields .TRUE.
7
72. LOGICAL Operators: 2/2LOGICAL Operators: 2/2
If INTEGER variables m, n, x and y have, , y
values 3, 5, 4 and 2, respectively.
.NOT. (m > n .AND. x < y) .NEQV. (m <= n .AND. x >= y)
.NOT. (3 > 5 .AND. 4 < 2) .NEQV. (3 <= 5 .AND. 4 >= 2)
.NOT. (.FALSE. .AND. 4 < 2) .NEQV. (3 <= 5 .AND. 4 >= 2)
.NOT. (.FALSE. .AND. .FALSE.) .NEQV. (3 <= 5 .AND. 4 >= 2)
.NOT. .FALSE. .NEQV. (3 <= 5 .AND. 4 >= 2)
TRUE NEQV (3 5 AND 4 2).TRUE. .NEQV. (3 <= 5 .AND. 4 >= 2)
.TRUE. .NEQV. (.TRUE. .AND. 4 >= 2)
.TRUE. .NEQV. (.TRUE. .AND. .TRUE.)
TRUE NEQV TRUE.TRUE. .NEQV. .TRUE.
.FALSE.
8
.NOT. is higher than .NEQV.
73. IF-THEN-ELSE Statement: 1/4IF THEN ELSE Statement: 1/4
Fortran 90 has three if-then-else forms.
The most complete one is the IF-THEN-ELSE-
IF-END IF
An old logical IF statement may be very handy
when it is needed.
There is an old and obsolete arithmetic IF that
you are not encouraged to use. We won’t talky g
about it at all.
Details are in the next few slides.
9
74. IF-THEN-ELSE Statement: 2/4IF THEN ELSE Statement: 2/4
IF-THEN-ELSE-IF-END IF is the following.g
Logical expressions are evaluated sequentially (i.e., top-
down). The statement sequence that corresponds to the
expression evaluated to .TRUE. will be executed.
Otherwise, the ELSE sequence is executed.
IF (logical-expression-1) THEN
statement sequence 1
ELSE IF (logical expression 2) THENELSE IF (logical-expression-2) THEN
statement seqence 2
ELSE IF (logical-expression-3) THEN
statement sequence 3statement sequence 3
ELSE IF (.....) THEN
...........
ELSE
10
ELSE
statement sequence ELSE
END IF
75. IF-THEN-ELSE Statement: 3/4IF THEN ELSE Statement: 3/4
Two Examples:Two Examples:
Find the minimum of a, b and c
and saves the result to Result Letter grade for x
IF (a < b .AND. a < c) THEN
Result = a
ELSE IF (b < a .AND. b < c) THEN
INTEGER :: x
CHARACTER(LEN=1) :: Grade
and saves the result to Result g f
( )
Result = b
ELSE
Result = c
END IF
IF (x < 50) THEN
Grade = 'F'
ELSE IF (x < 60) THEN
G d 'D'END IF Grade = 'D'
ELSE IF (x < 70) THEN
Grade = 'C'
ELSE IF (x < 80) THEN( )
Grade = 'B'
ELSE
Grade = 'A'
END IF
11
END IF
76. IF-THEN-ELSE Statement: 4/4IF THEN ELSE Statement: 4/4
The ELSE-IF part and ELSE part are optional.p p p
If the ELSE part is missing and none of the
logical expressions is .TRUE., the IF-THEN-g p ,
ELSE has no effect.
no ELSE-IF no ELSE
IF (logical-expression-1) THEN
statement sequence 1
ELSE
IF (logical-expression-1) THEN
statement sequence 1
ELSE IF (logical-expression-2) THEN
statement sequence ELSE
END IF
statement sequence 2
ELSE IF (logical-expression-3) THEN
statement sequence 3
ELSE IF ( ) THENELSE IF (.....) THEN
...........
END IF
12
77. Example: 1/2Example: 1/2
Given a quadratic equation ax2 +bx + c = 0,Given a quadratic equation ax bx c 0,
where a 0, its roots are computed as follows:
b b2
4
x
b b a c
a
2
4
2
However, this is a very poor and unreliable way
of computing roots. Will return to this soon.
PROGRAM QuadraticEquation
IMPLICIT NONE
REAL :: a, b, c
REAL :: d
REAL :: root1, root2
13
…… other executable statement ……
END PROGRAM QuadraticEquation
78. Example: 2/2Example: 2/2
The following shows the executable partThe following shows the executable part
READ(*,*) a, b, c
WRITE(*,*) 'a = ', a
WRITE(*,*) 'b = ', b
WRITE(*,*) 'c = ', c
WRITE(*,*)
d = b*b - 4.0*a*c
IF (d >= 0.0) THEN ! is it solvable?
d = SQRT(d)
root1 = (-b + d)/(2.0*a) ! first root
root2 = (-b - d)/(2.0*a) ! second root
WRITE(* *) 'R t ' t1 ' d ' t2WRITE(*,*) 'Roots are ', root1, ' and ', root2
ELSE ! complex roots
WRITE(*,*) 'There is no real roots!'
WRITE(* *) 'Discriminant = ' d
14
WRITE(*,*) 'Discriminant = ', d
END IF
79. IF-THEN-ELSE Can be Nested: 1/2IF THEN ELSE Can be Nested: 1/2
Another look at the quadratic equation solver.Another look at the quadratic equation solver.
IF (a == 0.0) THEN ! could be a linear equation
IF (b == 0 0) THEN ! the input becomes c = 0IF (b == 0.0) THEN ! the input becomes c = 0
IF (c == 0.0) THEN ! all numbers are roots
WRITE(*,*) 'All numbers are roots'
ELSE ! unsolvableELSE ! unsolvable
WRITE(*,*) 'Unsolvable equation'
END IF
ELSE ! linear equation bx + c = 0ELSE ! linear equation bx + c 0
WRITE(*,*) 'This is linear equation, root = ', -c/b
END IF
ELSE ! ok, we have a quadratic equation, q q
...... solve the equation here ……
END IF
15
80. IF-THEN-ELSE Can be Nested: 2/2IF THEN ELSE Can be Nested: 2/2
Here is the big ELSE part:g S p
d b*b 4 0*a*cd = b*b - 4.0*a*c
IF (d > 0.0) THEN ! distinct roots?
d = SQRT(d)
root1 = (-b + d)/(2 0*a) ! first rootroot1 = (-b + d)/(2.0*a) ! first root
root2 = (-b - d)/(2.0*a) ! second root
WRITE(*,*) 'Roots are ', root1, ' and ', root2
ELSE IF (d == 0.0) THEN ! repeated roots?ELSE IF (d == 0.0) THEN ! repeated roots?
WRITE(*,*) 'The repeated root is ', -b/(2.0*a)
ELSE ! complex roots
WRITE(*,*) 'There is no real roots!'( , )
WRITE(*,*) 'Discriminant = ', d
END IF
16
81. Logical IFLogical IF
The logical IF is from Fortran 66, which is ang ,
improvement over the Fortran I arithmetic IF.
If logical-expression is .TRUE. , statement isg p ,
executed. Otherwise, execution goes though.
The statement can be assignment andg
input/output.
IF (logical-expression) statementIF (logical expression) statement
Smallest = b Cnt = Cnt + 1Smallest = b
IF (a < b) Smallest = a
Cnt = Cnt + 1
IF (MOD(Cnt,10) == 0) WRITE(*,*) Cnt
17
82. The SELECT CASE Statement: 1/7The SELECT CASE Statement: 1/7
Fortran 90 has the SELECT CASE statement forS S
selective execution if the selection criteria are
based on simple values in INTEGER, LOGICALp ,
and CHARACTER. No, REAL is not applicable.
SELECT CASE (selector)
CASE (label-list-1)
statements-1
CASE (label-list-2)
2
selector is an expression evaluated
to an INTEGER, LOGICAL or
CHARACTER value
statements-2
CASE (label-list-3)
statements-3
other cases
label-list is a set of constants or
PARAMETERS of the same type
…… other cases ……
CASE (label-list-n)
statements-n
CASE DEFAULT
yp
as the selector
statements is one or more
18
CASE DEFAULT
statements-DEFAULT
END SELECT
statements s o e o o e
executable statements
83. The SELECT CASE Statement: 2/7The SELECT CASE Statement: 2/7
The label-list is a list of the following forms:The label list is a list of the following forms:
value a specific value
al e1 al e2 values betweenvalue1 : value2 values between
value1 and value2, including value1 and
al e2 and al e1 < al e2value2, and value1 <= value2
value1 : values larger than or equal to
value1
: value2 values less than or equal to
value2
Reminder: value, value1 and value2 must
19
,
be constants or PARAMETERs.
84. The SELECT CASE Statement: 3/7The SELECT CASE Statement: 3/7
The SELECT CASE statement is SELECT CASE (selector)
executed as follows:
Compare the value of
SELECT CASE (selector)
CASE (label-list-1)
statements-1
CASE (label-list-2)
selector with the labels in
each case. If a match is
f d t th
( )
statements-2
CASE (label-list-3)
statements-3
found, execute the
corresponding statements.
If no match is found and if
…… other cases ……
CASE (label-list-n)
statements-n
If no match is found and if
CASE DEFAULT is there,
execute the statements-
CASE DEFAULT
statements-DEFAULT
END SELECT
DEFAULT.
Execute the next statement optional
20
following the SELECT CASE.
85. The SELECT CASE Statement: 4/7The SELECT CASE Statement: 4/7
Some important notes:Some important notes:
The values in label-lists should be unique.
Otherwise it is not known which CASEOtherwise, it is not known which CASE
would be selected.
CASE DEFAULT should be used whenever itCASE DEFAULT should be used whenever it
is possible, because it guarantees that there is
l t d thi ( )a place to do something (e.g., error message)
if no match is found.
b h iCASE DEFAULT can be anywhere in a
SELECT CASE statement; but, a preferred
l i h l i h li
21
place is the last in the CASE list.
86. The SELECT CASE Statement: 5/7The SELECT CASE Statement: 5/7
Two examples of SELECT CASE:p S S
CHARACTER(LEN=4) :: Title
INTEGER :: DrMD = 0, PhD = 0
CHARACTER(LEN=1) :: c
INTEGER :: DrMD 0, PhD 0
INTEGER :: MS = 0, BS = 0
INTEGER ::Others = 0
i
SELECT CASE (c)
CASE ('a' : 'j')
WRITE(*,*) ‘First ten letters'
SELECT CASE (Title)
CASE ("DrMD")
DrMD = DrMD + 1
CASE ("PhD")
CASE ('l' : 'p', 'u' : 'y')
WRITE(*,*) &
'One of l,m,n,o,p,u,v,w,x,y'
CASE ('z', 'q' : 't')CASE ( PhD )
PhD = PhD + 1
CASE ("MS")
MS = MS + 1
( )
CASE ( z , q : t )
WRITE(*,*) 'One of z,q,r,s,t'
CASE DEFAULT
WRITE(*,*) 'Other characters'
CASE ("BS")
BS = BS + 1
CASE DEFAULT
Others = Others + 1
END SELECT
22
Ot e s Ot e s
END SELECT
87. The SELECT CASE Statement: 6/7The SELECT CASE Statement: 6/7
Here is a more complex example:Here is a more complex example:
INTEGER :: Number, Range Number Range Why?
<= -10 1 CASE (:-10, 10:)
SELECT CASE (Number)
CASE ( : -10, 10 : )
Range = 1
<= 10 1 CASE (: 10, 10:)
-9,-8,-7,-6 6 CASE DEFAULT
-5,-4,-3 2 CASE (-5:-3, 6:9)
CASE (-5:-3, 6:9)
Range = 2
CASE (-2:2)
-2,-1,0,1,2 3 CASE (-2:2)
3 4 CASE (3, 5)
Range = 3
CASE (3, 5)
Range = 4
4 5 CASE (4)
5 4 CASE (3, 5)
6,7,8,9 2 CASE (-5:-3, 6:9)
CASE (4)
Range = 5
CASE DEFAULT
R 6
6,7,8,9 2 CASE ( 5: 3, 6:9)
>= 10 1 CASE (:-10, 10:)
23
Range = 6
END SELECT
88. The SELECT CASE Statement: 7/7The SELECT CASE Statement: 7/7
PROGRAM CharacterTesting
IMPLICIT NONE
CHARACTER(LEN=1) :: Input
This program reads in a character and
determines if it is a vowel, a consonant,
CHARACTER(LEN=1) :: Input
READ(*,*) Input
SELECT CASE (Input)
CASE ('A' : 'Z', 'a' : 'z') ! rule out letters
a digit, one of the four arithmetic operators,
a space, or something else (i.e., %, $, @, etc).
WRITE(*,*) 'A letter is found : "', Input, '"'
SELECT CASE (Input) ! a vowel ?
CASE ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o','u')
WRITE(* *) 'It is a vowel'WRITE( , ) It is a vowel
CASE DEFAULT ! it must be a consonant
WRITE(*,*) 'It is a consonant'
END SELECT
CASE ('0' : '9') ! a digit
WRITE(*,*) 'A digit is found : "', Input, '"'
CASE ('+', '-', '*', '/') ! an operator
WRITE(*,*) 'An operator is found : "', Input, '"'WRITE( , ) An operator is found : , Input,
CASE (' ') ! space
WRITE(*,*) 'A space is found : "', Input, '"'
CASE DEFAULT ! something else
24
WRITE(*,*) 'Something else found : "', Input, '"'
END SELECT
END PROGRAM CharacterTesting
89. The Counting DO Loop: 1/6The Counting DO Loop: 1/6
Fortran 90 has two forms of DO loop: thep
counting DO and the general DO.
The counting DO has the following form:The counting DO has the following form:
DO control-var = initial, final [, step]
statementsstatements
END DO
control-var is an INTEGER variable,control var is an INTEGER variable,
initial, final and step are INTEGER
expressions; however, step cannot be zero.expressions; however, step cannot be zero.
If step is omitted, its default value is 1.
t bl t t t f th O
25
statements are executable statements of the DO.
90. The Counting DO Loop: 2/6The Counting DO Loop: 2/6
Before a DO-loop starts, expressions initial,p , p ,
final and step are evaluated exactly once.
When executing the DO-loop, these values willg p,
not be re-evaluated.
Note again the value of step cannot be zeroNote again, the value of step cannot be zero.
If step is positive, this DO counts up; if step is
negative this DO counts downnegative, this DO counts down
DO control-var = initial final [ step]DO control-var = initial, final [, step]
statements
END DO
26
91. The Counting DO Loop: 3/6The Counting DO Loop: 3/6
If step is positive:p p
The control-var receives the value of initial.
If the value of control-var is less than or equal toIf the value of control var is less than or equal to
the value of final, the statements part is executed.
Then, the value of step is added to control-var,
and goes back and compares the values of
control-var and final.
If the value of control-var is greater than the
value of final, the DO-loop completes and the
statement following END DO is executedstatement following END DO is executed.
27
92. The Counting DO Loop: 4/6The Counting DO Loop: 4/6
If step is negative:p g
The control-var receives the value of initial.
If the value of control-var is greater than orIf the value of control var is greater than or
equal to the value of final, the statements part is
executed. Then, the value of step is added to
control-var, goes back and compares the values
of control-var and final.
If the value of control-var is less than the value
of final, the DO-loop completes and the statement
following END DO is executedfollowing END DO is executed.
28
93. The Counting DO Loop: 5/6The Counting DO Loop: 5/6
Two simple examples:Two simple examples:
INTEGER :: N, k odd integers
between 1 & N
READ(*,*) N
WRITE(*,*) “Odd number between 1 and “, N
DO k = 1, N, 2
between 1 & N
WRITE(*,*) k
END DO
INTEGER, PARAMETER :: LONG = SELECTED_INT_KIND(15)
INTEGER(KIND=LONG) :: Factorial, i, N
READ(* *) N
factorial of N
READ(*,*) N
Factorial = 1_LONG
DO i = 1, N
Factorial = Factorial * i
29
END DO
WRITE(*,*) N, “! = “, Factorial
94. The Counting DO Loop: 6/6The Counting DO Loop: 6/6
Important Notes:Important Notes:
The step size step cannot be zero
N h th l f i bl iNever change the value of any variable in
control-var and initial, final, and
stepstep.
For a count-down DO-loop, step must be
i “ ” inegative. Thus, “do i = 10, -10” is not
a count-down DO-loop, and the statements
portion is not executed.
Fortran 77 allows REAL variables in DO; but,
30
don’t use it as it is not safe.
95. General DO-Loop with EXIT: 1/2General DO Loop with EXIT: 1/2
The general DO-loop has the following form:The general DO loop has the following form:
DO
statementsstatements
END DO
t t t ill b t d t dlstatements will be executed repeatedly.
To exit the DO-loop, use the EXIT or CYCLE
statement.
The EXIT statement brings the flow of control to
the statement following (i.e., exiting) the END DO.
The CYCLE statement starts the next iteration
31
e C C state e t sta ts t e e t te at o
(i.e., executing statements again).
96. General DO-Loop with EXIT: 2/2General DO Loop with EXIT: 2/2
REAL PARAMETER :: Lower = 1 0 Upper = 1 0 Step = 0 25REAL, PARAMETER :: Lower = -1.0, Upper = 1.0, Step = 0.25
REAL :: x
x = Lower ! initialize the control variable
DO
IF (x > Upper) EXIT ! is it > final-value?
WRITE(*,*) x ! no, do the loop body
x = x + Step ! increase by step-sizex = x + Step ! increase by step-size
END DO
INTEGER :: InputINTEGER :: Input
DO
WRITE(*,*) 'Type in an integer in [0, 10] please --> '
READ(*,*) Input
IF (0 <= Input .AND. Input <= 10) EXIT
WRITE(*,*) 'Your input is out of range. Try again'
END DO
32
END DO
97. Example, exp(x): 1/2Example, exp(x): 1/2
The exp(x) function has an infinite series:The exp(x) function has an infinite series:
exp( )
! !
....
!
......x x
x x x
i
i
1
2 3
2 3
Sum each term until a term’s absolute value is
! ! !i2 3
less than a tolerance, say 0.00001.
PROGRAM Exponential
IMPLICIT NONE
INTEGER :: Count ! # of terms used
REAL :: Term ! a term
REAL :: Sum ! the sum
REAL :: X ! the input x
REAL, PARAMETER :: Tolerance = 0.00001 ! tolerance
33
…… executable statements ……
END PROGRAM Exponential
98. Example, exp(x): 2/2Example, exp(x): 2/2
Note:
1
( 1)! ! 1
i i
x x x
i i i
This is not a good solution, though.
( 1)! ! 1i i i
This is not a good solution, though.
READ(*,*) X ! read in x
Count = 1 ! the first term is 1
iSum = 1.0 ! thus, the sum starts with 1
Term = X ! the second term is x
DO ! for each term
IF (ABS(T ) < T l ) EXIT ! if t ll itIF (ABS(Term) < Tolerance) EXIT ! if too small, exit
Sum = Sum + Term ! otherwise, add to sum
Count = Count + 1 ! count indicates the next term
Term = Term * (X / Count) ! compute the value of next termTerm = Term * (X / Count) ! compute the value of next term
END DO
WRITE(*,*) 'After ', Count, ' iterations:'
WRITE(* *) ' Exp(' X ') = ' Sum
34
WRITE( , ) Exp( , X, ) = , Sum
WRITE(*,*) ' From EXP() = ', EXP(X)
WRITE(*,*) ' Abs(Error) = ', ABS(Sum - EXP(X))
99. Example, Prime Checking: 1/2Example, Prime Checking: 1/2
A positive integer n >= 2 is a prime number if theA positive integer n 2 is a prime number if the
only divisors of this integer are 1 and itself.
If n = 2 it is a primeIf n = 2, it is a prime.
If n > 2 is even (i.e., MOD(n,2) == 0), not a prime.
If n is odd, then:
If the odd numbers between 3 and n-1 cannot
divide n, n is a prime!
Do we have to go up to n-1? No, SQRT(n) isg p , Q ( )
good enough. Why?
35
100. Example, Prime Checking: 2/2Example, Prime Checking: 2/2
INTEGER :: Number ! the input number
INTEGER :: Divisor ! the running divisor
READ(*,*) Number ! read in the input
IF (Number < 2) THEN ! not a prime if < 2
WRITE(* *) 'Illegal input'WRITE(*,*) 'Illegal input'
ELSE IF (Number == 2) THEN ! is a prime if = 2
WRITE(*,*) Number, ' is a prime'
ELSE IF (MOD(Number,2) == 0) THEN ! not a prime if even
WRITE(*,*) Number, ' is NOT a prime'
ELSE ! an odd number here
Divisor = 3 ! divisor starts with 3
DO ! divide the input numberDO ! divide the input number
IF (Divisor*Divisor > Number .OR. MOD(Number, Divisor) == 0) EXIT
Divisor = Divisor + 2 ! increase to next odd
END DO
IF (Divisor*Divisor > Number) THEN ! which condition fails?
WRITE(*,*) Number, ' is a prime'
ELSE
WRITE(* *) Number ' is NOT a prime'
36
WRITE(*,*) Number, is NOT a prime
END IF
END IF
this is better than SQRT(REAL(Divisor)) > Number
101. Finding All Primes in [2,n]: 1/2Finding All Primes in [2,n]: 1/2
The previous program can be modified to findThe previous program can be modified to find
all prime numbers between 2 and n.
PROGRAM Primes
IMPLICIT NONE
INTEGER :: Range, Number, Divisor, Count
WRITE(*,*) 'What is the range ? '
DO ! keep trying to read a good input
READ(*,*) Range ! ask for an input integer
IF (Range >= 2) EXIT ! if it is GOOD, exit
WRITE(*,*) 'The range value must be >= 2. Your input = ', Range
WRITE(*,*) 'Please try again:' ! otherwise, bug the user
END DOEND DO
…… we have a valid input to work on here ……
END PROGRAM Primes
37
102. Finding All Primes in [2,n]: 2/2Finding All Primes in [2,n]: 2/2
Count = 1 ! input is correct. start counting
WRITE(*,*) ! 2 is a prime
WRITE(*,*) 'Prime number #', Count, ': ', 2
DO Number = 3, Range, 2 ! try all odd numbers 3, 5, 7, ...
Divisor = 3 ! divisor starts with 3
DO
i i i i i iIF (Divisor*Divisor > Number .OR. MOD(Number,Divisor) == 0) EXIT
Divisor = Divisor + 2 ! not a divisor, try next
END DO
IF (Divisor*Divisor > Number) THEN ! divisors exhausted?IF (Divisor Divisor > Number) THEN ! divisors exhausted?
Count = Count + 1 ! yes, this Number is a prime
WRITE(*,*) 'Prime number #', Count, ': ', Number
END IF
END DO
WRITE(*,*)
WRITE(*,*) 'There are ', Count, ' primes in the range of 2 and ', Range
38
( , ) e e a e , Cou t, p es t e a ge o a d , a ge
103. Factoring a Number: 1/3Factoring a Number: 1/3
Given a positive integer, one can always factorizep g , y
it into prime factors. The following is an
example:
586390350 = 2 3 52 72 13 17 192
Here, 2, 3, 5, 7, 13, 17 and 19 are prime factors., , , , , , p
It is not difficult to find all prime factors.
We can repeatedly divide the input by 2.We can repeatedly divide the input by 2.
Do the same for odd numbers 3, 5, 7, 9, ….
But we said “prime” factors No problemBut, we said “prime” factors. No problem,
multiples of 9 are eliminated by 3 in an earlier
stage!
39
stage!
104. Factoring a Number: 2/3Factoring a Number: 2/3
PROGRAM Factorize
IMPLICIT NONE
INTEGER :: Input
INTEGER :: Divisor
INTEGER :: Count
WRITE(*,*) 'This program factorizes any integer >= 2 --> '
READ(*,*) Input
Count = 0
DO ! remove all factors of 2
IF (MOD(I t 2) / 0 OR I t 1) EXITIF (MOD(Input,2) /= 0 .OR. Input == 1) EXIT
Count = Count + 1 ! increase count
WRITE(*,*) 'Factor # ', Count, ': ', 2
Input = Input / 2 ! remove this factorInput = Input / 2 ! remove this factor
END DO
…… use odd numbers here ……
END PROGRAM Factorize
40
END PROGRAM Factorize
105. Factoring a Number: 3/3Factoring a Number: 3/3
Divisor = 3 ! now we only worry about odd factors
DO ! Try 3, 5, 7, 9, 11 ....
IF (Divisor > Input) EXIT ! factor is too large, exit and done
DO ! try this factor repeatedlyDO ! try this factor repeatedly
IF (MOD(Input,Divisor) /= 0 .OR. Input == 1) EXIT
Count = Count + 1
WRITE(*,*) 'Factor # ', Count, ': ', Divisor
Input = Input / Divisor ! remove this factor from Input
END DO
Divisor = Divisor + 2 ! move to next odd number
END DOEND DO
Note that even 9 15 49 will be used they would only be usedNote that even 9, 15, 49, … will be used, they would only be used
once because Divisor = 3 removes all multiples of 3 (e.g., 9, 15, …),
Divisor = 5 removes all multiples of 5 (e.g., 15, 25, …), and
Divisor = 7 removes all multiples of 7 (e.g., 21, 35, 49, …), etc.
41
Divisor 7 removes all multiples of 7 (e.g., 21, 35, 49, …), etc.
106. Handling End-of-File: 1/3Handling End of File: 1/3
Very frequently we don’t know the number ofVery frequently we don t know the number of
data items in the input.
Fortran uses IOSTAT= for I/O error handling:Fortran uses IOSTAT= for I/O error handling:
READ(*,*,IOSTAT=v) v1, v2, …, vn
In the above, v is an INTEGER variable.
After the execution of READ(*,*):
If v = 0, READ(*,*) was executed successfully
If v > 0, an error occurred in READ(*,*) and not
all variables received values.
If v < 0, encountered end-of-file, and not all
42
variables received values.
107. Handling End-of-File: 2/3Handling End of File: 2/3
Every file is ended with a special character.Every file is ended with a special character.
Unix and Windows use Ctrl-D and Ctrl-Z.
When using keyboard to enter data toWhen using keyboard to enter data to
READ(*,*), Ctrl-D means end-of-file in Unix.
If IOSTAT returns a positive value we onlyIf IOSTAT= returns a positive value, we only
know something was wrong in READ(*,*) such
t i t h h fil d i tas type mismatch, no such file, device error, etc.
We really don’t know exactly what happened
because the returned value is system dependent.
43
108. Handling End-of-File: 3/3Handling End of File: 3/3
i t t t
INTEGER :: io, x, sum 1
3
The total is 8
input output
sum = 0
DO
READ(*,*,IOSTAT=io) x
IF (io > 0) THEN
4
inputIF (io > 0) THEN
WRITE(*,*) 'Check input. Something was wrong'
EXIT
ELSE IF (io < 0) THEN
(* *) h l i
1
&
4
no output
WRITE(*,*) 'The total is ', sum
EXIT
ELSE
sum = sum + x
END IF
END DO
44
109. Computing Means, etc: 1/4Computing Means, etc: 1/4
Let us compute the arithmetic, geometric andLet us compute the arithmetic, geometric and
harmonic means of unknown number of values:
arithmetic mean =
x x xn1 2 ......
arithmetic mean =
geometric mean =
n
x x xn
n
1 2 ......
harmonic mean =
n
1 1 1
Note that only positive values will be considered
x x xn1 2
......
Note that only positive values will be considered.
This naïve way is not a good method.
45
110. Computing Means, etc: 2/4Computing Means, etc: 2/4
PROGRAM ComputingMeansPROGRAM ComputingMeans
IMPLICIT NONE
REAL :: X
REAL :: Sum, Product, InverseSum, ,
REAL :: Arithmetic, Geometric, Harmonic
INTEGER :: Count, TotalValid
INTEGER :: IO ! for IOSTAT=
Sum = 0.0
Product = 1.0
InverseSum = 0.0
TotalValid = 0
Count = 0
…… other computation part ……
END PROGRAM ComputingMeans
46
111. Computing Means, etc: 3/4Computing Means, etc: 3/4
DO
READ(*,*,IOSTAT=IO) X ! read in data
IF (IO < 0) EXIT ! IO < 0 means end-of-file reached
Count = Count + 1 ! otherwise, got some value
IF (IO > 0) THEN ! IO > 0 means something wrongIF (IO > 0) THEN ! IO > 0 means something wrong
WRITE(*,*) 'ERROR: something wrong in your input'
WRITE(*,*) 'Try again please'
ELSE ! IO = 0 means everything is normal
WRITE(*,*) 'Input item ', Count, ' --> ', X
IF (X <= 0.0) THEN
WRITE(*,*) 'Input <= 0. Ignored'
ELSEELSE
TotalValid = TotalValid + 1
Sum = Sum + X
Product = Product * X
InverseSum = InverseSum + 1.0/X
END IF
END IF
END DO
47
END DO
112. Computing Means, etc: 4/4Computing Means, etc: 4/4
WRITE(*,*)
IF (TotalValid > 0) THEN
Arithmetic = Sum / TotalValid
Geometric = Product**(1.0/TotalValid)
Harmonic = TotalValid / InverseSum
WRITE(*,*) '# of items read --> ', Count
WRITE(*,*) '# of valid items -> ', TotalValidWRITE( , ) # of valid items > , TotalValid
WRITE(*,*) 'Arithmetic mean --> ', Arithmetic
WRITE(*,*) 'Geometric mean --> ', Geometric
WRITE(*,*) 'Harmonic mean --> ', Harmonic
ELSE
WRITE(*,*) 'ERROR: none of the input is positive'
END IF
48
113. Fortran 90 ArraysFortran 90 Arrays
Program testing can be used to show the presence of bugsProgram testing can be used to show the presence of bugs,
but never to show their absence
Edsger W. Dijkstra
1
Fall 2009
114. The DIMENSION Attribute: 1/6The DIMENSION Attribute: 1/6
A Fortran 90 program uses the DIMENSIONp g
attribute to declare arrays.
The DIMENSION attribute requires threeq
components in order to complete an array
specification, rank, shape, and extent.
The rank of an array is the number of “indices”
or “subscripts.” The maximum rank is 7 (i.e.,
seven-dimensional).
The shape of an array indicates the number of
elements in each “dimension.”
2
115. The DIMENSION Attribute: 2/6The DIMENSION Attribute: 2/6
The rank and shape of an array is representedThe rank and shape of an array is represented
as (s1,s2,…,sn), where n is the rank of the array
and si (1 i n) is the number of elements in theand si (1 i n) is the number of elements in the
i-th dimension.
(7) means a rank 1 array with 7 elements(7) means a rank 1 array with 7 elements
(5,9) means a rank 2 array (i.e., a table)
h fi t d d di i h 5whose first and second dimensions have 5
and 9 elements, respectively.
(10,10,10,10) means a rank 4 array that has
10 elements in each dimension.
3
116. The DIMENSION Attribute: 3/6The DIMENSION Attribute: 3/6
The extent is written as m:n, where m and n (mThe extent is written as m:n, where m and n (m
n) are INTEGERs. We saw this in the SELECT
CASE, substring, etc., g,
Each dimension has its own extent.
A t t f di i i th f itAn extent of a dimension is the range of its
index. If m: is omitted, the default is 1.
i i i 3 2 1 0-3:2 means possible indices are -3, -2 , -1, 0,
1, 2
5:8 means possible indices are 5,6,7,8
7 means possible indices are 1,2,3,4,5,6,7
4
p , , , , , ,
117. The DIMENSION Attribute: 4/6The DIMENSION Attribute: 4/6
The DIMENSION attribute has the followingg
form:
DIMENSION(extent-1, extent-2, …, extent-n)( , , , )
Here, extent-i is the extent of dimension i.
This means an array of dimension n (i.e., nThis means an array of dimension n (i.e., n
indices) whose i-th dimension index has a range
given by extent-i.g y
Just a reminder: Fortran 90 only allows
maximum 7 dimensions.
Exercise: given a DIMENSION attribute,
determine its shape.
5
p
118. The DIMENSION Attribute: 5/6The DIMENSION Attribute: 5/6
Here are some examples:Here are some examples:
DIMENSION(-1:1) is a 1-dimensional
array with possible indices -1 0 1array with possible indices -1,0,1
DIMENSION(0:2,3) is a 2-dimensional
(i t bl ) P ibl l f tharray (i.e., a table). Possible values of the
first index are 0,1,2 and the second 1,2,3
i 3 i iDIMENSION(3,4,5) is a 3-dimensional
array. Possible values of the first index are
1,2,3, the second 1,2,3,4, and the third
1,2,3,4,5.
6
119. The DIMENSION Attribute: 6/6The DIMENSION Attribute: 6/6
Array declaration is simple. Add they p
DIMENSION attribute to a type declaration.
Values in the DIMENSION attribute are usuallyy
PARAMETERs to make program modifications
easier.
INTEGER, PARAMETER :: SIZE=5, LOWER=3, UPPER = 5
INTEGER, PARAMETER :: SMALL = 10, LARGE = 15
REAL, DIMENSION(1:SIZE) :: x
INTEGER, DIMENSION(LOWER:UPPER,SMALL:LARGE) :: a,b, ( , ) ,
LOGICAL, DIMENSION(2,2) :: Truth_Table
7
120. Use of Arrays: 1/3Use of Arrays: 1/3
Fortran 90 has, in general, three different ways, g , y
to use arrays: referring to individual array
element, referring to the whole array, and
referring to a section of an array.
The first one is very easy. One just starts with
the array name, followed by () between which
are the indices separated by ,.
Note that each index must be an INTEGER or an
expression evaluated to an INTEGER, and the
l f i d t b i th f thvalue of an index must be in the range of the
corresponding extent. But, Fortran 90 won’t
check it for you
8
check it for you.
121. Use of Arrays: 2/3Use of Arrays: 2/3
Suppose we have the following declarationsSuppose we have the following declarations
INTEGER, PARAMETER :: L_BOUND = 3, U_BOUND = 10
INTEGER, DIMENSION(L BOUND:U BOUND) :: xINTEGER, DIMENSION(L_BOUND:U_BOUND) :: x
DO i = L_BOUND, U_BOUND
x(i) = i
DO i = L_BOUND, U_BOUND
IF (MOD(i,2) == 0) THEN
iEND DO x(i) = 0
ELSE
x(i) = 1
array x() has 3,4,5,…, 10
END IF
END DO
array x() has 1 0 1 0 1 0 1 0
9
array x() has 1,0,1,0,1,0,1,0
122. Use of Arrays: 3/3Use of Arrays: 3/3
Suppose we have the following declarations:
INTEGER, PARAMETER :: L_BOUND = 3, U_BOUND = 10
INTEGER, DIMENSION(L_BOUND:U_BOUND, &
L_BOUND:U_BOUND) :: a
DO i = L_BOUND, U_BOUND
DO j = L_BOUND, U_BOUND
a(i j) = 0
DO i = L_BOUND, U_BOUND
DO j = i+1, U_BOUND
t = a(i,j)a(i,j) = 0
END DO
a(i,i) = 1
t a(i,j)
a(i,j) = a(j,i)
a(j,i) = t
END DO
END DO END DO
generate an identity matrix Swapping the lower and
upper diagonal parts (i e
10
upper diagonal parts (i.e.,
the transpose of a matrix)
123. The Implied DO: 1/7The Implied DO: 1/7
Fortran has the implied DO that can generatep g
efficiently a set of values and/or elements.
The implied DO is a variation of the DO-loop.p p
The implied DO has the following syntax:
(item-1 item-2 item-n v=initial final step)(item 1, item 2, …,item n, v=initial,final,step)
Here, item-1, item-2, …, item-n are
variables or expressions, v is an INTEGERvariables or expressions, v is an INTEGER
variable, and initial, final, and step are
INTEGER expressions.p
“v=initial,final,step” is exactly what we
saw in a DO-loop.
11
p
124. The Implied DO: 2/7The Implied DO: 2/7
The execution of an implied DO below lets variablep
v to start with initial, and step though to
final with a step size step.
(item 1 item 2 item n v=initial final step)(item-1, item-2, …,item-n, v=initial,final,step)
The result is a sequence of items.
(i+1, i=1,3) generates 2 3 4(i+1, i=1,3) generates 2, 3, 4.
(i*k, i+k*i, i=1,8,2) generates k, 1+k (i
= 1), 3*k, 3+k*3 (i = 3), 5*k, 5+k*5 (i = 5),), , ( ), , ( ),
7*k, 7+k*7 (i = 7).
(a(i),a(i+2),a(i*3-1),i*4,i=3,5)
t (3) ( ) (8) 12 (i 3) (4)generates a(3), a(5), a(8) , 12 (i=3), a(4),
a(6), a(11), 16 (i=4), a(5), a(7), a(14), 20.
12
125. The Implied DO: 3/7The Implied DO: 3/7
Implied DO may be nested.p y
(i*k,(j*j,i*j,j=1,3), i=2,4)
In the above (j*j i*j j 1 3) is nested inIn the above, (j*j,i*j,j=1,3) is nested in
the implied i loop.
Here are the results:
When i = 2, the implied DO generates
2*k, (j*j,2*j,j=1,3)
Then j goes from 1 to 3 and generatesThen, j goes from 1 to 3 and generates
2*k, 1*1, 2*1, 2*2, 2*2, 3*3, 2*3
j = 1 j = 2 j = 3
13
j = 1 j = 2 j = 3
126. The Implied DO: 4/7The Implied DO: 4/7
Continue with the previous examplep p
(i*k,(j*j,i*j,j=1,3), i=2,4)
When i = 3, it generates the following:g g
3*k, (j*j,3*j,j=1,3)
Expanding the j loop yields:p g j p y
3*k, 1*1, 3*1, 2*2, 3*2, 3*3, 3*3
When i = 4, the i loop generates, p g
4*k, (j*j, 4*j, j=1,3)
Expanding the j loop yieldsp g j p y
4*k, 1*1, 4*1, 2*2, 4*2, 3*3, 4*3
14j = 1 j = 2 j = 3
127. The Implied DO: 5/7The Implied DO: 5/7
The following generates a multiplication table:The following generates a multiplication table:
((i*j,j=1,9),i=1,9)
When i 1 the inner j implied DO loopWhen i = 1, the inner j implied DO-loop
produces 1*1, 1*2, …, 1*9
When i = 2, the inner j implied DO-loop
produces 2*1, 2*2, …, 2*9
When i = 9, the inner j implied DO-loop
produces 9*1, 9*2, …, 9*9
15
128. The Implied DO: 6/7The Implied DO: 6/7
The following produces all upper triangularThe following produces all upper triangular
entries, row-by-row, of a 2-dimensional array:
((a(p q) q = p n) p = 1 n)((a(p,q),q = p,n),p = 1,n)
When p = 1, the inner q loop produces a(1,1),
a(1 2) a(1 n)a(1,2), …, a(1,n)
When p=2, the inner q loop produces a(2,2),
a(2,3), …., a(2,n)
When p=3, the inner q loop produces a(3,3),
a(3,4), …, a(3,n)
When p=n, the inner q loop produces a(n,n)
16
p , q p p ( , )
129. The Implied DO: 7/7The Implied DO: 7/7
The following produces all upper triangularThe following produces all upper triangular
entries, column-by-column:
((a(p q) p = 1 q) q = 1 n)((a(p,q),p = 1,q),q = 1,n)
When q=1, the inner p loop produces a(1,1)
When q=2, the inner p loop produces a(1,2),
a(2,2)
When q=3, the inner p loop produces a(1,3),
a(2,3), …, a(3,3)
When q=n, the inner p loop produces a(1,n),
a(2,n), a(3,n), …, a(n,n)
17
( , ), ( , ), , ( , )
130. Array Input/Output: 1/8Array Input/Output: 1/8
Implied DO can be used in READ(*,*) andp ( , )
WRITE(*,*) statements.
When an implied DO is used it is equivalent toWhen an implied DO is used, it is equivalent to
execute the I/O statement with the generated
elementselements.
The following prints out a multiplication table
(* *)((i * j i*j j 1 9) i 1 9)WRITE(*,*)((i,“*”,j,“=“,i*j,j=1,9),i=1,9)
The following has a better format (i.e., 9 rows):
DO i = 1, 9
WRITE(*,*) (i, “*”, j, “=“, i*j, j=1,9)
18
END DO
131. Array Input/Output: 2/8Array Input/Output: 2/8
The following shows three ways of reading ng y g
data items into an one dimensional array a().
Are they the same?Are they the same?
READ(*,*) n,(a(i),i=1,n)(1)
READ(*,*) n
i i
( )
(2)
READ(*,*) (a(i),i=1,n)
READ(* *) n(3) READ(*,*) n
DO i = 1, n
READ(*,*) a(i)
(3)
19
END DO
132. Array Input/Output: 3/8Array Input/Output: 3/8
Suppose we wish to fill a(1), a(2) and a(3)pp ( ), ( ) ( )
with 10, 20 and 30. The input may be:
3 10 20 303 10 20 30
Each READ starts from a new line!
OKREAD(*,*) n,(a(i),i=1,n)
READ(* *) n
(1)
(2)
OK
Wrong! n gets 3 andREAD(*,*) n
READ(*,*) (a(i),i=1,n)
(2)
Wrong! n gets 3 and
the second READ fails
READ(*,*) n
DO i = 1, n
(3) Wrong! n gets 3 and
the three READs fail
20
READ(*,*) a(i)
END DO
133. Array Input/Output: 4/8Array Input/Output: 4/8
What if the input is changed to the following?What if the input is changed to the following?
3
10 20 30
OK
10 20 30
READ(*,*) n,(a(i),i=1,n)
READ(* *) n
(1)
(2)
OK
OK. Why????READ(*,*) n
READ(*,*) (a(i),i=1,n)
(2)
OK. Why????
READ(*,*) n
DO i = 1, n
(3) Wrong! n gets 3, a(1) has
10; but, the next two
READs fail
21
READ(*,*) a(i)
END DO
READs fail
134. Array Input/Output: 5/8Array Input/Output: 5/8
What if the input is changed to the following?What if the input is changed to the following?
3
10
20
OK
20
30
READ(*,*) n,(a(i),i=1,n)
READ(* *) n
(1)
(2)
OK
OKREAD(*,*) n
READ(*,*) (a(i),i=1,n)
(2)
OK
READ(*,*) n
DO i = 1, n
(3) OK
22
READ(*,*) a(i)
END DO
135. Array Input/Output: 6/8Array Input/Output: 6/8
Suppose we have a two-dimensional array a():pp y ()
INTEGER, DIMENSION(2:4,0:1) :: a
Suppose further the READ is the following:Suppose further the READ is the following:
READ(*,*) ((a(i,j),j=0,1),i=2,4)
What are the results for the following input?
1 2 3
1 2 3 4 5 6
1 2 3
4 5 6
7 8 9
0 1 0 1
1 2
3 4
1 2
3 4
2
3
2
3
0 1 0 1
23
3 4
5 6
3 4
5 64 4
136. Array Input/Output: 7/8Array Input/Output: 7/8
Suppose we have a two-dimensional array a():pp y ()
INTEGER, DIMENSION(2:4,0:1) :: a
DO i = 2 4DO i = 2, 4
READ(*,*) (a(i,j),j=0,1)
END DOEND DO
What are the results for the following input?
1 2 3 4 5 6
1 2 3
4 5 6
7 8 97 8 9
1 2 1 2A(2,0)=1 row-by-row2
0 1 0 1
24
? ?
? ?
4 5
7 8
A(2,1)=2
then error!
y
3
4
137. Array Input/Output: 8/8Array Input/Output: 8/8
Suppose we have a two-dimensional array a():pp y ()
INTEGER, DIMENSION(2:4,0:1) :: a
DO j = 0 1DO j = 0, 1
READ(*,*) (a(i,j),i=2,4)
END DOEND DO
What are the results for the following input?
1 2 3 4 5 6
1 2 3
4 5 6
7 8 97 8 9
1 ? 1 4
A(2,0)=1
A(3,0)=2 column-by-column2
0 1 0 1
25
2 ?
3 ?
2 5
3 6
A(4,0)=3
then error!
y
3
4
138. Matrix Multiplication: 1/2Matrix Multiplication: 1/2
Read a l m matrix Al m and a m n matrix Bm n,Read a l m matrix Al m and a m n matrix Bm n,
and compute their product Cl n = Al m Bm n.
PROGRAM Matrix MultiplicationPROGRAM Matrix_Multiplication
IMPLICIT NONE
INTEGER, PARAMETER :: SIZE = 100
INTEGER DIMENSION(1:SIZE 1:SIZE) :: A B CINTEGER, DIMENSION(1:SIZE,1:SIZE) :: A, B, C
INTEGER :: L, M, N, i, j, k
READ(*,*) L, M, N ! read sizes <= 100
iDO i = 1, L
READ(*,*) (A(i,j), j=1,M) ! A() is L-by-M
END DO
DO i = 1, M
READ(*,*) (B(i,j), j=1,N) ! B() is M-by-N
END DO
26
…… other statements ……
END PROGRAM Matrix_Multiplication
139. Matrix Multiplication: 2/2Matrix Multiplication: 2/2
The following does multiplication and outputThe following does multiplication and output
DO i = 1, L
DO j = 1, N
C(i,j) = 0 ! for each C(i,j)
DO k = 1, M ! (row i of A)*(col j of B)
C(i,j) = C(i,j) + A(i,k)*B(k,j)
END DO
END DOEND DO
END DO
DO i = 1 L ! print row-by-rowDO i = 1, L ! print row-by-row
WRITE(*,*) (C(i,j), j=1, N)
END DO
27
140. Arrays as Arguments: 1/4Arrays as Arguments: 1/4
Arrays may also be used as arguments passingy y g p g
to functions and subroutines.
Formal argument arrays may be declared asg y y
usual; however, Fortran 90 recommends the use
of assumed-shape arrays.
An assumed-shape array has its lower bound in
each extent specified; but, the upper bound is
not used.
formal arguments
REAL, DIMENSION(-3:,1:), INTENT(IN) :: x, y
INTEGER, DIMENSION(:), INTENT(OUT) :: a, b
28assumed-shape
141. Arrays as Arguments: 2/4Arrays as Arguments: 2/4
The extent in each dimension is an expressionThe extent in each dimension is an expression
that uses constants or other non-array formal
arguments with INTENT(IN) :g ( )
SUBROUTINE Test(x,y,z,w,l,m,n)
I PLICIT NONE
assumed-shape
IMPLICIT NONE
INTEGER, INTENT(IN) :: l, m, n
REAL, DIMENSION(10:),INTENT(IN) :: x
INTEGER, DIMENSION(-1:,m:), INTENT(OUT) :: y
LOGICAL, DIMENSION(m,n:), INTENT(OUT) :: z
REAL, DIMENSION(-5:5), INTENT(IN) :: w
…… other statements ……
END SUBROUTINE Test DIMENSION(1:m,n:)
29not assumed-shape
142. Arrays as Arguments: 3/4Arrays as Arguments: 3/4
Fortran 90 automatically passes an array and itsFortran 90 automatically passes an array and its
shape to a formal argument.
A subprogram receives the shape and uses theA subprogram receives the shape and uses the
lower bound of each extent to recover the upper
boundbound.
INTEGER,DIMENSION(2:10)::Score
……
CALL Funny(Score) shape is (9)
SUBROUTINE Funny(x)
IMPLICIT NONE
INTEGER,DIMENSION(-1:),INTENT(IN) :: x
30
…… other statements ……
END SUBROUTINE Funny (-1:7)
143. Arrays as Arguments: 4/4Arrays as Arguments: 4/4
One more exampleOne more example
REAL, DIMENSION(1:3,1:4) :: x, ( , )
INTEGER :: p = 3, q = 2
CALL Fast(x,p,q) shape is (3,4)
SUBROUTINE Fast(a,m,n)( , , )
IMPLICIT NONE
INTEGER,INTENT(IN) :: m,n
REAL DIMENSION(-m: n:) INTENT(IN)::aREAL,DIMENSION( m:,n:),INTENT(IN)::a
…… other statements ……
END SUBROUTINE Fast
31
(-m:,n:) becomes (-3:-1,2:5)
144. The SIZE() Intrinsic Function: 1/2The SIZE() Intrinsic Function: 1/2
How do I know the shape of an array?p y
Use the SIZE() intrinsic function.
SIZE() requires two arguments, an arraySIZE() requires two arguments, an array
name and an INTEGER, and returns the size of
the array in the given “dimension.”y g
INTEGER,DIMENSION(-3:5,0:100):: a
shape is (9,101)
WRITE(*,*) SIZE(a,1), SIZE(a,2)
CALL ArraySize(a)
(1:9,5:105)
SUBROUTINE ArraySize(x)
INTEGER,DIMENSION(1:,5:),… :: x
Both WRITE prints
9 and 101
32
WRITE(*,*) SIZE(x,1), SIZE(x,2)
9 and 101
145. The SIZE() Intrinsic Function : 2/2The SIZE() Intrinsic Function : 2/2
INTEGER,DIMENSION(-1:1,3:6):: Empty
CALL Fill(Empty)CALL Fill(Empty)
DO i = -1,1
WRITE(*,*) (Empty(i,j),j=3,6)
END DO
SUBROUTINE Fill(y)
I PLICIT NONE
END DO shape is (3,4)
IMPLICIT NONE
INTEGER,DIMENSION(1:,1:),INTENT(OUT)::y
INTEGER :: U1, U2, i, j
output U1 = SIZE(y,1)
U2 = SIZE(y,2)
DO i = 1, U1
2 3 4 5
3 4 5 6
4 5 6 7
output
(1:3 1:4)
DO j = 1, U2
y(i,j) = i + j
END DO
4 5 6 7 (1:3,1:4)
33
END DO
END DO
END SUBROUTINE Fill
146. Local Arrays: 1/2Local Arrays: 1/2
Fortran 90 permits to declare local arrays usingFortran 90 permits to declare local arrays using
INTEGER formal arguments with the
INTENT(IN) attribute.( )
SUBROUTINE Compute(X m n)INTEGER, & SUBROUTINE Compute(X, m, n)
IMPLICIT NONE
INTEGER,INTENT(IN) :: m, n
INTEGER DIMENSION(1 1 ) &
INTEGER, &
DIMENSION(100,100) &
::a, z
W(1:3) Y(1:3,1:15)
INTEGER,DIMENSION(1:,1:), &
INTENT(IN) :: X
INTEGER,DIMENSION(1:m) :: W
local arrays
CALL Compute(a,3,5)
CALL Compute(z,6,8)
REAL,DIMENSION(1:m,1:m*n)::Y
…… other statements ……
END SUBROUTINE ComputeW(1:6) Y(1:6,1:48)
34
W(1:6) Y(1:6,1:48)
147. Local Arrays: 2/2Local Arrays: 2/2
Just like you learned in C/C++ and Java,
memory of local variables and local arrays in
Fortran 90 is allocated before entering a
subprogram and deallocated on return.
Fortran 90 uses the formal arguments tog
compute the extents of local arrays.
Therefore, different calls with different valuesTherefore, different calls with different values
of actual arguments produce different shape
and extent for the same local array. However,and extent for the same local array. However,
the rank of a local array will not change.
35
148. The ALLOCATBLE AttributeThe ALLOCATBLE Attribute
In many situations, one does not know exactlyIn many situations, one does not know exactly
the shape or extents of an array. As a result,
one can only declare a “large enough” array.one can only declare a large enough array.
The ALLOCATABLE attribute comes to rescue.
The ALLOCATABLE attribute indicates that atThe ALLOCATABLE attribute indicates that at
the declaration time one only knows the rank of
b t t it t tan array but not its extent.
Therefore, each extent has only a colon :.
INTEGER,ALLOCATABLE,DIMENSION(:) :: a
REAL,ALLOCATABLE,DIMENSION(:,:) :: b
36
LOGICAL,ALLOCATABLE,DIMENSION(:,:,:) :: c
149. The ALLOCATE Statement: 1/3The ALLOCATE Statement: 1/3
The ALLOCATE statement has the followingg
syntax:
ALLOCATE(array-1 array-n STAT=v)ALLOCATE(array-1,…,array-n,STAT=v)
Here, array-1, …, array-n are array names
with complete extents as in the DIMENSIONwith complete extents as in the DIMENSION
attribute, and v is an INTEGER variable.
Af i f if 0After the execution of ALLOCATE, if v 0, then
at least one arrays did not get memory.
REAL,ALLOCATABLE,DIMENSION(:) :: a
LOGICAL,ALLOCATABLE,DIMENSION(:,:) :: x
37
INTEGER :: status
ALLOCATE(a(3:5), x(-10:10,1:8), STAT=status)
150. The ALLOCATE Statement: 2/3The ALLOCATE Statement: 2/3
ALLOCATE only allocates arrays with they y
ALLOCATABLE attribute.
The extents in ALLOCATE can use INTEGERThe extents in ALLOCATE can use INTEGER
expressions. Make sure all involved variables
have been initialized properlyhave been initialized properly.
INTEGER,ALLOCATABLE,DIMENSION(:,:) :: x
INTEGER,ALLOCATABLE,DIMENSION(:) :: aINTEGER,ALLOCATABLE,DIMENSION(:) :: a
INTEGER :: m, n, p
READ(*,*) m, n
ALLOCATE(x(1:m m+n:m*n) a(-(m*n):m*n) STAT=p)ALLOCATE(x(1:m,m+n:m*n),a(-(m*n):m*n),STAT=p)
IF (p /= 0) THEN
…… report error here ……
38
If m = 3 and n = 5, then we have
x(1:3,8:15) and a(-15:15)
151. The ALLOCATE Statement: 3/3The ALLOCATE Statement: 3/3
ALLOCATE can be used in subprograms.p g
Formal arrays are not ALLOCATABLE.
I l ll t d i bIn general, an array allocated in a subprogram
is a local entity, and is automatically
d ll t d h th b tdeallocated when the subprogram returns.
Watch for the following odd use:
PROGRAM Try_not_to_do_this
IMPLICIT NONE
REAL,ALLOCATABLE,DIMENSION(:) :: x
CONTAINS
SUBROUTINE Hey(…)
ALLOCATE(x(1:10))
39
ALLOCATE(x(1:10))
END SUBROUTINE Hey
END PROGRAM Try_not_to_do_this
152. The DEALLOCATE StatementThe DEALLOCATE Statement
Allocated arrays may be deallocated by theAllocated arrays may be deallocated by the
DEALLOCATE() statement as shown below:
DEALLOCATE(array-1 array-n STAT=v)DEALLOCATE(array-1,…,array-n,STAT=v)
Here, array-1, …, array-n are the names of
allocated arrays and is an INTEGER variableallocated arrays, and v is an INTEGER variable.
If deallocation fails (e.g., some arrays were not
) i iallocated), the value in v is non-zero.
After deallocation of an array, it is not available
and any access will cause a program error.
DEALLOCATE(a b c STAT=status)
40
DEALLOCATE(a, b, c, STAT=status)
153. The ALLOCATED Intrinsic FunctionThe ALLOCATED Intrinsic Function
The ALLOCATED(a) function returns .TRUE.( )
if ALLOCATABLE array a has been allocated.
Otherwise, it returns .FALSE.,
INTEGER,ALLOCATABLE,DIMENSION(:) :: Mat
INTEGER :: status
ALLOCATE(Mat(1:100),STAT=status)
…… ALLOCATED(Mat) returns .TRUE. …..
…… other statements ……
DEALLOCATE(Mat,STAT=status)DEALLOCATE(Mat,STAT status)
…… ALLOCATED(Mat) returns .FALSE. ……
41
154. Fortran 90 SubprogramsFortran 90 Subprograms
If Fortran is the lingua franca, then certainly it must
be true that BASIC is the lingua playpen
1
Thomas E. Kurtz
Co-Designer of the BASIC language
Fall 2010
155. Functions and SubroutinesFunctions and Subroutines
Fortran 90 has two types of subprograms,Fortran 90 has two types of subprograms,
functions and subroutines.
A Fortran 90 function is a function like those inA Fortran 90 function is a function like those in
C/C++. Thus, a function returns a computed
result via the function nameresult via the function name.
If a function does not have to return a function
l b tivalue, use subroutine.
2
156. Function Syntax: 1/3Function Syntax: 1/3
A Fortran function, or function subprogram,, p g ,
has the following syntax:
type FUNCTION function-name (arg1, arg2, ..., argn)
IMPLICIT NONE
[specification part]
[execution part]p
[subprogram part]
END FUNCTION function-name
type is a Fortran 90 type (e g INTEGERtype is a Fortran 90 type (e.g., INTEGER,
REAL, LOGICAL, etc) with or without KIND.
function name is a Fortran 90 identifierfunction-name is a Fortran 90 identifier
arg1, …, argn are formal arguments.
3
157. Function Syntax: 2/3Function Syntax: 2/3
A function is a self-contained unit that receives
some “input” from the outside world via its
formal arguments, does some computations, and
returns the result with the name of the function.
Somewhere in a function there has to be one or
more assignment statements like this:
function-name = expression
where the result of expression is saved to the
name of the function.
Note that function-name cannot appear in
the right-hand side of any expression.
4
158. Function Syntax: 3/3Function Syntax: 3/3
In a type specification, formal argumentsyp p , g
should have a new attribute INTENT(IN).
The meaning of INTENT(IN) is that theg
function only takes the value from a formal
argument and does not change its content.
Any statements that can be used in PROGRAM
can also be used in a FUNCTION.
5
159. Function ExampleFunction Example
Note that functions can have no formal argument.Note that functions can have no formal argument.
But, () is still required.
INTEGER FUNCTION Factorial(n)
IMPLICIT NONE
REAL FUNCTION GetNumber()
IMPLICIT NONE
Factorial computation Read and return a positive real number
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
INTEGER :: i, Ans
IMPLICIT NONE
REAL :: Input_Value
DO
WRITE(*,*) 'A positive number: '
Ans = 1
DO i = 1, n
Ans = Ans * i
END DO
( , ) p
READ(*,*) Input_Value
IF (Input_Value > 0.0) EXIT
WRITE(*,*) 'ERROR. try again.'
END DOEND DO
Factorial = Ans
END FUNCTION Factorial
END DO
GetNumber = Input_Value
END FUNCTION GetNumber
6
160. Common Problems: 1/2Common Problems: 1/2
forget function type forget INTENT(IN) not an error
FUNCTION DoSomething(a, b)
IMPLICIT NONE
INTEGER, INTENT(IN) :: a, b
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
INTEGER :: a, b
g yp g
DoSomthing = SQRT(a*a + b*b)
END FUNCTION DoSomething
DoSomthing = SQRT(a*a + b*b)
END FUNCTION DoSomething
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
change INTENT(IN) argument forget to return a value
INTEGER, INTENT(IN) :: a, b
IF (a > b) THEN
a = a - b
ELSE
INTEGER, INTENT(IN) :: a, b
INTEGER :: c
c = SQRT(a*a + b*b)
END FUNCTION DoSomethingELSE
a = a + b
END IF
DoSomthing = SQRT(a*a+b*b)
END FUNCTION DoSomething
7
END FUNCTION DoSomething
161. Common Problems: 2/2Common Problems: 2/2
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
incorrect use of function name only the most recent value is returned
IMPLICIT NONE
INTEGER, INTENT(IN) :: a, b
DoSomething = a*a + b*b
DoSomething = SQRT(DoSomething)
IMPLICIT NONE
INTEGER, INTENT(IN) :: a, b
DoSomething = a*a + b*b
DoSomething = SQRT(a*a - b*b)
END FUNCTION DoSomething END FUNCTION DoSomething
8
162. Using FunctionsUsing Functions
The use of a user-defined function is similar toThe use of a user defined function is similar to
the use of a Fortran 90 intrinsic function.
The following uses function Factorial(n) toThe following uses function Factorial(n) to
compute the combinatorial coefficient C(m,n) ,
where m and n are actual arguments:where m and n are actual arguments:
Cmn = Factorial(m)/(Factorial(n)*Factorial(m-n))
Note that the combinatorial coefficient is
defined as follows, although it is not the most
efficient way:
C m n
m
( )
!
9
C m n
n m n
( , )
! ( )!
163. Argument Association : 1/5Argument Association : 1/5
Argument association is a way of passing valuesArgument association is a way of passing values
from actual arguments to formal arguments.
If an actual argument is an expression it isIf an actual argument is an expression, it is
evaluated and stored in a temporary location
from which the value is passed to thefrom which the value is passed to the
corresponding formal argument.
If t l t i i bl it l iIf an actual argument is a variable, its value is
passed to the corresponding formal argument.
C d h i i blConstant and (A), where A is variable, are
considered expressions.
10
164. Argument Association : 2/5Argument Association : 2/5
Actual arguments are variables:Actual arguments are variables:
a b cWRITE(*,*) Sum(a,b,c)
x y z
INTEGER FUNCTION Sum(x,y,z)
IMPLICIT NONE
INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..
END FUNCTION Sum
11
165. Argument Association : 3/5Argument Association : 3/5
Expressions as actual arguments. Dashed lineExpressions as actual arguments. Dashed line
boxes are temporary locations.
a+b b+c cWRITE(*,*) Sum(a+b,b+c,c)
x y z
INTEGER FUNCTION Sum(x,y,z)
IMPLICIT NONE
INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..
END FUNCTION Sum
12
166. Argument Association : 4/5Argument Association : 4/5
Constants as actual arguments. Dashed lineConstants as actual arguments. Dashed line
boxes are temporary locations.
1 2 3WRITE(*,*) Sum(1, 2, 3)
x y z
INTEGER FUNCTION Sum(x,y,z)
IMPLICIT NONE
INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..
END FUNCTION Sum
13
167. Argument Association : 5/5Argument Association : 5/5
A variable in () is considered as an expression.() p
Dashed line boxes are temporary locations.
(a) (b) (c)WRITE(*,*) Sum((a), (b), (c))
x y z
INTEGER FUNCTION Sum(x,y,z)
IMPLICIT NONE
INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..
END FUNCTION Sum
14
168. Where Do Functions Go: 1/2Where Do Functions Go: 1/2
Fortran 90 functions can be internal or external.Fortran 90 functions can be internal or external.
Internal functions are inside of a PROGRAM, the
main program:main program:
PROGRAM program-name
IMPLICIT NONEC NON
[specification part]
[execution part]
CONTAINSCONTAINS
[functions]
END PROGRAM program-name
Although a function can contain other functions,
i t l f ti t h i t l f ti
15
internal functions cannot have internal functions.
169. Where Do Functions Go: 2/2Where Do Functions Go: 2/2
The right shows PROGRAM TwoFunctionsg
two internal
functions,
PROGRAM TwoFunctions
IMPLICIT NONE
REAL :: a, b, A_Mean, G_Mean
READ(*,*) a, b
ArithMean()
and GeoMean().
A_Mean = ArithMean(a, b)
G_Mean = GeoMean(a,b)
WRITE(*,*) a, b, A_Mean, G_Mean
CONTAINS
They take two
REAL actual
t d
CONTAINS
REAL FUNCTION ArithMean(a, b)
IMPLICIT NONE
REAL, INTENT(IN) :: a, b
arguments and
compute and
return a REAL
ArithMean = (a+b)/2.0
END FUNCTION ArithMean
REAL FUNCTION GeoMean(a, b)
IMPLICIT NONEreturn a REAL
function value.
IMPLICIT NONE
REAL, INTENT(IN) :: a, b
GeoMean = SQRT(a*b)
END FUNCTION GeoMean
16
END PROGRAM TwoFunctions
170. Scope Rules: 1/5Scope Rules: 1/5
Scope rules tell us if an entity (i.e., variable,Scope rules tell us if an entity (i.e., variable,
parameter and function) is visible or accessible
at certain places.at certain places.
Places where an entity can be accessed or visible
is referred as the scope of that entityis referred as the scope of that entity.
17
171. Scope Rules: 2/5Scope Rules: 2/5
Scope Rule #1: The scope of an entity is the
program or function in which it is declared.
PROGRAM Scope_1 Scope of PI, m and n
IMPLICIT NONE
REAL, PARAMETER :: PI = 3.1415926
INTEGER :: m, n
...................
CONTAINS
INTEGER FUNCTION Funct1(k)
IMPLICIT NONE
Scope of k, f and g
local to Funct1()
INTEGER, INTENT(IN) :: k
REAL :: f, g
..........
END FUNCTION Funct1END FUNCTION Funct1
REAL FUNCTION Funct2(u, v)
IMPLICIT NONE
REAL, INTENT(IN) :: u, v
Scope of u and v
local to Funct2()
18
..........
END FUNCTION Funct2
END PROGRAM Scope_1
172. Scope Rules: 3/5Scope Rules: 3/5
Scope Rule #2 :A global entity is visible to allp
contained functions.
PROGRAM Scope_2
IMPLICIT NONE
INTEGER :: a = 1, b = 2, c = 3
WRITE(*,*) Add(a)
a, b and c are global
The first Add(a) returns 4
Th d dd tc = 4
WRITE(*,*) Add(a)
WRITE(*,*) Mul(b,c)
CONTAINS
The second Add(a) returns 5
Mul(b,c) returns 8
INTEGER FUNCTION Add(q)
IMPLICIT NONE
INTEGER, INTENT(IN) :: q
Add = q + c
Thus, the two Add(a)’s produce different
results, even though the formal arguments
are the same! This is usually referred toEND FUNCTION Add
INTEGER FUNCTION Mul(x, y)
IMPLICIT NONE
INTEGER, INTENT(IN) :: x, y
are the same! This is usually referred to
as side effect.
Avoid using global entities!
19
Mul = x * y
END FUNCTION Mul
END PROGRAM Scope_2
Avoid using global entities!
173. Scope Rules: 4/5Scope Rules: 4/5
Scope Rule #2 :A global entity is visible to allp
contained functions.
PROGRAM Global
IMPLICIT NONE
INTEGER :: a = 10, b = 20
The first Add(a,b) returns 30
It also changes b to 30
Th 2 d WRITE(* *) h 30
INTEGER :: a 10, b 20
WRITE(*,*) Add(a,b)
WRITE(*,*) b
WRITE(*,*) Add(a,b)
The 2nd WRITE(*,*) shows 30
The 2nd Add(a,b) returns 40
This is a bad side effect
CONTAINS
INTEGER FUNCTION Add(x,y)
IMPLICIT NONE
Avoid using global entities!
INTEGER, INTENT(IN)::x, y
b = x+y
Add = b
20
END FUNCTION Add
END PROGRAM Global
174. Scope Rules: 5/5Scope Rules: 5/5
Scope Rule #3 :An entity declared in the scope of
th tit i l diff t ifanother entity is always a different one even if
their names are identical.
PROGRAM Scope_3
IMPLICIT NONE
INTEGER :: i, Max = 5
DO i 1 Max
Although PROGRAM and FUNCTION
Sum() both have INTEGER variable i,
They are TWO different entities.
DO i = 1, Max
Write(*,*) Sum(i)
END DO
CONTAINS
y
Hence, any changes to i in Sum() will
not affect the i in PROGRAM.
INTEGER FUNCTION Sum(n)
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
INTEGER :: i sINTEGER :: i, s
s = 0
…… other computation ……
Sum = s
21
END FUNCTION Sum
END PROGRAM Scope_3
175. Example: 1/4Example: 1/4
If a triangle has side lengths a, b and c, the HeronIf a triangle has side lengths a, b and c, the Heron
formula computes the triangle area as follows,
where s = (a+b+c)/2:where s (a b c)/2:
Area s s a s b s c( ) ( ) ( )
To form a triangle, a, b and c must fulfill the
following two conditions:
a > 0, b > 0 and c > 0
a+b > c, a+c > b and b+c > a
22
176. Example: 2/4Example: 2/4
LOGICAL Function TriangleTest() makesg ()
sure all sides are positive, and the sum of any
two is larger than the third.two is larger than the third.
LOGICAL FUNCTION TriangleTest(a, b, c)LOGICAL FUNCTION TriangleTest(a, b, c)
IMPLICIT NONE
REAL, INTENT(IN) :: a, b, c
LOGICAL :: test1, test2OG C :: test , test
test1 = (a > 0.0) .AND. (b > 0.0) .AND. (c > 0.0)
test2 = (a + b > c) .AND. (a + c > b) .AND. (b + c > a)
TriangleTest = test1 .AND. test2 ! both must be .TRUE.
END FUNCTION TriangleTest
23
177. Example: 3/4Example: 3/4
This function implements the Heron formula.This function implements the Heron formula.
Note that a, b and c must form a triangle.
REAL FUNCTION Area(a, b, c)
IMPLICIT NONE
REAL, INTENT(IN) :: a, b, c
REAL :: s
s = (a + b + c) / 2.0
A SQRT( *( )*( b)*( ))Area = SQRT(s*(s-a)*(s-b)*(s-c))
END FUNCTION Area
24
178. Example: 4/4Example: 4/4
Here is the main program!
PROGRAM HeronFormula
IMPLICIT NONE
REAL :: a, b, c, TriangleArea
DODO
WRITE(*,*) 'Three sides of a triangle please --> '
READ(*,*) a, b, c
WRITE(*,*) 'Input sides are ', a, b, c
IF (TriangleTest(a, b, c)) EXIT ! exit if they form a triangle
WRITE(*,*) 'Your input CANNOT form a triangle. Try again'
END DO
TriangleArea = Area(a b c)TriangleArea = Area(a, b, c)
WRITE(*,*) 'Triangle area is ', TriangleArea
CONTAINS
LOGICAL FUNCTION TriangleTest(a, b, c)
……
END FUNCTION TriangleTest
REAL FUNCTION Area(a, b, c)
25
……
END FUNCTION Area
END PROGRAM HeronFormula
179. Subroutines: 1/2Subroutines: 1/2
A Fortran 90 function takes values from itsA Fortran 90 function takes values from its
formal arguments, and returns a single value
with the function name.with the function name.
A Fortran 90 subroutine takes values from its
formal arguments and returns some computedformal arguments, and returns some computed
results with its formal arguments.
A F t 90 b ti d t tA Fortran 90 subroutine does not return any
value with its name.
26
180. Subroutines: 2/2Subroutines: 2/2
The following is Fortran 90 subroutine syntax:The following is Fortran 90 subroutine syntax:
SUBROUTINE subroutine-name(arg1,arg2,...,argn)
IMPLICIT NONE
[specification part]
[ ti t][execution part]
[subprogram part]
END SUBROUTINE subroutine-nameEND SUBROUTINE subroutine name
If a subroutine does not require any formal
arguments “arg1 arg2 argn” can be removed;arguments, arg1,arg2,...,argn can be removed;
however, () must be there.
S b ti i il t f ti
27
Subroutines are similar to functions.
181. The INTENT() Attribute: 1/2The INTENT() Attribute: 1/2
Since subroutines use formal arguments toSince subroutines use formal arguments to
receive values and to pass results back, in
addition to INTENT(IN), there are( ),
INTENT(OUT) and INTENT(INOUT).
INTENT(OUT) means a formal argument doesINTENT(OUT) means a formal argument does
not receive a value; but, it will return a value to
its corresponding actual argumentits corresponding actual argument.
INTENT(INOUT) means a formal argument
i l f d t l t itreceives a value from and returns a value to its
corresponding actual argument.
28
182. The INTENT() Attribute: 2/2The INTENT() Attribute: 2/2
Two simple examples:Two simple examples:
SUBROUTINE Means(a, b, c, Am, Gm, Hm)
IMPLICIT NONE
Am, Gm and Hm are used to return the results
REAL, INTENT(IN) :: a, b, c
REAL, INTENT(OUT) :: Am, Gm, Hm
Am = (a+b+c)/3.0
Gm = (a*b*c)**(1 0/3 0)Gm = (a*b*c)**(1.0/3.0)
Hm = 3.0/(1.0/a + 1.0/b + 1.0/c)
END SUBROUTINE Means
values of a and b are swapped
SUBROUTINE Swap(a, b)
IMPLICIT NONE
INTEGER, INTENT(INOUT) :: a, b
INTEGER :: cINTEGER :: c
c = a
a = b
b = c
29
END SUBROUTINE Swap
183. The CALL Statement: 1/2The CALL Statement: 1/2
Unlike C/C++ and Java, to use a Fortran 90Unlike C/C and Java, to use a Fortran 90
subroutine, the CALL statement is needed.
The CALL statement may have one of the threeThe CALL statement may have one of the three
forms:
CALL sub name(arg1 arg2 argn)CALL sub-name(arg1,arg2,…,argn)
CALL sub-name( )
CALL sub-name
The last two forms are equivalent and are forThe last two forms are equivalent and are for
calling a subroutine without formal arguments.
30
184. The CALL Statement: 2/2The CALL Statement: 2/2
PROGRAM Test PROGRAM SecondDegreePROGRAM Test
IMPLICIT NONE
REAL :: a, b
READ(*,*) a, b
PROGRAM SecondDegree
IMPLICIT NONE
REAL :: a, b, c, r1, r2
LOGICAL :: OK
CALL Swap(a,b)
WRITE(*,*) a, b
CONTAINS
SUBROUTINE Swap(x y)
READ(*,*) a, b, c
CALL Solver(a,b,c,r1,r2,OK)
IF (.NOT. OK) THEN
WRITE(* *) “No root”SUBROUTINE Swap(x,y)
IMPLICIT NONE
REAL, INTENT(INOUT) :: x,y
REAL :: z
WRITE(*,*) “No root”
ELSE
WRITE(*,*) a, b, c, r1, r2
END IF
z = x
x = y
y = z
END SUBROUTINE Swap
CONTAINS
SUBROUTINE Solver(a,b,c,x,y,L)
IMPLICIT NONE
REAL INTENT(IN) :: a b cEND SUBROUTINE Swap
END PROGRAM Test
REAL, INTENT(IN) :: a,b,c
REAL, INTENT(OUT) :: x, y
LOGICAL, INTENT(OUT) :: L
………
31
END SUBROUTINE Solver
END PROGRAM SecondDegree