CS310 Team Lab #15
ForTran Programming
Programming

OBJECTIVES

INTRODUCTION

FORTRAN is flexible, fast, and found in lots of demanding scientific computing problems! 

There are many reasons programmers learn to program in more than one programming language.  Usually it's to take advantage of features that exist or are more sophisticated or execute faster in one language over another.   Sometimes its because all of the existing code for that area of interest is written in the other language.

We chose FORTRAN for this unit because a number of students requested information about programming in FORTRAN.  This is due in large part to FORTRAN's extensive use in the Atmospheric and Oceanic Science Department, at several National Laboratories, and in many engineering Graduate Study programs.  While you won't be able write much FORTRAN code after only one week on this very powerful and flexible language, we do hope to give you the basic idea of command line program development and enough exposure to a different programming language syntax to help you make use of existing tutorials for any language you may desire to learn.

You will be learning about FORTRAN in the context of identifying the high temperature for each day of water temperatures in a local stream. In this team lab you will edit, compile, and run a FORTRAN program that processes a data file with 93 rows and 24 columns of data per row.  The data file has one row for each day of a monitoring season and one column for each hour of that day.  The value at that row and column is the water temperature on that day at that hour.  We wish to find the high temp for each day of the season.

PROBLEMS

Problem 0: Connect remotely to a CAE Unix/Linux workstation.

The Windows machines in CAE do not have an available FORTRAN compiler.  A compiler is a program that translates source code to an executable file.  We will connect remotely to one of the CAE tux machines.  The tux machines are running linux, an open source version of UNIX.  We can connect to tux machines right from our Windows computer by using a utility program called Secure Shell CRT.  There are other such programs, but this one is available for free to students and staff from the DoIT Shelf.

  1. Launch the Secure Shell terminal emulator from the Start Menu:
    Start -> All Programs -> Internet ->SecureCRT
  2. Click [No] to check for updates dialog.
  3. If Connect dialog appears, close it.
  4. Click [Quick Connect] to open a remote connection dialog box.
  5. Type best-tux.cae.wisc.edu in the Hostname field.
  6. Type your CAE login name in the User Name field.
  7. Click [Connect].
  8. Click [Accept & Save] to accept the new certificate and save the new host key.
  9. Type your CAE account password and click [OK].
  10. Type mkdir fortran and type the Enter key to create a new FORTRAN directory (folder) on your U: drive.
  11. Type cd fortran and type the Enter key to change to your new directory for today's team lab work.

Problem 1: EDIT: Create a FORTRAN source code file.

FORTRAN is a very structured language.  It matters where you start each command line and how many characters are on the line.  The maximum number of characters on each program line is 72 and the first letter of the command must be the 7th character in the line. FORTRAN source code is typed as text characters in a text only file with the file extension of .f.  There are many Windows and UNIX file editors that can create text-only files.  We will use a commonly available editor that most beginning UNIX users find easy to use, if not as powerful or flexible as vi or emacs.

  1. Type pico myProgram.f  and press [Enter] to open an editing buffer.
  2. Use your mouse to highlight all of the following program lines.
    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
    c myProgram is a simple data processing program written in FORTRAN.
    c Written by: <your names here>
    c23456789012345678901234567890123456789012345678901234567890123456789012
          PROGRAM myProgram
          WRITE(*,*) 'Hello FORTRAN Programmers!'
          END
    
  3. Right-click inside the highlighted text and select Copy.
  4. Click the SecureCRT application tab to get back to the tux terminal window.
  5. Right-click inside the blank area to place a copy of the code lines in to the pico buffer.  Select paste from the menu if right-click did not automatically paste the code. Be sure that the lines look just like those above with each code line starting in the seventh column of its line.
  6. Replace <your names here> with your names in the file header (c Written by: )
  7. Type [Ctrl-x] to save the file.
  8. Type Y to say Yes to saving the modified buffer.
  9. Leave or type the filename myProgram.f and press [Enter] to save the file.
  10. Type the UNIX command ls and press [Enter] to see a listing of the files in your current directory.  There should be only one file, the file you just edited.

Problem 2: COMPILE: Translate and build an executable file.

