Fortran 2003 programming in GEF4510. Fall 2012

Size: px
Start display at page:

Download "Fortran 2003 programming in GEF4510. Fall 2012"

Transcription

1 Fortran 2003 programming in GEF4510 Fall

2 Course content 1. Fortran historical background, what, why and how 2. A short program converting from Farenheit to centigrades and vice versa 3. The variable types, arrays, loops and allocating space 4. File I/O 5. Multidimensional arrays 6. Functions and Subroutines 7. Modules 8. Optimization 2

3 Historical background of Fortran Introduction The purpose of this book is to give a good insight in the Fortran 2003 programming language.by going through a number of examples showing how computational problems and the reading and writing data to files can be solved. Why use Fortran? In the last 15 to 20 years Fortran has been looked upon as an old-fashioned unstructured programming language by researchers and students in the field of Informatics. Fortran has lacked most of the features found in modern programming languages like C++, Java etc. Especially the lack of object orientation has been the main drawback of Fortran. This is no longer true. Fortran 2003 has all the modern features including OOP (Object Oriented Programming). The reason we still use Fortran as a programming language is because of the exeecution speed of the program. In the field of natural sciences, computer simulations of natural phenomena are becoming increasingly more important. Laboratory experiments are getting too complex and too costly to be performed. The only alternative is to use a computer simulation to try to solve the problem under study. Thus the need to have your code execute faster becomes more and more important when the simulations grows larger and larger. In number-crunching Fortran still has an edge in speed over C and C++. Tests has shown that an optimized Fortran program in some cases runs up to 30 percent faster than the equivalent C or C++ program. For programs with a runtime of weeks even a small increase in speed will reduce the overall time it takes to solve a problem. Historical background Seen in a historical perspective Fortran is an old programming language John Backus and his team at IBM begin developing the scientific programming language Fortran. It was first introduced in 1957 for a limited set of computer architectures. In a short time the language spread to other architectures and has since been the most widely used programming language for solving numerical problems. The name Fortran is derived from Formula Translation and it is still the language of choice for fast numerical computations. A couple of years later in 1959 a new version, Fortran II was introduced. This version was more advanced and among the new features was the ability to use complex numbers and splitting a 3

4 program into various subroutines. In the following years Fortran was further developed to become a programming language that was fairly easy to understand and well adapted to solve numerical problems. In 1962 a new version called Fortran IV emerged. This version had among it s features the ability to read and write direct access files and also had a new data-type called LOGICAL. This was a Boolean data-type with two states true or false. At the end of the seventies Fortran 77 was introduced. This version contained better loop and test structures. In 1992 Fortran 90 was formally introduced as an ANSI/ISO standard. This version of Fortran has made the language into a modern programming language. Fortran 95 is a small extension of Fortran 90. These latest versions of Fortran has many of the features we expect from a modern programming languages. Now we have the Fortran 2003 which incorporates object-oriented programming with type extension and inheritance, polymorphism, dynamic type allocation and type-bound procedures. 4

5 A Farenheit to Centigrade converter Let us ask a question before we continue with our problem solving. Why do I have to learn to program? In the field of Meteorology and Oceanography you will probably be using models like WRF, CAM and ROMS or other models like them. Depending on your Master-project, you will some times have to make changes or additions to an already existing model written in Fortran. Without any knowledge of programming and the Fortran language you will use too much time trying to find out how you are going to make the changes to the model and loosing valuable time. If that is not a good reason to learn how to program I would like to hear why. Our first step in learning how to program using Fortran 2003 language will be to write a small program converting a temperature from Farenheit to Centigrade and display the two temperatures on the screen. The formula for the conversion is: C = (F 32) 5 (1) 9 So how do we go about solving this problem using Fortran? First we have to take a look at the structure of a Fortran program. A Fortran program always starts with the sentence PROGRAM program_name and ends with the sentence END PROGRAM program_name. Between these two lines the actual code performing a task is written. To proceed with the solution we need a couple of variables to hold the temperature in Farenheit and Centigrades. We use the F and C for Farenheit and Centigrades. The syntax for declaring a floating point variable in Fortran is like this:!// The Farenheit variable REAL :: F!// The Centigrade variable REAL :: C Note that we use the REAL keyword to declare a floating point variable. In other languages the keyword float is used. The Fortran language is case insensitive. That means that a variable or function mane is the same if it is written with uppercase or lowercase letters. In most other languages it is the opposite where a variable whose name is written in uppercase is different from a variable in lowercase. From the Fortran 90 version we separate the variable type from the variable name with a double colon. Also from this version and on we use an exclamation sign to signal the compiler that the rest of the line is a comment. In order to make the code more readable an additional double slash si also used. As we shall see 5

6 later in this course a program that is easy to read is also easy to understand and also makes it easier to find and correct errors. One ting we have to be aware of is that Fortran uses what is called implicit declarations of variables. This is from the earliest versions of Fortran and can cause unwanted results due to misspelling of a variable name. To prevent this all programs written in Fortran should have as the first line of code after the PROGRAM program_name the which tells the compiler to check that all variables has benn declared thus avoid problems. The net step is to initialize the Farenheit variable and perform the conversion according to the formula. The whole program can look like this. PROGRAM farenheit_to_centigrades!// Declare the Farenheit variable F as a floating!// point number REAL :: F!// Declare the Centigrade variable C as a floating!// point number REAL :: C!// Assigne a value to F as a constant number!// note the decimal point after the constant number F = 75.!// Perform the calculations C = (F - 32.)*5./9.!// Write the result to the screen PRINT *, C END PROGRAM farenheit_to_centigrades We need to comment on some of the code here. In order to tell the compiler that the constant value like 75. we have to use a decimal point as part of the number. If we omit this the compiler will assume that is an integer and in some cases the calculations will be wrong. Also note the use of parenthesis to perform the calculations in the proper sequence. The sentence PRINT *, C writes the value of the Centigrades to the display. Writing the source code is one thing, but in order to run the program we have to compile it from source code to a binary executable program file. There are several commercial Fortran compilers, but we are going to use the GNU Fortran compiler called gfortran to compile our program. So how do we do it? Assume we have called our file with the source code farenheit_to_centigrades.f90. To compile it we use the command gfortran -o farenheit_to_centigrades farenheit_to_centigrades.f90 6

7 where the o is a signal to the compiler that the next argument is the name of the program and the last argument is the name of the file with the source code. This command tells the compiler to create a binary program file called farenheit_to_centigrades which can be run by typing the program name in a terminal window. All Fortran programs are compiled this way. We shall take a look at how we compile a program consisting of several files with source code later. 7

8 A more user friendly temperature converter The temperature conversion program we made in the previous section is not very user friendly. Th convert a new temperature we have to change the source code, recompile the program and then run it again. Back in 1957 this was not uncommon, but we do not have to use stoen age tools here. We will therefore upgrade our program with a user interface asking for a temperature in either Farenheit or Centigrade and print the result to the screen as before. The first thing we have to do is to write the "prompt" to the screen. To do this we declare a text variable using the keyword CHARACTER with a length option like this CHARACTER(LEN=80) which means that we have allocated a space for a text up to 80 characters long. Also we need a single character variable to hold the answer of the temperature (F or C) for conversion. The complete program is here:!//////////////////////////////////////////////////////////!//!// f2c.f90!//!// Program to convert from Farenheit to!// Centigrades or vice versa!////////////////////////////////////////////////////////// PROGRAM f2c!// Temperature in Farenheit REAL :: F!// Temperature in Centigrades REAL :: C!// Character string to hold the prompts for communicating!// with the user CHARACTER(LEN=80) :: prompt1, prompt2!// A single character to hold the answer!// which is is either F or C CHARACTER :: answer!// Assign a value to the prompt1 prompt1 = Enter F for Farenheit or C for centigrade!// Print the contents to the screen without trailing blank!// characters PRINT *, TRIM(prompt1) 8

9 !// Read the input from the keyboard READ(*,*) answer!// Assign a value to the prompt2 prompt2 = Enter a temperature!// Print the contents to the screen without trailing blank!// characters PRINT *, TRIM(prompt2)!// Is the temperature given in Farenheit IF(answer.EQ. F ) THEN!// Yes, read the input from the keyboard into!// the F variable READ(*,*) F!// Convert from Farenheit to Centigrade C = (F - 32) * (5. / 9.)!// Print the result to the screen PRINT *, C ELSE!// No, read the input from the keyboard into!// the C variable READ(*,*) C!// convert from Centigrade to Farenheit F = (C * 9. / 5.) + 32!// Print the result to the screen PRINT *, F END PROGRAM f2c Note that this program contains a descriptive comment as the first part of the source code including the name of the file containing the source code. This is a very good way of making the code more readable and easier to understand and should always be used even for very small programs. The use of the keyword TRIM tells the compiler to print out the text witout printing the trailing space characters. We use the READ to get the answer entered by the user and put it in the proper variable. The use of the construct READ(*,*) means we read the input from the keyboard with default formatting into the recieving variable. 9

10 Variable types, arrays, loops and memory allocation Until now we have used single variables with the exception of a character string. Most often we need to use large amount of data stored in one dimensional vectors or matrices with two or more dimensions. We shall start with a program calculating the Fibonacchi sequence and store the numbers in a vector of integers. Also we shall have a user interface asking for the length of the sequence. The formula for calculating the Fibonacchi sequence is this: F n = F n 1 + F n 2 (2) We will of course start with the program skeleton as always with the code PROGRAM fibonacchi END PROGRAM fibonacchi The easy part done it is now the work begins. We will need to break the problem down into several smaller parts like I suggest here: Decide which variables we need to store the numbers, the indexes and if we need it some help variables. Decide how we are going to access the variables and how we are going to perform the calculations on each element of the sequence First we need an array of integers to hold the numbers. The length of this array (or vector) is not known in advance so we will have to use an allocatable array where we allocate the needed space at runtime. In addition we need an index variable and a status variable where the first one is for accessing the various elements of the array and the status variable to check the result of the allocation. Since we have to get the length ogf the array at runtime we also need a user interface like we had in the temperature conversion program. The code is shown here:!////////////////////////////////////////////////////////////////!//!// fibonacchi.f90!//!// Program to display the fbonacchi sequence from!// 1 to n!//!//////////////////////////////////////////////////////////////// 10

11 PROGRAM fibonacchi!// Variable declarations!// Declaring integer variables!// Counter variable :: i!// Length of fibonacchi array :: n!// The status variable :: res!// Array to hold the fibonacchi sequence with!// unknown length at compile time, ALLOCATABLE, DIMENSION(:) :: sequence!// The prompt to ask for length of the fibonacchi!// sequence CHARACTER(LEN=80) :: prompt!// Assign value to the prompt prompt = Enter the length of the sequence:!// Get the number of non blank characters in prompt i = LEN(TRIM(prompt))!// Display the prompt asking for the length suppressing!// the line feed WRITE(*,FMT= (A),ADVANCE= NO ) prompt(1:i+1)!// Read the keyboard input READ(*,*) n!// Allocate space for the sequence ALLOCATE(sequence(n), STAT=res)!// Test the value of the res variable for errors!// We have an error. Print a message and stop the program PRINT *, Error in allocating space, status:, res STOP!// Initialize the two first elements in the sequence sequence(1) = 1 sequence(2) = 1!// Loop and calculate the fibonacchi numbers DO i = 3, n sequence(i) = sequence(i-1) + sequence(i-2) 11

12 !// Print the sequence to the screen PRINT *, sequence END PROGRAM fibonacchi Some explanation to the code. To declare an array with unknown length we use the keywords, ALLOCATABLE, DIMENSION(:) where we replace the length of the array with a colon :. If we knew in advance the length of the array was 100 elements we could use this construct, DIMENSION(100). Since we want a dynamic program we have to use the first construct. Using the keyword PRINT * always prints the text to the screen with a linefeed as the last operation. This is not something we want in a user interface so we have to add some code to suppress the linefeed. This is why we use WRITE(*,FMT= (A)ADVANCE= NO ) instead of PRINT *. When we have stored the length of the array in the variable n we can allocate space for the array sequence using the construct: ALLOCATE(sequence(n), STAT=res). Then we test if the res is different from zero which means that the allocation failed and we stop the program. Then we initialize the first two elements of the array to one and start the loop calculating the next element in the sequence based on the value of the two previous elements. Note that we start the value of the index variable with the value of 3. that is because we already have given the first two elements og the array the value of 1. Finally we display the contents of the sequence on the screen. 12

13 File I/O Usually we do not enter data into a program manually. Mostly the data is generated either through the output of a program written to a file and not to the display, or from data produced by sensors in one way or another. We will now take a look at how we can read data from a file into an array, perform some operation on the data set and write the result to a new file. As before we have to think how we should break down the problem into smaller, more manageable parts. In our case w know in advance the length of the array which is 7 elements long. first we declare a static variable containing the length of the array. Then we declare two arrays, one to hold the Farenheit and the other to hold the Centigrades. In addition to this we need two character strings to hold the input filename and the output filename. Further we need two static variables to hold the unit numbers which we use to reference the two files with. These reference numbers are integers. Once we have declared these variables we also have to declare the index and status variable. Before we can access the contents of a file we have to open it using the unit number we declared and testing that the opening was successful. once we have opened the file we can read the contents into the array using a loop running from one to the length of the array. Once we have read in the contents of the file into the array we can then loop and convert from Farenheit to Centigrades storing the result into the other array. Once this conversion is finished we write the contents of the array to the output file after we have opened it like we did for the input file. As the alst thing to do is to close the files before the program terminates. The complete code with comments are shown below. PROGRAM temp_calc!// A program calculating centigrades from farenheit!// Create a static variable to hold the length of the array, PARAMETER :: n = 7!// Declare the arrays for the temperatures in Farenheit and!// Centigrades REAL,DIMENSION(n) :: farenheit REAL,DIMENSION(n) :: centigrade!// Index variables :: i!// Character strings to hold the filenames CHARACTER(LEN=80) :: farenheit_file CHARACTER(LEN=80) :: centigrade_file!// Constant values for the Logical Unit Number 13