FORTRAN source code can not be executed directly.  It must  be compiled or translated into a form that the machine can execute. The standard installation of the UNIX operating system comes with a program that can perform this translation.  The next step is to compile your source code and link it to create an executable program.  When the source code exists in a single file, this is done easily with one command.

  1. Type the command gfortran myProgram.f to compile and create an executable file named a.out.
  2. Type ls to see the current list of files.  There should now be two files, the file you just edited and a new executable file named a.out.
  3. Type the command gfortran -o myProgram myProgram.f to compile and create a new executable file named myProgram.
  4. Type ls to see the current list of files.  There should now be three files, the myProgram.f source code file, the executable a.out file, and a new executable file named myProgram. The asterisk (*) indicates the file is an executable file.

Problem 3: RUN: Execute the program(s) you just wrote.

Now, that the program executable has been built (twice in fact), we can run it like other programs in UNIX.

  1. Type the command ./a.out and press [Enter] to run your program.  The period slash tells the operating system to look in the current directory for this executable instead of in the standard application directory path.  You should see the message Hello FORTRAN Programmers!
  2. Type the command ./myProgram to try the second program you built from that source code file and press [Enter] to run your program.  You should see the message Hello FORTRAN Programmers!.

Problem 4: Add do loop

The counting do loop in FORTRAN 90/95 is actually similar to the for loop in MATLAB.  It iterates through values from start to last repeating the code between the line that starts the loop and the line indicated by the end do. The indentation is optional.

  1. Open a new pico window and type or copy the following fortran code into a file named myLoopProgram.f.

    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
    c process the temp data and convert to F
    c Written by: <your names here>
    c2345678901234567890123456789012345678901234567890123456789012345678901234567890
          program myLoopProgram
          real f, c
          do i=0,12
            c = i*10.0
            f = c*9/5+32
            write(*,*) i, ') ', f, 'F = ',     c, 'C'
          end do
          end
    
  2. Save the file as myLoopProgram.f.
  3. Make a guess about what will happen when the program is run.
  4. Compile and run the fortran program to see if you were right.
    1. Compile the source code and create an executable:
      tux-7:~/fortran% gfortran -o myLoopProgram myLoopProgram.f
    2. Run the executable:
      tux-7:~/fortran% ./myLoopProgram
  5. Display a listing of all files in the current directory.
    tux-7:~/fortran% ls

This code declares two real variables and executes a simple conversion inside of a loop through the values 0 to 12. 

FORTRAN style guides recommend using the letters i through n to start the name of an integer value.  Variables that store non-integer values should start with other letters.  Following this, and other conventions, makes it easier for you and other programmers to know if a variable stores integers or floating point values.

The counting do loop will execute the body of the loop for each value of i from 0 to 12. The end do line indicates the end of the counting do loop in Fortran 90/95.

Problem 5: Command line MATLAB

It is also possible to edit and run MATLAB programs from the command line. Try the same program in MATLAB on Linux/UNIX.

  1. Open a new pico window and type or copy the following MATLAB code into a file and name it myLoopProgram.m.

    %% myLoopProgram.m will process the temp data and convert to F using MATLAB
    % Written by: <your names here>
    for i = 0:12
        c = i*10.0;
        f = c*9/5+32;
        disp([num2str(i), ') ', num2str(f), 'F = ', num2str(c), 'C']);
    end
  2. Save the file as myLoopProgram.m.

  3. Launch MATLAB and run your myLoopProgram.m program.
    tux-7:~/fortran% matlab -r myLoopProgram

  4. Notice that the command line prompt changed to a MATLAB prompt after your program executes. This indicates that you are still "in" MATLAB and can execute other MATLAB commands. Try computing the area under the curve f(x)=x3-3x+1 between 1 and 2
    >> area = quad('x.^3-3*x+1',1,2)

  5. Some UNIX commands also work in MATLAB. Type pwd to see the current working directory name and then type ls to display a listing of all files in the current directory.
    >> pwd
    >> ls

This MATLAB code creates and assigned to two variables and executes a simple conversion inside of a loop through the values 0 to 12. 

To exit MATLAB and return to the linux command line:

>> exit

Problem 6: Basic Control structures in ForTran

Notice the form of the if statement, as it is very similar to the if statement in MATLAB.  FORTRAN also has an elseif  keyword, like MATLAB. 