14 !// for referencing the files for opening, reading!// and writing, PARAMETER :: ilun = 10, PARAMETER :: olun = 11!// A status variable to hold the result of file!// operations :: res!// Assign the input filename for Farenheit temp. farenheit_file = "farenheit.txt"!// Assign the output filename for Centigrade temp. centigrade_file = "centigrade.txt"!// Open the input file OPEN(UNIT=ilun,FILE=farenheit_file,FORM="FORMATTED",IOSTAT=res)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in opening file, status: ", res!// Stop the program STOP!// Loop and read each line of the file DO i = 1, n!// Read the current line READ(UNIT=ilun,FMT= (F4.1,X,F4.1),IOSTAT=res) farenheit(i)!// Was the read successful?!// No, test if we have reached End Of File (EOF) IF(res /= -1) THEN!// No, an error has occurred, print a message PRINT *, "Error in reading file, status: ", res!// Close the file CLOSE(UNIT=ilun)!// Stop the program STOP!// Loop and convert from Farenheit to Centigrade 14

15 DO i = 1, n centigrade(i) = (farenheit(i) - 32) * 5. / 9.!// Print the temperatures to the screen DO i = 1, 7 PRINT *, "Degrees Farenheit ", farenheit(i),& " Degrees Centigrade ",centigrade(i)!// Open the output file OPEN(UNIT=olun,FILE=outfile,FORM="FORMATTED",IOSTAT=res)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in opening output file, status: ", res!// Stop the program STOP DO i = 1, n WRITE(UNIT=olun,FMT= (F4.1,A1,F4.1),IOSTAT=res) centigrade(i)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in writing file, status: ", res!// Exit the loop EXIT!// Close the input file CLOSE(UNIT=ilun)!// Close the output file CLOSE(UNIT=olun) END PROGRAM temp_calc Again we need to comment some of the new things in the code. First we use the keyword PARAMETER to specify that the comtents of the static variable is not to be changed at runtime. Using the OPEN function we use the already mentioned unit number. then we provide the filename as part of the FILE argument and the result of the call to the open is returned in the IOSTAT=res keyword/argument pair. Much of the same procedure is used in erading and writing of data from 15

16 and to files. In this case we use formatted files which means that the file ca be displayed on the screen in contrast to bianry files which will only display garbage on the screen. Two examples of how a binary and formatted files looks like is shown ^@^@^@<B9><B8>_N^@H<C7>D$0P^@^@^@<BA>^C<FF><84> ^C3<C0>H<C7>D$8<80><DC>s^@L<8D>D$0H<C7>D$@ ^@^@^@H<C7>D$H<E0> N^@H<C7>D$P^D^@^@^@<E8>O<C3> As we can see the binary format is unreadable unless you use a program which convert from binary to ASCII format, where ASCII format is the same as a formatted file in Fortran. ASCII is short for American Standard Code for Iformation Interchange. Next wh anve the format description of the file contents. We use the keyword/argument pair FMT= (F4.1,X,F4.1) to tell the system that we have a floating point number with 4 digits including the decimal point and one decimal, a space character and then another floating point number like the first. 16

17 Multidimensional arrays In the field of Meteorology and Oceanography the data sets we operate on is usually in four dimensions, space and time. this means that we have to declare matrices in four dimensions to be able to store the data. the next example shows how we can use a two dimensional matrix to store a set of temperatures in Farenheit from two measuring stations read in from a file and convert the temperatures into Centigrades. The solution will be just like the previous program with the exception that we here operate on a matrix with two dimensions and thus needs a nested loop to perform the calculations. The complete code is shown below. PROGRAM temp_calc2!// A program calculating Centigrades from Farenheit from two!// measuring stations!// Declare the arrays for the temperatures in Farenheit and!// Centigrades REAL,DIMENSION(7,2) :: farenheit REAL,DIMENSION(7,2) :: centigrade!// Index variables :: i, j!// Character strings to hold the filenames CHARACTER(LEN=80) :: farenheit_file CHARACTER(LEN=80) :: centigrade_file!// Constant values for the Logical Unit Number!// for referencing the files for opening, reading!// and writing, PARAMETER :: ilun = 10, PARAMETER :: olun = 11!// A status variable to hold the result of file!// operations :: res!// Assign the input filename for Farenheit temp. farenheit_file = "farenheit.txt"!// Assign the output filename for Centigrade temp. centigrade_file = "centigrade.txt"!// Open the Farenheit input file OPEN(UNIT=ilun,FILE=farenheit_file,FORM="FORMATTED",IOSTAT=res)!// Test if the operation was successful 17

18 !// No, an error occurred, print a message to!// the screen PRINT *, "Error in opening file, status: ", res!// Stop the program STOP!// Loop and read each line of the file DO i = 1, 7!// Read the current line READ(UNIT=ilun,FMT= (F4.1,X,F4.1),IOSTAT=res) farenheit(i,1), & farenheit(i,2)!// Was the read successful?!// No, test if we have reached End Of File (EOF) IF(res /= -1) THEN!// No, an error has occurred, print a message PRINT *, "Error in reading file, status: ", res!// Close the file CLOSE(UNIT=ilun)!// Stop the program STOP!// Close the input file CLOSE(UNIT=ilun)!// Loop and convert from Farenheit to Centigrade DO j = 1, 2 DO i = 1, 7 centigrade(i,j) = (farenheit(i,j) - 32) * 5./9.!// Open the Centigrade output file OPEN(UNIT=olun,FILE=centigrade_file,FORM="FORMATTED",IOSTAT=res)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in opening output file, status: ", res!// Stop the program STOP 18

19 DO i = 1, 7 WRITE(UNIT=olun,FMT= (F4.1,A1,F4.1),IOSTAT=res) centigrade(i,1),, & centigrade(i,2)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in writing file, status: ", res!// Exit the loop EXIT!// Close the output file CLOSE(UNIT=olun) END PROGRAM temp_calc2 Like in he previous section we need to explain a couple of things, mainly the use of the nested loops. It is important for the efficiency of the program to know how Fortran accesses a matrix. Fortran and also Matlab accesses a matrix column wise. It means that all the row elements in a column will be accessed before the row elements in the next column. This is in contrast to other programming languages which accesses all the column elements in a row before moving to the next row just like we would read each line of text before moving th the next line. Therefore it is a rule of thumb to always have the first index in the innermost loop using Fortran (and Matlab). 19