c234567 An if statement
      if (data(j,k) < 0) then
          write(*,*) 'The stream must be frozen'
      else
        if (data(j,k)   > high(j)) then
          high(j) = data(j,k)
        end if
      end if

This loop is a counting do loop.  It functions similar to a for loop in MATLAB.  You can read this loop as Repeat the body of the loop for each value of k from 2 to 24 in 1 unit increments.  The body of the loop includes the statements after the "do" line up until the line labeled 30 (in this case).  After the loop has competed 23 times, then, continue with the line labeled 30.

C234567 A do loop
      do k = 2,24
        if (data(j,k)   > high(j)) then
          high(j) = data(j,k)
        end if
      end do

Editor Tips for pico:

  1. Ctrl-k is used to "kut" (cut) a line.
  2. Ctrl-u is used to "unkut" (paste) a line.
  3. Ctrl-o is used to "overwrite" (save) a file without exiting the editor.

In Linux/UNIX, to remove unnecessary files, type:

rm filename

You may remove any files you no longer need (including core files). Core files may be created when your program crashes. For our purposes, core files can safely be deleted. Maybe some day you'll learn how to read core files, but don't hold your breath. There are usally easier ways to debug your code than to wade through core dumps.

Problem 7: Data File Processing

FORTRAN can process all types of files, but we will be processing a text-only data file.  The file does not have to be in the same directory as your program, but it will make the command to open the file shorter if it is in the same folder.  So, we ask you to follow these instructions to copy this token_creek.dat file to your fortran directory.

  1. Copy the token_creek.dat file to your fortran directory.
    cp ~deppeler/Public/fortran/data/token_creek.dat .

    If the copy command does not work, right-click the filename link above and save it from windows to your fortran directory.

  2. Open the data file to see the data format.
    pico token_creek.dat

  3. Type [Ctrl-x] and exit without saving any changes to this data file.
  4. Type the command pico myDataProgram.f to create a new FORTRAN source file.
  5. Type or copy and paste this FORTRAN code. 
    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
    c process a data file and report daily high temp
    c Written by: <your names here>
    c2345678901234567890123456789012345678901234567890123456789012345678901234567890
          program myDataProgram
          integer i, j, k
          real f, c, data(93,24), high(93)
          open(UNIT=10, FILE='token_creek.dat')
          do j = 1,93
            read(10,*) (data(j,k), k=1,24)
            high(j) = data(j,1)
            do k = 2,24
              if (data(j,k) > high(j)) then
                high(j) = data(j,k)
              endif
            end do
            write(*,*) 'Day ',j,' ',high(j)*9/5+32
          end do
          close(10)
          end
    
  6. Compile the source code and create an executable.
  7. Run the executable.

This code declares three integer variables, two single precision floating point values, and two 2D arrays of real values.  The first 2D array has 93 rows and 24 columns and will store data values and the second array is a single dimension array of 93 floating point values. 

What does the code after the declarations do?

The file is opened, then a do loop processes each line in the file.  The read statement gets all values from one line.  The inner do loop finds the high or max value of the values just read.  The write line displays the high temp for the current day.  The file is closed after all rows have been processed.

ADDITIONAL PROBLEMS or FURTHER READING

Problem 8: Write a program that asks a user for an H20 temperature in Fahrenheit and then returns the corresponding temperature in Celsius and displays a message that states if the H20 is a solid, liquid, or gas.

To read in a value from the user:

  1. Declare a variable of the correct type to hold the value.  Declarations must all occur at the start of the program, after the program line. 
  2. Read values into variables. The read statement is used to get values from the user or from a file.  Use read(*,*) to read from standard input (keyboard) while the program is running.

    If you want to get data from a file, open the file with a unit number and use that unit number in the read statement.  The last read statement shown here, works to read 24 of the same type of value from one line of the file opened and assigned to unit=10.

    c Read one value from standard input (keyboard)
    read(*,*) c

    c Read 24 values from one line of a file opened
    c with UNIT=10
    read(10,*) (data(j,k), k=1,24)

    c Read 24 values of the type described by the
    c format statement at label 100 into file unit=10
    read(10,100) (data(j,k), k=1,24)

    c 24 values that are floating point with
    c 6 characters total and 2 chars to right of decimal 100   format (24(F6.2))