20 Functions and Subroutines It is not a very good programming style to write a long program with all the necessary code in one source file. this makes the program difficult to maintain and to understand. usually we break down a problem into smaller parts like functions or subroutines. In this section we will extend the program from the previous section to read temperatures stored in either Farenheit or Centigrades and perform the correct conversion using functions for the conversion. We need therefore two functions, one which we will call f2c() and the other c2f(). First we program f2c() like this: FUNCTION f2c(f) RESULT(C)!// The input argument which is read only REAL(KIND=8), INTENT(IN) :: F!// The result from the calculations REAL(KIND=8) :: C!// Perform the calculation C = (F -32) * 5./9.!// Return the result RETURN END FUNCTION f2c And c2f().like this: FUNCTION c2f(c) RESULT(F)!// The input argument which is read only REAL(KIND=8), INTENT(IN) :: C!// The result from the calculations REAL(KIND=8) :: F!// Perform the calculation F = (C * 9. / 5.) + 32!// Return the result RETURN END FUNCTION f2c In contrast to the way we write mathematical functions Fortran are using a keyword RESULT(arg) where the datatype of the argument states what kind of function it is. In Fortran 77 and older versions the syntax was REAL FUNCTION f2c(arg). Note the use of INTENT(IN) for the input argument to the functions. This is to prevent accidental overwriting of the argument since Fortran function and subroutine arguments are always called by reference and not 20

21 by value. The only thing we need to do in the main program with the exception of the user interface is to replace the formula for the conversion with a call to the respective functions. Note that in order to use other the Fortran intrinsic functions we have to declare them as external functions of the correct type. If we omit the external attribute the compiler will flag en error and the compilation will be aborted. The complete main program is shown below. PROGRAM array2!// A program calculating centigrades from Farenheit to Centigrades!// and vice versa!// Declare the arrays for the temperatures in Farenheit and!// Centigrades REAL,DIMENSION(7,2) :: farenheit REAL,DIMENSION(7,2) :: centigrade!// Index variables :: i, j!// Character strings to hold the filenames CHARACTER(LEN=80) :: farenheit_file CHARACTER(LEN=80) :: centigrade_file!// Constant values for the Logical Unit Number!// for referencing the files for opening, reading!// and writing, PARAMETER :: ilun = 10, PARAMETER :: olun = 11!// A status variable to heold the result of file!// operations :: res!// External function(s) REAL, EXTERNAL :: f2c REAL, EXTERNAL :: c2f!// A character string for a prompt CHARACTER(LEN=80) :: prompt CHARACTER :: answer!// Assign the input filename for Farenheit temp. farenheit_file = "farenheit.txt"!// Assign the output filename for Centigrade temp. centigrade_file = "centigrade.txt"!// Ask the user if we are converting from farenheit to!// centigrade or from centigrade to farenheit 21

22 prompt = Convert from Farenheit to Centigrade (F/C)? PRINT *, TRIM(prompt) READ(*,*) answer!// Check if the answer is F or f for Farenheit IF(answer.EQ. F.OR. answer.eq. f ) THEN!// Yes, open the Farenheit input file OPEN(UNIT=ilun,FILE=farenheit_file,FORM="FORMATTED",IOSTAT=res)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in opening file, status: ", res!// Stop the program STOP!// Loop and read each line of the file DO i = 1, 7!// Read the current line READ(UNIT=ilun,FMT= (F4.1,X,F4.1),IOSTAT=res) farenheit(i,1), & farenheit(i,2)!// Was the read successful?!// No, test if we have reached End Of File (EOF) IF(res /= -1) THEN!// No, an error has occurred, print a message PRINT *, "Error in reading file, status: ", res!// Close the file CLOSE(UNIT=ilun)!// Stop the program STOP ELSE!// No, open the Centigrade input file OPEN(UNIT=lun,FILE=centigrade_file,FORM="FORMATTED",IOSTAT=res)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in opening file, status: ", res 22

23 !// Stop the program STOP!// Loop and read each line of the file DO i = 1, 7!// Read the current line READ(UNIT=ilun,FMT= (F4.1,X,F4.1),IOSTAT=res) centigrade(i,1), & centigrade(i,2)!// Was the read successful?!// No, test if we have reached End Of File (EOF) IF(res /= -1) THEN!// No, an error has occurred, print a message PRINT *, "Error in reading file, status: ", res!// Close the file CLOSE(UNIT=ilun)!// Stop the program STOP!// Close the input file CLOSE(UNIT=ilun)!// Which way to convert? IF(answer.EQ. F.OR. answer.eq. f ) THEN!// Loop and convert from Farenheit to Centigrade DO j = 1, 2 DO i = 1, 7 centigrade(i,j) = f2c(farenheit(i,j)) ELSE!// Loop and convert from Centigrade to Farenheit DO j = 1, 2 DO i = 1, 7 farenheit(i,j) = c2f(centigrade(i,j)) 23

24 !// Which file to write to? IF(answer.EQ. F.OR. answer.eq. f ) THEN!// Open the Centigrade output file OPEN(UNIT=olun,FILE=centigrade_file,FORM="FORMATTED",IOSTAT=res)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in opening output file, status: ", res!// Stop the program STOP DO i = 1, 7 WRITE(UNIT=olun,FMT= (F4.1,A1,F4.1),IOSTAT=res) centigrade(i,1),, & centigrade(i,2)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in writing file, status: ", res!// Exit the loop EXIT ELSE!// Open the Farenheit output file OPEN(UNIT=olun,FILE=farenheit_file,FORM="FORMATTED",IOSTAT=res)!// Test if the operation was successful!// No, an error occurred, print a message to!// the screen PRINT *, "Error in opening output file, status: ", res!// Stop the program STOP DO i = 1, 7 WRITE(UNIT=olun,FMT= (F4.1,A1,F4.1),IOSTAT=res) farenheit(i,1),, & farenheit(i,2)!// Test if the operation was successful!// No, an error occurred, print a message to 24

25 !// the screen PRINT *, "Error in writing file, status: ", res!// Exit the loop EXIT!// Close the output file CLOSE(UNIT=olun) END PROGRAM array2 In contrast to the functions a subroutine does not return a value and is the same as a void function in other languages. We can replace the f2c() and c2f() with corresponding subroutines which can look like this: SUBROUTINE f2c(f,c)!// The input argument which is read only REAL(KIND=8), INTENT(IN) :: F!// The result of the conversion which is!// write only REAL(KIND=8), INTENT(OUT) :: C!// Perform the conversion C = (F -32) * 5./9.!// Return the result through the second argument RETURN END SUBROUTINE f2c SUBROUTINE c2f(c,f)!// The input argument which is read only REAL(KIND=8), INTENT(IN) :: C!// The result of the conversion which is REAL(KIND=8), INTENT(OUT) :: F!// Perform the conversion F = (C * 9. / 5.) + 32!// Return the result through the second argument RETURN END SUBROUTINE c2f The calling from the main program is like this:... 25

26 !// Loop and perform the conversion using!// nested loops DO j = 1, 2 DO i = 1, 7!// Call the subroutine with the current element!// of the farenheit array as the first argument to!// the soubroutine and the current element of the!// centigrade array as the second argument. CALL f2c(farenheit(i,j),centigrade(i,j))...!// Loop and perform the conversion using!// nested loops DO j = 1, 2 DO i = 1, 7!// Call the subroutine with the current element!// of the farenheit array as the first argument to!// the soubroutine and the current element of the!// centigrade array as the second argument. CALL c2f(centigrade(i,j).farenheit(i,j)) A subroutine shall not be declared as external, only non intrinsic functions. Also note the use of the INTENT(OUT) which means we can only give value to the argument and trying to read the valeu fro the argument would flag a compilation error just like it would if we were trying to give the argument a value when it has the attribute INTENT(IN) which means read only. 26

27 Modules Now it is time to progress further into the world of Fortran programming. We know now how to use functions and subroutines, but often we need to put global variables together with the corresponding procedures working with these variables. It is here we utilize the MODULE which was introduced in Fortran 90. A module consists of a set of variable declarations and an optional set of functions and subroutines working on the variables. A skeleton module can look like this: MODULE my_module!// Global variable declarations CONTAINS!// Procedure declarations END MODULE my_module A module always starts with the keyword MODULE module_name and ends with the keyword END MODULE module_name. to separate the variable declarations from the procedure declarations the keyword CONTAINS is used. To create a module all we have to do is to fill in the variables and procedures. Note that we use procedure as a common name for functions and subroutines here. We shall now transfer our temperature conversion program into a module with five separate functions and subroutines and corresponding global variables and constants. MODULE my_module!// Arrays and strings!// The array containing the temperature which we!// will perform the conversion from REAL(KIND=8),ALLOCATABLE,DIMENSION(:,:) :: from!// The array receiving the converted temperature REAL(KIND=8),ALLOCATABLE,DIMENSION(:,:) :: to!// A character string containing the name of the input!// file CHARACTER(LEN=80) :: infile!// A character string containing the name of the output!// file CHARACTER(LEN=80) :: outfile!// A single character containing the type of temperature!// which will be the input (F or C) CHARACTER :: conversion 27

28 !// Integers to hold the number of rows columns of!// arrays :: m, n CONTAINS!// The procedure declarations FUNCTION f2c(f) RESULT(C)!// The input argument which is read only REAL(KIND=8), INTENT(IN) :: F!// The result from the calculations REAL(KIND=8) :: C!// Perform the calculation C = (F -32) * 5./9.!// Return the result RETURN END FUNCTION f2c FUNCTION c2f(c) RESULT(F)!// The input argument which is read only REAL(KIND=8), INTENT(IN) :: C!// The result from the calculations REAL(KIND=8) :: F!// Perform the calculation F = (C * 9. / 5.) + 32!// Return the result RETURN END FUNCTION c2f!// Subroutines skeleton SUBROUTINE load(res) :: res,parameter :: lun = 10 END SUBROUTINE load SUBROUTINE dump(res) :: res 28

29 ,PARAMETER :: lun = 10 END SUBROUTINE dump SUBROUTINE solve(res) END SUBROUTINE solve :: res END MODULE my_module Here we have a skeleton outlining the module. All we have to do is to fill in the missing code in the three subroutines since we already have written the two functions f2c and c2f. Let us take the first subroutine load and write it. In this case the input file contains a description of the contents of the file and then two integers telling the size of the array in number of columns and rows. We have to open the file and read the first line discarding it since we are interested in the two integers so we can allocate space for the arrays. The code solving this problem can look like this: SUBROUTINE load(res)!// Argument containing the result of the operations in the!// subroutine :: res!// Index variables :: i, j, k, l!// The unit number associated with the file,parameter :: lun = 10!// Help variable for use with extracting each!// number from the buffer :: buff_end!// A character string to hold each line read from the!// file CHARACTER(LEN=256) :: buffer!// A help variable to hold each ASCII number CHARACTER(LEN=20) :: tmp_num!// An external function converting from ASCII digits to!// a binary floating point number REAL(KIND=8),EXTERNAL :: a2d!// Open the file OPEN(UNIT=lun,FILE=TRIM(infile),FORM= FORMATTED,IOSTAT=res)!// Is the open a success? 29

30 !// No, print an error message and return to the main!// program PRINT *, Error in opening file, status:, res RETURN READ(UNIT=lun,FMT= (A),IOSTAT=res) buffer!// Print an error message and return to the main!// program PRINT *, Error in reading file, status:, res CLOSE(UNIT=lun) RETURN READ(UNIT=lun,FMT= (I4),IOSTAT=res) m!// Print an error message and return to the main!// program PRINT *, Error in reading file, status:, res CLOSE(UNIT=lun) RETURN READ(UNIT=lun,FMT= (I4),IOSTAT=res) n!// Print an error message and return to the main!// program PRINT *, Error in reading file, status:, res CLOSE(UNIT=lun) RETURN ALLOCATE(F(m,n),STAT=res)!// Print an error message and return to the main!// program PRINT *, Error in allocating space, status:, res CLOSE(UNIT=lun) RETURN ALLOCATE(C(m,n),STAT=res)!// Print an error message and return to the main 30

31 !// program PRINT *, Error in allocating space, status:, res CLOSE(UNIT=lun) RETURN... END SUBROUTINE load Now we have managed to retrieve the size of the array and allocated the necessary space for the array we can proceed with reading the values into the array. Depending on the formatting of the values we have to adjust the way we read the data into the array. Normally we read in one line at the time and convert the ASCII digits to binary numbers in one way or another. Very often this kind of data is presented as a comma separated text file where each number is separated from the next with a comma, a semicolon or just a space character. We will therefore assume that our file is such a.csv file and write the code to support this file type. SUBROUTINE load(res)...!// Loop and read all the lines from the file DO i = 1, m!// Clear the buffer character string buffer =!// Read the line into the buffer READ(UNIT=lun,FMT= (A),IOSTAT=res), buffer!// Was the operation successful?!// No, print an error message and return to the main!// program PRINT *, Error in reading file, status:, res!// colse the input file CLOSE(UNIT=lun)!// Return to the main program RETURN!// Fine the number of characters in the buffer with the!// exception of trailing space buff_end = LEN_TRIM(buffer)!// Initialize index variables j = 1 l = 1 31

32 !// Find the next comma in the buffer and extract the!// ASCII digits for this number DO k = 1,buff_End IF(buffer(k:k).EQ., ) THEN!// Convert form ASCII digits to a binary number!// using the external function a2f (ASCII to floating) from(i,j) = a2d(buffer(l:k-1))!// Update index variables j = j + 1 l = k + 1!// Close the input file CLOSE(UNIT=lun) END SUBROUTINE load Here we traverse each line of data and extract the temperature taking the part of the text that contains the number in ASCII digits to real number using the a2f function which is an external function for the conversion of ASCII digits to floating point. Having the load subroutine ready we will take a look at the dump subroutine. This works in many way like load, but is much easier to program not needing the conversion from ASCII digits to binary numbers. So let us roll up our sleeves and start coding. SUBROUTINE dump(res)!// Argument containing the result of the operations in the!// subroutine :: res!// Index variables :: i, j!// Unit number associated with the file,parameter :: lun = 10!// Open the file OPEN(UNIT=lun,FILE=TRIM(outfile),FORM= FORMATTED,IOSTAT=res)!// Print an error message and return to the main!// program PRINT *, Error in opening file, status:, res RETURN 32

33 !// Write the number of rows and columns to the file WRITE(UNIT=lun,FMT= (I4),IOSTAT=res) m!// Print an error message and return to the main!// program PRINT *, Error in writing file, status:, res RETURN WRITE(UNIT=lun,FMT= (I4),IOSTAT=res) n!// Print an error message and return to the main!// program PRINT *, Error in writing file, status:, res RETURN!// Loop and write the converted temperatures to the!// output file DO i = 1,n DO j = 1, m -1!// Write the n-1 elements of the row to the file!// separated by a comma WRITE(UNIT=lun,FMT= (F4.1,A1),ADVANCE= NO ) to(i,j),,!// Print an error message and return to the main!// program PRINT *, Error in writing file, status:, res RETURN!// Write the nth element of the row to the file!// separated by a comma WRITE(UNIT=lun,FMT= (F4.1),IOSTAT=res) to(i,m)!// Print an error message and return to the main!// program PRINT *, Error in writing file, status:, res RETURN!// Close the output file CLOSE(UNIT=lun) 33

34 END SUBROUTINE dump Simple compared to load is it not? then all we have to do is write the solve subroutine which can be done like this. SUBROUTINE solve(res)!// Argument containing the result of the operations in the!// subroutine :: res!// Index variables :: i, j!// Test which way to convert IF(conversion.EQ. F ) THEN!// Loop and convert from Farenheit to Centigrades DO j = 1,m DO i = 1, n!// Calling f2c with the current element of from as!// input argument and put the result in the!// corresponding element in the to array to(i,j) = f2c(from(i,j)) ELSE!// Loop and convert from Centigrades to Farenheit DO j = 1,m DO i = 1, n!// Calling c2f with the current element of from as!// input argument and put the result in the!// corresponding element in the to array to(i,j) = c2f(from(i,j)) END SUBROUTINE solve This is also quite simple. We just check which way to convert and then call the correct function within the nested loops. The only thing different her and in the load and dump subroutines is the way we traverse the array. Note that we are traversing the array column by column in load and dump, but row by row in the solve. The last one is, as mentioned before, the correct way in Fortran, but due to the way the data is stored in the files we have to go the "wrong way" in load and dump. 34

35 The only thing to do now is to write the main program which will use the module. The program can look like this. PROGRAM convert_temp!// The main program!// Use the module called my_module USE my_module!// A status variable :: res!// Ask the user which way to convert WRITE(*,FMT= (A),ADVANCE= NO ) & Enter F for conversion from Farenheit or C the other wy: READ(*,*) conversion!// Ask the user for the input file WRITE(*,FMT= (A),ADVANCE= NO ) & Enter the name of the input file: READ(*,*) infile!// Ask the user for the output file WRITE(*,FMT= (A),ADVANCE= NO ) & Enter the name of the output file: READ(*,*) outfile!// Call the load subroutine sith the status!// variable as the only argument CALL load(res)!// Was the call successful?!// No, stop the program STOP CALL solve(res)!// Was the call successful?!// No, stop the program STOP CALL dump(res)!// Was the call successful?!// No, stop the program 35

36 STOP END PROGRAM convert_temp As we can see the main program is quite small, as it should be, and all the work is done in the procedures in the module. This shows that using modules will give us a more structured program which is far more readable and easy to understand than putting all the code in one large file. Also a module can use another module and so on so we can have a hierarchical structure of the program. In order to compile and run this program we have to take the compilation either in one step or we can use two steps. It is often preferable to use two steps since it is easier to trace syntax errors in the source code that way. The two steps are like this. gfortran -c my_module.f90 gfortran -o convert_temp convert_temp.f90 my_module.o -L./ -lstrconv The first step with the c tells the compiler to take the source code and compile it into an intermediate binary object file with the extension.o. The second step tells the compiler to produce an executable binary program consisting of the compiled source code for the main program and then link the contents of the object file into the executable program together with procedures from a library using the -L./ -lstrconv to tell the compiler that the location of the library is in the current directory and the library file is libstrconv.a shortened to -lstrconv which is the standard way of writing it. When this has been successfully completed we just type the name of the executable program in a terminal window to run it. 36

37 Optimization As the programs grow larger and the datasets we are using are increasing in size we have to make our program work as fast as possible. This is not an easy task to do on our own, but we shall look at some small things that we can do to optimize our code. The following items will help us to make the code run faster. Use the compiler options for optimizing the code Be sure to traverse matrices the correct way according to the programming language. Put all tests and calculations outside loops when it is possible Do all assignment of a value to a variable only once if it will not change while running the program. One of the compiler flags mostly used for optimization is the On wher n is the level of optimization. For most compilers O3 it the highest level of optimization. Note that in some cases where the code consists of several hundred thousand of lines this level of optimization can cause problem because of the size of the code. A last advice is to learn the various options your compiler offers and use it to make your pgorgam run faster. 37

UNIVERSITY OF OSLO Department of Geosciences. GEO4060: Intro to Fortran 2003 programming. Gunnar Wollan

UNIVERSITY OF OSLO Department of Geosciences. GEO4060: Intro to Fortran 2003 programming. Gunnar Wollan UNIVERSITY OF OSLO Department of Geosciences GEO4060: Intro to Fortran 2003 programming Gunnar Wollan Spring 2014 Contents 1 Introduction 2 1.1 Why use Fortran?.................................... 2 1.2

More information

write (unit=*,fmt=*) i =, i! will print: i = 3

write (unit=*,fmt=*) i =, i! will print: i = 3 I/O (F book, chapters 9, 10 and 15) All I/O in Fortran90 is record-based, typically with record delimiters of some kind. This is in contrast to C, which has stream I/O, with no record delimiters required.

More information

FORTRAN 90: Functions, Modules, and Subroutines. Meteorology 227 Fall 2017

FORTRAN 90: Functions, Modules, and Subroutines. Meteorology 227 Fall 2017 FORTRAN 90: Functions, Modules, and Subroutines Meteorology 227 Fall 2017 Purpose First step in modular program design Cannot always anticipate all of the steps that will be needed to solve a problem Easier

More information

Our Strategy for Learning Fortran 90

Our Strategy for Learning Fortran 90 Our Strategy for Learning Fortran 90 We want to consider some computational problems which build in complexity. evaluating an integral solving nonlinear equations vector/matrix operations fitting data

More information

MATLAB. Devon Cormack and James Staley

MATLAB. Devon Cormack and James Staley MATLAB Devon Cormack and James Staley MATrix LABoratory Originally developed in 1970s as a FORTRAN wrapper, later rewritten in C Designed for the purpose of high-level numerical computation, visualization,

More information

A quick guide to Fortran

A quick guide to Fortran A quick guide to Fortran Sergiy Bubin Department of Physics Nazarbayev University History of Fortran One of the oldest general purpose high-level computer languages First developed in 1957 at IBM in the

More information

Topic 6: A Quick Intro To C

Topic 6: A Quick Intro To C Topic 6: A Quick Intro To C Assumption: All of you know Java. Much of C syntax is the same. Also: Many of you have used C or C++. Goal for this topic: you can write & run a simple C program basic functions

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Evolution of Fortran. Presented by: Tauqeer Ahmad. Seminar on Languages for Scientific Computing

Evolution of Fortran. Presented by: Tauqeer Ahmad. Seminar on Languages for Scientific Computing Evolution of Fortran Presented by: Seminar on Languages for Scientific Computing Outline (1) History of Fortran Versions FORTRAN I FORTRAN II FORTRAN III FORTRAN IV FORTRAN 66 FORTRAN 77 Evolution of FORTRAN

More information

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Ordinary Differential Equation Solver Language (ODESL) Reference Manual Ordinary Differential Equation Solver Language (ODESL) Reference Manual Rui Chen 11/03/2010 1. Introduction ODESL is a computer language specifically designed to solve ordinary differential equations (ODE

More information

AMath 483/583 Lecture 8

AMath 483/583 Lecture 8 AMath 483/583 Lecture 8 This lecture: Fortran subroutines and functions Arrays Dynamic memory Reading: class notes: Fortran Arrays class notes: Fortran Subroutines and Functions class notes: gfortran flags

More information

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++ Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

An Introduction to Fortran

An Introduction to Fortran An Introduction to Fortran Sylvia Plöckinger March 10, 2011 Sylvia Plöckinger () An Introduction to Fortran March 10, 2011 1 / 43 General Information Find this file on: http://homepage.univie.ac.at/nigel.mitchell/numprac/

More information

TABLE OF CONTENTS 2 CHAPTER 1 3 CHAPTER 2 4 CHAPTER 3 5 CHAPTER 4. Algorithm Design & Problem Solving. Data Representation.

TABLE OF CONTENTS 2 CHAPTER 1 3 CHAPTER 2 4 CHAPTER 3 5 CHAPTER 4. Algorithm Design & Problem Solving. Data Representation. 2 CHAPTER 1 Algorithm Design & Problem Solving 3 CHAPTER 2 Data Representation 4 CHAPTER 3 Programming 5 CHAPTER 4 Software Development TABLE OF CONTENTS 1. ALGORITHM DESIGN & PROBLEM-SOLVING Algorithm:

More information

Introduction to MATLAB

Introduction to MATLAB Chapter 1 Introduction to MATLAB 1.1 Software Philosophy Matrix-based numeric computation MATrix LABoratory built-in support for standard matrix and vector operations High-level programming language Programming

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

SOEE1160: Computers and Programming in Geosciences Semester /08. Dr. Sebastian Rost

SOEE1160: Computers and Programming in Geosciences Semester /08. Dr. Sebastian Rost SOEE1160 L3-1 Structured Programming SOEE1160: Computers and Programming in Geosciences Semester 2 2007/08 Dr. Sebastian Rost In a sense one could see a computer program as a recipe (this is pretty much

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Review More Arrays Modules Final Review

Review More Arrays Modules Final Review OUTLINE 1 REVIEW 2 MORE ARRAYS Using Arrays Why do we need dynamic arrays? Using Dynamic Arrays 3 MODULES Global Variables Interface Blocks Modular Programming 4 FINAL REVIEW THE STORY SO FAR... Create

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

3. Simple Types, Variables, and Constants

3. Simple Types, Variables, and Constants 3. Simple Types, Variables, and Constants This section of the lectures will look at simple containers in which you can storing single values in the programming language C++. You might find it interesting

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

Scientific Programming in C X. More features & Fortran interface

Scientific Programming in C X. More features & Fortran interface Scientific Programming in C X. More features & Fortran interface Susi Lehtola 20 November 2012 typedef typedefs are a way to make shorthand for data types, and possibly also make the code more general

More information

Why Study Assembly Language?

Why Study Assembly Language? Why Study Assembly Language? This depends on the decade in which you studied assembly language. 1940 s You cannot study assembly language. It does not exist yet. 1950 s You study assembly language because,

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

Review Functions Subroutines Flow Control Summary

Review Functions Subroutines Flow Control Summary OUTLINE 1 REVIEW 2 FUNCTIONS Why use functions How do they work 3 SUBROUTINES Why use subroutines? How do they work 4 FLOW CONTROL Logical Control Looping 5 SUMMARY OUTLINE 1 REVIEW 2 FUNCTIONS Why use

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Program Organization and Comments

Program Organization and Comments C / C++ PROGRAMMING Program Organization and Comments Copyright 2013 Dan McElroy Programming Organization The layout of a program should be fairly straight forward and simple. Although it may just look

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

MATLIP: MATLAB-Like Language for Image Processing

MATLIP: MATLAB-Like Language for Image Processing COMS W4115: Programming Languages and Translators MATLIP: MATLAB-Like Language for Image Processing Language Reference Manual Pin-Chin Huang (ph2249@columbia.edu) Shariar Zaber Kazi (szk2103@columbia.edu)

More information

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB: Contents VARIABLES... 1 Storing Numerical Data... 2 Limits on Numerical Data... 6 Storing Character Strings... 8 Logical Variables... 9 MATLAB S BUILT-IN VARIABLES AND FUNCTIONS... 9 GETTING HELP IN MATLAB...

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

COMP 110 Project 1 Programming Project Warm-Up Exercise

COMP 110 Project 1 Programming Project Warm-Up Exercise COMP 110 Project 1 Programming Project Warm-Up Exercise Creating Java Source Files Over the semester, several text editors will be suggested for students to try out. Initially, I suggest you use JGrasp,

More information

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead. Chapter 9: Rules Chapter 1:Style and Program Organization Rule 1-1: Organize programs for readability, just as you would expect an author to organize a book. Rule 1-2: Divide each module up into a public

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Kadi Sarva Vishwavidyalaya, Gandhinagar

Kadi Sarva Vishwavidyalaya, Gandhinagar Kadi Sarva Vishwavidyalaya, Gandhinagar MASTERS OF COMPUTER APPLICATION (MCA) Semester I (First Year) Subject: MCA-101 Programming for Logic Building (LDPL) SUB Teaching scheme Examination scheme Total

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

Compiler Design. Computer Science & Information Technology (CS) Rank under AIR 100

Compiler Design. Computer Science & Information Technology (CS) Rank under AIR 100 GATE- 2016-17 Postal Correspondence 1 Compiler Design Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts,

More information

CROSSREF Manual. Tools and Utilities Library

CROSSREF Manual. Tools and Utilities Library Tools and Utilities Library CROSSREF Manual Abstract This manual describes the CROSSREF cross-referencing utility, including how to use it with C, COBOL 74, COBOL85, EXTENDED BASIC, FORTRAN, Pascal, SCREEN

More information

Computer Vision. Matlab

Computer Vision. Matlab Computer Vision Matlab A good choice for vision program development because Easy to do very rapid prototyping Quick to learn, and good documentation A good library of image processing functions Excellent

More information

(Refer Slide Time 01:41 min)

(Refer Slide Time 01:41 min) Programming and Data Structure Dr. P.P.Chakraborty Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture # 03 C Programming - II We shall continue our study of

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 7 Input/Output

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 7 Input/Output ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 7 Input/Output Reading: Bowman, Chapters 10-12 READING FROM THE TERMINAL The READ procedure is used to read from the terminal. IDL

More information

Standard 11. Lesson 9. Introduction to C++( Up to Operators) 2. List any two benefits of learning C++?(Any two points)

Standard 11. Lesson 9. Introduction to C++( Up to Operators) 2. List any two benefits of learning C++?(Any two points) Standard 11 Lesson 9 Introduction to C++( Up to Operators) 2MARKS 1. Why C++ is called hybrid language? C++ supports both procedural and Object Oriented Programming paradigms. Thus, C++ is called as a

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 4 Certificate in IT SOFTWARE DEVELOPMENT

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 4 Certificate in IT SOFTWARE DEVELOPMENT BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 4 Certificate in IT SOFTWARE DEVELOPMENT Wednesday 25th March 2015 - Afternoon Time: TWO hours Section A and Section B each

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

An Introduction to MATLAB. Lab tutor : Dennis Yang LIU Lab 1: Sept. 11, 2014

An Introduction to MATLAB. Lab tutor : Dennis Yang LIU   Lab 1: Sept. 11, 2014 Lab 1 of COMP 319 An Introduction to MATLAB Lab tutor : Dennis Yang LIU Email: csygliu@comp.polyu.edu.hk Lab 1: Sept. 11, 2014 1 Outline of Lab 1 Introduction to the Lab Matlab overview Basic manipulation

More information

Basics of Programming

Basics of Programming Unit 2 Basics of Programming Problem Analysis When we are going to develop any solution to the problem, we must fully understand the nature of the problem and what we want the program to do. Without the

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

Introduction to Modern Fortran

Introduction to Modern Fortran Introduction to Modern Fortran p. 1/?? Introduction to Modern Fortran Advanced I/O and Files Nick Maclaren Computing Service nmm1@cam.ac.uk, ext. 34761 November 2007 Introduction to Modern Fortran p. 2/??

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Topic 6: A Quick Intro To C. Reading. goto Considered Harmful History Topic 6: A Quick Intro To C Reading Assumption: All of you know basic Java. Much of C syntax is the same. Also: Some of you have used C or C++. Goal for this topic: you can write & run a simple C program

More information

2. Basic Elements of Fortran

2. Basic Elements of Fortran 2. Basic Elements of Fortran Structure of a Fortran Program 31 characters must be in the 1st line if present declaration section program my_first_program! Declare variables integer :: i, j, k! i, j, k

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Examining the Code. [Reading assignment: Chapter 6, pp ]

Examining the Code. [Reading assignment: Chapter 6, pp ] Examining the Code [Reading assignment: Chapter 6, pp. 91-104] Static white-box testing Static white-box testing is the process of carefully and methodically reviewing the software design, architecture,

More information

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Data Types, Variables and Arrays OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani Identifiers in Java Identifiers are the names of variables, methods, classes, packages and interfaces. Identifiers must

More information

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

More information

The Warhol Language Reference Manual

The Warhol Language Reference Manual The Warhol Language Reference Manual Martina Atabong maa2247 Charvinia Neblett cdn2118 Samuel Nnodim son2105 Catherine Wes ciw2109 Sarina Xie sx2166 Introduction Warhol is a functional and imperative programming

More information

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << The sum of the integers 1 to 10 is  << sum << endl; Debugging Some have said that any monkey can write a program the hard part is debugging it. While this is somewhat oversimplifying the difficult process of writing a program, it is sometimes more time

More information

variables programming statements

variables programming statements 1 VB PROGRAMMERS GUIDE LESSON 1 File: VbGuideL1.doc Date Started: May 24, 2002 Last Update: Dec 27, 2002 ISBN: 0-9730824-9-6 Version: 0.0 INTRODUCTION TO VB PROGRAMMING VB stands for Visual Basic. Visual

More information

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program Syntax What the Compiler needs to understand your program 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line Possibly replacing it with other

More information

Computer Programming: C++

Computer Programming: C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming: C++ Experiment #7 Arrays Part II Passing Array to a Function

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

Outline. Program development cycle. Algorithms development and representation. Examples.

Outline. Program development cycle. Algorithms development and representation. Examples. Outline Program development cycle. Algorithms development and representation. Examples. 1 Program Development Cycle Program development cycle steps: Problem definition. Problem analysis (understanding).

More information

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0 VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 L J Howell UX Software 2009 Ver. 1.0 TABLE OF CONTENTS INTRODUCTION...ii What is this book about?... iii How to use this book... iii

More information

c Microsoft, 1977, 1978, 1979

c Microsoft, 1977, 1978, 1979 c Microsoft, 1977, 1978, 1979 Microsoft FORTRAN 80 User's Manual CONTENTS SECTION 1 1.1 1.2 1.3 Compiling FORTRAN Programs 5 FORTRAN-80 Command Scanner..... 5 1.1.1 Format of Commands......... 5 1.1.2

More information

What is MATLAB and howtostart it up?

What is MATLAB and howtostart it up? MAT rix LABoratory What is MATLAB and howtostart it up? Object-oriented high-level interactive software package for scientific and engineering numerical computations Enables easy manipulation of matrix

More information

Computer Programming C++ (wg) CCOs

Computer Programming C++ (wg) CCOs Computer Programming C++ (wg) CCOs I. The student will analyze the different systems, and languages of the computer. (SM 1.4, 3.1, 3.4, 3.6) II. The student will write, compile, link and run a simple C++

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Introduction to C Programming

Introduction to C Programming 1 2 Introduction to C Programming 2.6 Decision Making: Equality and Relational Operators 2 Executable statements Perform actions (calculations, input/output of data) Perform decisions - May want to print

More information

Variables and Constants

Variables and Constants HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and

More information

CMAT Language - Language Reference Manual COMS 4115

CMAT Language - Language Reference Manual COMS 4115 CMAT Language - Language Reference Manual COMS 4115 Language Guru: Michael Berkowitz (meb2235) Project Manager: Frank Cabada (fc2452) System Architect: Marissa Ojeda (mgo2111) Tester: Daniel Rojas (dhr2119)

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Sprite an animation manipulation language Language Reference Manual

Sprite an animation manipulation language Language Reference Manual Sprite an animation manipulation language Language Reference Manual Team Leader Dave Smith Team Members Dan Benamy John Morales Monica Ranadive Table of Contents A. Introduction...3 B. Lexical Conventions...3

More information

Chapter 2: Overview of C++

Chapter 2: Overview of C++ Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman C++ Background Introduced by Bjarne Stroustrup of AT&T s Bell Laboratories in

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Chapter 1 & 2 Introduction to C Language

Chapter 1 & 2 Introduction to C Language 1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information