+ All Categories
Home > Documents > Introduction-to-programming-using-Fortran-95.pdf

Introduction-to-programming-using-Fortran-95.pdf

Date post: 02-Jun-2018
Category:
Upload: lisused
View: 216 times
Download: 0 times
Share this document with a friend

of 179

Transcript
  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    1/179

    Introduction to

    Programmingusing

    Fortran 95

    Ed Jorgensen

    June, 2013

    Version 1.5

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    2/179

    Cover Diagram

    The cover image is the plotted output from the chaos gameprogram from chapter 11. Theimage was plotted with !"plot.

    Copyright

    Ed Jorgensen 2013

    #ou are free$ to %hare & to cop', distri(ute and transmit the wor)

    to *emi+ & to adapt the wor)

    "nder the following conditions$ ttri(ution. #ou must attri(ute the wor) to -ntroduction to /rogramming using ortran

    5 (ut not in an' wa' that suggests that the authors endorse 'ou or 'our use of the

    wor)4. %hare li)e. f 'ou alter, transform, or (uild upon this wor), 'ou ma' distri(ute the

    resulting wor) onl' under the same, similar or a compati(le license.or an' reuse or distri(ution, 'ou must ma)e clear to others the license terms of this wor). The

    (est wa' to do this is with a lin) to http$creativecommons.orglicenses('6sa3.0

    n' of the a(ove conditions can (e waived if 'ou get permission from the cop'right holder.

    !othing in this license impairs or restricts the author7s moral rights.

    ii

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    3/179

    Table of Contents

    1 Introduction....................................................................................................................................... 1

    1.1 8h' 9earn /rogramming............................................................................................................ 1

    1.2 ortran......................................................................................................................................... 1

    1.3 :omplete ortran 5 ;ocumentation.......................................................................................... 11.< 8hat s /rogram...................................................................................................................... 2

    1.5 =perating %'stem........................................................................................................................ 2

    2 Computer Organization.................................................................................................................... 3

    2.1 rchitecture =verview................................................................................................................ 3

    2.2 :ompiler...................................................................................................................................... movies.

    1. Fortran

    ortran is a programming language often used (' the scientific communit'. ts name is a contraction of

    =*mula T*!slation. =*T*! is one of the earliest programming languages.

    This te+t utili@es the ortran 05 standard. =lder versions of ortran, li)e ortran BB, are notreferenced. The older ortran versions have less features and reAuire additional, often (urdensome

    formatting reAuirements.

    1.! Com"lete Fortran 95 #ocumentation

    This te+t it is not a comprehensive or complete reference to the ortran 5 language. The entire !"

    ortran compiler documentation is availa(le on6line at the following location$

    http://gcc.gnu.org/onlinedocs/gcc-4.5.0/gfortran/

    f this location changes, a we( search will (e a(le to find the new location.

    1

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    12/179

    :hapter 1 K ntroduction

    1.$ What Is % Program

    computer programis a series of instructions which ena(les the computer to perform a designated

    tas). s this te+t will demonstrate, a computer must (e told what to do in precise, step6('6step detail.These steps might include o(taining data, arithmetic operations additional, su(traction, multiplication,

    division, etc.4, data storage, and information output. The computer will perform these tas)s as

    instructed, even if the' don7t alwa's ma)e sense. :onseAuentl', it is the programmer who mustdevelop a solution to the pro(lem.

    1.5 &"erating 'ystem

    The =perating %'stem, or =%, is an interface (etween the user and the hardware :/", memor',screen, dis) drive, etc.4. The =% is responsi(le for the management of the hardware, coordination of

    activities and the sharing of the resources of the computer that acts as a host for computing applications

    run on the machine. The common operating s'stems include various versions of 8indows. I: =%

    , and "!9inu+. /rograms written in ortran will wor) on these operating s'stems.

    2

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    13/179

    Com"uter &rgani(ation

    >efore writing programs, it is useful to understand some (asics a(out how a computer is organi@ed.

    This section provides a (rief, high6level overview of the (asic components of a computer and how it is

    organi@ed.

    .1 %rchitecture &)er)ie*

    The (asic components of a computer include a :entral /rocessing "nit :/"4, *andom ccess

    Iemor' *I4, ;is) ;rive, and nput=utput devices i.e., screen and )e'(oard4, and aninterconnection referred to as >"%.

    ver' (asic diagram of a computer architecture is as follows$

    /rograms and data are t'picall' stored on the dis) drive. 8hen a program is e+ecuted, it must (e

    copied from the dis) drive into the *I memor'. The :/" e+ecutes the program from *I. This issimilar to storing a term paper on the dis) drive, and when writingediting the term paper, it is copied

    from the dis) drive into memor'. 8hen done, the updated version is stored (ac) to the dis) drive.

    3

    Illustration 1: Computer Architecture

    Screen / Keyboard /

    Mouse

    Disk Drive /

    Other Storage Media

    Random Access

    Memory (RAM)CP

    !S

    ("nterconnection)

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    14/179

    :hapter 2 K :omputer =rgani@ation

    . Com"iler

    /rograms are written in the ortran programming language. However, the :/" does not read ortran

    directl'. nstead, the ortran program that we create will (e converted into (inar' 17s and 07s4 (' thecompiler. The :/" will read the instructions and information, represented in (inar', and perform the

    commands from the program.

    The compiler is a program itself and is reAuired in order to create the files needed to e+ecute programs

    written in ortran 5.

    .! Information +e"resentation

    ll information, including num(ers, characters, and instructions are represented in the computer in

    (inar' 17s and 07s4. The information is converted into (inar' representation 17s and 07s4 for storage in

    the computer. ortunatel', this is generall' done transparentl'.

    2.3.1 Decimal Numbers

    >efore discussing (inar' num(ers, a (rief review of the decimal s'stem is presented. The num(erL123

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    15/179

    :hapter 2 M :omputer =rgani@ation

    2.3.2 Binary Numbers

    The (inar' s'stem, as well as its math, operates in base 2, using two s'm(ols, 0 and 1.

    2B 2 25 2< 23 22 21 20

    12C < 32 1 C < 2 1

    0 0 0 0 1 1 0 1

    n (ase 2, we put the digits 061 in columns 20, 21, 23, and so on. or e+ample,

    11012 = 123 12

    2 02

    1 12

    0= Celow are some Aui@ Auestions (ased on this chapter.

    2.4.1 Quiz Questions

    >elow are some Aui@ Auestions.

    14 How is information represented in the computerN

    24 8hat does the ortran compilerdoN

    34 8hat architecture component connects the memor' to the :/"N

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    16/179

    :hapter 2 K :omputer =rgani@ation

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    17/179

    ! -etting 'tarted

    This section provides a (rief overview of how to get started. This includes the general process for

    creating a ver' simple program, compiling, and e+ecuting the program. %ome detailed steps regarding

    wor)ing with files, o(taining the compiler, and compiling a program are included inAppendix B!indo"s #tart$up Instructions.

    !.1 +euired '/ills

    >efore starting, 'ou should have some (asic computer s)ills, including the following$

    (ilit' to use a we( (rowser

    >asic understanding of computer director' structure ile manipulation create, delete, rename, move, etc.4 (ilit' to edit a te+t file

    ncludes selecting and learning a te+t editor i.e., !otepad, !otepadOO, emacs, etc.4

    f 'ou are unsure a(out an' or all of these reAuirements 'ou will need to learn them. ortunatel', the'

    are not difficult. dditionall', there are numerous tutorials availa(le on the 8e(.

    The following sections assume the the ortran 5 compiler is installed and availa(le. or additional

    information regarding o(taining and installing the compiler, refer to ppendi+ >. The ortran 5

    compiler is availa(le for download at no cost.

    !. Program Formats

    ortran 5 programs must (e written and formatted in a specific manner. The following sections

    summari@e the (asic program elements followed (' a simple e+ample.

    3.2.1 Program tatement

    ortran 5 program is started with a program statement, 7program 7, and ended with an end

    program statement, 7end program 7. *efer to the e+ample first program to see an e+ample of

    these statements.

    3.2.2 Comments

    :omments are information for the programmer and are not read (' the computer. or e+ample,

    comments t'picall' include information a(out the program. or programming assignments, the

    comments should include the programmer name, assignment num(er, and a (rief description of theprogram.

    B

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    18/179

    :hapter 3 K etting %tarted

    3.2.3 imple !utput

    program can displa' a simple message to the screen (' using the "ritestatement. or e+ample$

    write(*,*) "Hello World"

    8ill displa' the message Hello World to the screen. dditional information regarding the write

    statement and outputting information is provided in later chapters.

    3.2.4 "#ample $ %irst Program

    The following trivial program illustrates the initial formatting reAuirements.

    ! Simple Example Programprogram first

    write (*,*) "Hello World"

    end program first

    n this e+ample, the program is named 7first7. This file is t'picall' referred to as thesourcefile.

    !.! Text ,ditor

    The first step is to create a te+t file named hw.f95 using a te+t editor. t is useful to place programsand various files into a wor)ing director'. This wa' the files can (e easil' found and not confused with

    other, unrelated files and data. The hw.f95 file should (e created and placed in the wor)ingdirector'.

    file name is t'picall' comprised of two partsP a name and an e+tension. n this e+ample, the name ishw and the e+tension is .f95. The usual e+tension for this a future programs will (e .f95whichindicates that the file is a ortran 5 source file.

    The following e+amples will use the hw.f95 file name. f desired, a different file name ma' (eused. However, the name will need to (e adFusted for the compiler and e+ecute steps.

    !.$ Com"iling

    =nce the program is t'ped into a file, the file must (e compiled. :ompiling will convert the human

    reada(le ortran program, or source file, into a computer reada(le version in (inar'4.

    n the e+amples (elow, the commands t'ped (' the user are displa'ed in (old. The regular non6

    (olded4 te+t refers to prompts or other information displa'ed (' the computer which will not need to(e t'ped4.

    To compile the e+ample program, the following command would (e entered$

    K:\mydir>gfortran -o hw hw.f95

    This command will tell the 7gfortran7 compiler to read the file hw.f95and, if there are no errors,

    C

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    19/179

    :hapter 3 M etting %tarted

    create an e+ecuta(le file named hw.exe. f there is an error, the compiler will generate an errormessage, sometimes cr'ptic, and provide a line num(er. %uch errors are usuall' the result of mist'ping

    one of the instructions. n' errors must (e resolve (efore continuing.

    !.5 ,xecuting

    To e+ecute or run a program, t'pe the name of the e+ecuta(le file. or e+ample, to e+ecute or run the

    hw.exeprogram$

    K:\mydir>hwHello World

    K:\mydir>

    8hich will e+ecute the e+ample program and displa' the -Hello 8orld message to the screen. more

    complete e+ample is as follows$

    t is not necessar' to t'pe the e+tension i.e., -.e+e4 portion of the file name.

    !.0 ,xercises

    >elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.

    3.&.1 Quiz Questions

    >elow are some Aui@ Auestions.

    14 8hat the the input file for the compilerN

    24 8hat is the output file from the compilerN

    34 ortran program must start with and end with what statementN

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    20/179

    :hapter 3 K etting %tarted

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    21/179

    $ Fortran 95 2asic ,lements

    >efore (eginning to writing programs, it is necessar' to )now some of the (asic elements of the

    ortran language. This section descri(es some of the (asic elements of ortran. dditionalinformation will (e added in later sections.

    $.1 3ariables

    The (asic concept in a program is the concept of a varia(le. Varia(les in a program are li)e varia(les inan alge(raic e+pression. The' are used to hold values and then write mathematical e+pressions using

    them. ortran allows us to have varia(les of different t'pes.

    varia(le can hold one value at a time. f another value is placed in the varia(le, the previous value is

    over6written and lost.

    Varia(le !ame Q

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    22/179

    :hapter < K ortran 5 D >asic Elements

    4.1.2 *ey+or's

    n programming, a )e'word is a word or identifier that has a special ortran meaning. or e+ample, in

    the -hello world program from the previous chapter, the wordprogramhad a special meaning in that itused to note the start or (eginning of a program. dditionall', the word "ritehas a special meaning to

    note an output action e.g., writing some information to an output device, li)e the screen4.

    %uch )e'words are reserved in that the' can not (e used for an'thing else such varia(le names. That is,

    a varia(le name of program or write is not allowed.

    s additional ortran 5 statements and language constructs are e+plained, more )e'words willidentified. n general, words used for ortran language statements, attri(utes, and constructs will li)el'

    (e )e'words. complete list of )e'words or reserved words is located in ppendi+ .

    $. #ata Ty"es

    ortran, li)e man' other high level programming languages, supports several different data t%pesto

    ma)e data manipulation easier. The most freAuentl' used data t'pes are integer and floating point.

    =ther data t'pes are comple+ num(ers, characters and logical data.

    n a ortran statement, data can appear either as a literal e.g., an actual value such as 3.1

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    23/179

    :hapter < M ortran 5 D >asic Elements

    4.2.2 Real

    real num(er2includes the fractional part, even if the fractional part is 0. *eal num(ers, also referred

    to as floating point num(ers, include (oth rational num(ers and irrational num(ers. E+amples of

    irrational num(ers or repeating decimals include , 2 and e. dditional e+amples include 1.5, 5.0,and 3.1

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    24/179

    :hapter < K ortran 5 D >asic Elements

    4.3.1 Declaring )ariables

    ;eclaring varia(les formall' defines the data t'pe of each varia(le and sets aside a memor' location.

    This is performed (' a t'pe declaration statement in the form of$

    ::

    The t'pe must (e one of the predefined data t'pes integer, real, comple+, character, logical4. =utlined

    in the previous section. ;eclarations are placed in the (eginning of the program after the programstatement4.

    or e+ample, to define an integer varia(le toda%,

    integer :: today

    dditional e+amples include$

    integer :: today, tomorrow, yesterdayreal :: ans2

    complex :: zlogical :: answer

    The declarations can (e entered in an' order.

    dditional information regarding character varia(les is provided in a later chapter.

    4.3.2 ,nitialization

    t is possi(le to declare a varia(le and to set it is initial value at the same time. This initiali@ation is not

    reAuired, (ut can sometime (e convenient. or e+ample, to define an integer varia(le toda%sdateand

    set it to the 15thof the month$

    integer :: todaysdate=15

    dditional e+amples include$

    integer :: todaysday=15, tomorrow=16, yesterday=14real :: ave = 5.5

    %paces or no spaces (etween the varia(les, eAual signs, semicolons, and commas are allowed.

    Varia(les initiali@ed at declaration can (e changed later in the program as needed.

    4.3.3 Constants

    constantis a varia(le that can not (e changed during program e+ecution. or e+ample, a programmight declare a varia(le for ;and set it to 3.1

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    25/179

    :hapter < M ortran 5 D >asic Elements

    or e+ample, the declarations$

    real, parameter :: pi = 3.14159integer, parameter :: width = 1280

    will set the varia(lepito 3.1

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    26/179

    :hapter < K ortran 5 D >asic Elements

    $.0 ,xercises

    >elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.

    4.&.1 Quiz Questions

    >elow are some Aui@ Auestions.

    14 8hat are the five ortran 5 data t'pesN

    24 8hat should a ortran varia(le name start withN

    34 8hat data t'pe are each of the following num(ers integer or real4N

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    27/179

    5 ,x"ressions

    This section descri(es how to form (asic ortran 5 e+pressions and perform arithmetic operations

    i.e., add, su(tract, multiple, divide, etc.4. E+pressions are formed using literals actual values4,

    varia(les, and operators i.e.,

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    28/179

    :hapter 5 K E+pressions

    The following are some real constants using e6notation$

    2.75E63.3333E-1

    Hence, 2.B5E5 is 2.B5105 or 2B5,000 and 3.333E61 is 3.333101 or 0.3333 or appro+imatel'

    one third.

    -.1.3 Comple# iterals

    complexconstantis designated (' a pair of constants integer or real4, separated (' a comma and

    enclosed in parentheses. E+amples are$

    (3.2, -4.1)(1.0, 9.9E-1)

    The first num(er denotes the real part and the second the imaginar' part. 8hile a comple+ num(er

    consits of two elements it is considered a single value.

    -.1.4 Character iterals

    characterconstantis either a single character or a set of characters, called a string. character is a

    single character enclosed in Auotes. string consists of an ar(itrar' seAuence of characters also

    enclosed in Auotes. %ome e+amples include$

    "X""Hello World""Good bye cruel world!""Have a nice day"

    :haracter and string constants enclosed with Auotes4 are case sensitive. %o, character - upper6

    case4 is not the same as -+ lower6case4.

    pro(lem arises if 'ou want to have a Auote in the string itself. dou(le Auote will (e interpreted as a

    single within a string.

    "He said ""wow"" when he heard"

    The dou(le6Auoting is sometimes referred to as an escape character. %trings and characters must (eassociated with the character data t'pe.

    -.1.- ogical Constants

    The fifth t'pe is logicalconstant. These can onl' have one of two values$.true..false.

    The dots enclosing the true and false are reAuired.

    1C

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    29/179

    :hapter 5 M E+pressions

    5. %rithmetic &"erations

    This section summari@es the (asic arithmetic operations.

    -.2.1 ssignment

    ssignment is term for setting a varia(le eAual to some value. ssignment is performed with a eAual>4 sign. The general form is$

    variable = expression

    The e+pression ma' (e a literal, varia(le, an arithmetic formula, or com(ination of each. =nl' oneassignment to a single varia(le can (e made per line.

    or e+ample, to declare the varia(le ans"er1as a real value,

    real :: answer1

    and set it eAual to 2.B1C2C1C3,

    answer1 = 2.71828183

    The value for ans"er1can (e changed as often as needed. However, it can onl' hold one value at a

    time.

    -.2.2 ''ition

    The ortran addition operation is specified with a plus sign O4. or e+ample, to declare the varia(les,

    sum, number1, number2, and number&,

    integer :: sum, number1=4, number2=5, number3=3

    and calculate the sum,sum = number1 + number2

    which will set the varia(le sum to in this e+ample. The data t'pes of the varia(les, integer in thise+ample, should (e the same. Iultiple varia(les can (e added on one line. The line can also include

    literal values. or e+ample,

    sum = number1 + number2 + number3 + 2

    which will set the varia(lesumvaria(le to 1

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    30/179

    :hapter 5 K E+pressions

    should (e the same. Iultiple varia(les can (e su(tracted on one line. The line can also include literal

    values. or e+ample,

    ans = value1 - value2 value3

    which will set the varia(le ansvaria(le to 1.0. dditionall', it will over6write the previous value of 2.0.

    -.2.4 ultiplication

    The ortran multiplication operation is specified with an asteris) Y4. or e+ample, to declare thevaria(les, ans, 'alue1, 'alue2, and 'alue&,

    real :: ans, value1=4.5, value2=2.0, value3=1.5

    and calculate the product,

    ans = value1 * value2

    which will set the varia(le ansto .0. The data t'pes of the varia(les, real in this e+ample, should (e

    the same. Iultiple varia(les can (e multiplied on one line. The line can also include literal values.or e+ample,

    ans = value1 * value2 * 2.0 * value3

    which will set the varia(lesumto 2B.0. dditionall', it will over6write the previous value of .0.

    -.2.- Diision

    The ortran division operation is specified with a slash s'm(ol 4. or e+ample, to declare thevaria(les, ans, 'alue1, 'alue2, and 'alue&,

    real :: ans, value1=10.0, value2=2.5, value3=2.0

    and calculate the Auotient,

    ans = value1 / value2

    which will set the varia(le ansto

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    31/179

    :hapter 5 M E+pressions

    and calculate the e+ponentiation,

    ans = value1 ** 3

    which will set the varia(le ansto C.0. The data t'pes of the varia(les, real in this e+ample, should (ethe same.

    5.! Precedence of &"erations

    ortran follows the standard mathematical precedence of operations. That is multiplication anddivision are performed (efore addition and su(traction. urther, in accordance with mathematical

    standards, the e+ponentiation operation is performed (efore multiplication and division.

    The following ta(le provides a partial summar' of the (asic ortran 5 precedence levels$

    )recedence

    +eve&

    Operator Operation

    1st unar' 6

    2nd == e+ponentiation

    3rd = - multiplication and division

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    32/179

    :hapter 5 K E+pressions

    or e+ample, the cosine of ;is 61. n ortran, to declare the varia(lesxandpi,

    real :: zreal, parameter :: pi = 3.14159

    and then calculate the cosine of the varia(lepi,

    z = cos(pi)

    which will setzto 61.0. The varia(lepiis the input argument and the result returned is assigned to the

    varia(lez.

    -.4.2 Conersion %unctions

    =ther intrinsic functions include functions to change the t'pe of varia(les or values. The (asic

    conversion functions are as follows$

    Function %'p&anation

    realZinteger argument[4 :onvert the Zinteger argument[ to a realvalue

    intZreal argument[4 :onvert the Zreal argument[ to an integer,

    truncates the fractional portion

    nintZreal argument[4 :onvert the Zreal argument[ to an integer,

    rounds the fractional portion

    or e+ample, given the following varia(le declarations,

    integer :: inum1=10, inum2, inum3real :: rnum1, rnum2 = 4.8

    and calculate the ans1and ans2,

    rnum1 = real(inum1)inum2 = int(rnum2)inum3 = int(rnum3)

    which will set to rnum1to 10.0, inum2to

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    33/179

    :hapter 5 M E+pressions

    !!T4 *eturns the nearest integer to real value thus rounding

    up or down as appropriate4.

    *E94 :onverts integer argument to real.

    %!84 *eturns real sine of real argument 8 in radians.

    %?*T84 *eturns the real sAuare root of real argument 8P 8 must (epositive.

    T!4 *eturns the real tangent of real argument in radians.

    more complete list of intrinsic functions in located in ppendi+ >.

    5.5 4ixed 4ode

    n general, mathematical operations should (e performed on varia(les of the same t'pe. 8hen (oth

    integer and real values or varia(les are used in the same statement, it is called mi+ed mode.

    *eal and integer operations$

    1/2 = 01.0 + 1/4 = 1.01.0 + 1.0/4 = 1.25

    when mi+6mode is encountered, integer is converted to real onl' when mi+ed6mode is encountered onthe same operation t'pe. :onversion ma' also occur on assignment.

    "ne+pected conversions can cause pro(lems when calculating values. n order to avoid such pro(lems,

    it is strongl' recommended to not use mi+6mode. There are a series of rules associated with mi+ed6

    mode operations. or simplicit', those rules are not covered in here.

    f it is necessar' to perform calculations with different data t'pes, li)e integers and reals, the

    conversion functions should (e used correct and predicta(le results.

    5.0 ,xam"les

    >elow is an e+ample program that calculates velocit' (ased on acceleration and time. The programdeclares the appropriate varia(les and calculate the velocit'.

    program velocity! Program to calculate the velocity from the! acceleration and time

    ! Declare variablesimplicit nonereal :: velocity, acceleration = 128.0real :: time = 8.0

    ! Display initial headerwrite (*,*) "Velocity Calculation Program"write (*,*)

    23

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    34/179

    :hapter 5 K E+pressions

    ! Calculate the velocityvelocity = acceleration * time

    write (*,*) "Velocity = ", velocity

    end program velocity

    dditional information regarding how to perform input and output in the ne+t chapter. The commentsare not reAuired, (ut help ma)e the program easier to read and understand.

    5. ,xercises

    >elow are some Aui@ Auestions and proFect suggestion (ased on this chapter.

    -.5.1 Quiz Questions

    >elow are some Aui@ Auestions.

    14 8hat is assignmentoperatorN

    24 8hat is the e+ponentiation operatorN

    34 How can an integer varia(le (e converted to a real valueN

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    35/179

    :hapter 5 M E+pressions

    -.5.2 uggeste' Pro(ects

    >elow are some suggested proFects.

    14 T'pe in the velocit' program, compile, and e+ecute the program. :hange the declared values,

    compile, and e+ecute the modified program. Verif' the results of (oth e+ecutions with a

    calculator.

    24 8rite a program to calculate and displa' the difference (etween time as read from a sundial anda cloc). The difference can (e calculated with the -eAuation of time which is$

    b 2(n *1) / 3(4

    e .*7 $in(20) 7.!3 co$(b) 1.! $in(b)

    8here, nis the da' num(er. or e+ample, nU 1 for Januar' 1, nU 2 for Januar' 2, and so on.

    The program should read the value for n163

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    36/179

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    37/179

    0 'im"le In"ut and &ut"ut

    %imple, unstructured, input and output can (e performed with the "riteand readstatements as

    e+plained in the following sections. n a later chapter, a more structured approach will (e presented inlater sections.

    0.1 &ut"ut Write

    s noted from the first program, simple output can (e performed (' using the a "ritestatement. ore+ample$

    write (*,*) "Hello World"

    8hich will send the message, referred to as astring, ?e&&o or&dto the screen. The first -Y meansthe default output device, which is the screen or monitor. The second -Y refers to the 7free format7.Thus, the -(*,*) means to send it to the screen in 7free format7.

    The free format allows the ortran compiler to determine the appropriate format for the information

    (eing displa'ed. This is eas', especiall' when first getting started, (ut does not allow the program

    much control over how the output will (e formatted or displa'ed on the screen.

    dditionall', the value held (' declared varia(les can (e displa'ed. or e+ample, to declare the

    varia(les num1, num2, and num&.

    integer :: num1=20, num2=50, num3=10

    the write statement to displa' num1would (e,write (*,*) num1

    The free format allows the ortran compiler to determine the appropriate output format for the

    information (eing displa'ed.

    write statement with no string or varia(les,

    write (*,*) num1

    8ill displa' a (lan) line.

    Iultiple varia(les and strings can (e displa'ed with one write statement. or e+ample, using the

    previous declarations,write (*,*) "Number 1 = ", num1, "Number 2 = ", num2

    The information inside the Auotes is displa'ed as is, including capitali@ation and an' spelling errors.8hen the Auotes are not used, it is interpreted as a varia(le. f the varia(le is not declared, a compiler

    error will (e generated. The value assigned to each varia(le will (e displa'ed. value must have (e

    assigned to the varia(le prior to attempting to displa'.

    2B

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    38/179

    :hapter K %imple nput and =utput

    &.1.1 !utput $ Print

    n addition to the write statement, a print statement can (e used. The print statement will send output

    onl' to the screen. Thus it is a more restrictive form of the write statement.

    s with the write statement, multiple varia(les and strings can (e displa'ed with one print statement.

    or e+ample, using the previous declarations,print *,"Number 1 = ", num1, "Number 2 = ", num2

    The information inside the Auotes is displa'ed as is, including capitali@ation and an' spelling errors.

    8hen the Auotes are not used, it is interpreted as a varia(le. f the varia(le is not declared, an error will(e generated. f the varia(le is defined, the value assigned to that varia(le will (e displa'ed.

    n general, all e+amples will use the write statement.

    0. In"ut +ead

    To o(tain information from the user, a readstatement is used. or e+ample, to declare the varia(les

    num1, num2,

    integer :: ans1, ans2

    then read a value for ans1from the user,

    read (*,*) ans1

    8hich will read a num(er from the user entered on the )e'(oard into the varia(le ans1. The Y,Y4means to send it to read the information in 7free format7. The free format allows the ortran compiler to

    determine the appropriate format for the information (eing read.

    Iultiple varia(les can (e read with one write statement. or e+ample, using the previous declarations,

    read (*,*) ans1, ans2

    will read two values from the user into the varia(les ans1and ans2.

    %ince the read is using free format, two num(ers will (e reAuired. The num(ers can (e entered on the

    same line with one more more spaces (etween them or on separate lines. The read will wait until two

    num(ers are entered.

    8hen reading information from the user, it is usuall' necessar' to provide a prompt in order to ensurethat the user understands that input is (eing reAuested (' the program. suita(le write statement with

    an appropriate string, followed (' a read statement will ensure that the user is notified that input is

    (eing reAuested.

    or e+ample, to read a date, a program might reAuest month, date, and 'ear as three separate varia(les.iven the following declarations,

    integer :: month, date, year

    the program might prompt for and read the data in the following manner,

    write (*,*) "Enter date (month, date, and year)"read (*,*) month, date, year

    2C

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    39/179

    :hapter M %imple nput and =utput

    %ince the program is reAuesting three integers, three integers must (e entered (efore the program

    continues. The three num(ers ma' (e entered on one line with a single space (etween them, with

    multiple spaces or ta( (etween them, or even on three different lines as in the following e+amples$

    Enter date (month, date, and year)

    10 17 2009

    Enter date (month, date, and year)10172009

    Enter date (month, date, and year)10 17 2009

    The t'pe of num(er reAuested here is an integer, so integers should (e entered. /roviding a real

    num(er or character i.e., letter4 would generate an error. 9ater chapters will address how to deal with

    such errors.

    0.! ,xam"le

    >elow is an e+ample program that calculates the area of a circle. The program will declare the

    appropriate varia(les, read the radius, calculate the circle area, and displa' the result.

    Program circle! Program to calculate the area of a circle

    ! Declare variablesimplicit none

    real :: radius, areareal, parameter :: pi = 3.14159

    ! Display initial header and blank linewrite (*,*) "Circle Area Calculation Program"write (*,*)

    ! Prompt for and read the radiuswrite (*,*) "Enter Circle Radius"read (*,*) radius

    ! Calculate the circle areaarea = pi * radius**2

    ! Display resultwrite (*,*) "Circle Area: ", area

    end program circle

    The comments are not reAuired, (ut help ma)e the program easier to read and understand. f the

    program does not wor) at first, the comments can aid in determining the pro(lem.

    2

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    40/179

    :hapter K %imple nput and =utput

    0.$ ,xercises

    >elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.

    &.4.1 Quiz Questions

    >elow are some Aui@ Auestions.

    14 8hat does the(*,*) meanN

    24 8hat is the statement to output a message -/rogramming is un\

    34 8hat are the statements to declare and read the value for a persons age in 'ears.

    &.4.2 uggeste' Pro(ects

    >elow are some suggested proFects.

    14 T'pe in the circle area program, compile and e+ecute the program. Test the program on severalsets of input.

    24 Iodif' the circle area program to reAuest a circle diameter. The formula for circler area must(e adFusted accordingl'. *ecall that radius U diameter divided (' two. Test the program on

    several sets of input.

    34 T'pe in the velocit' program from the previous chapter and update to prompt for and reAuestinput for the acceleration and time, and then displa' the results. Test the program on several

    sets of input.

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    41/179

    :hapter M %imple nput and =utput

    54 8rite a ortran program compute geometric information for a Gite. The program should read

    the a,candplengths and compute the qlength. The program should

    displa' an appropriate prompt, read the values, compute the answer, anddispla' the original input and the final result.

    *ecall that$

    q (a2

    p2

    4) ( c

    2

    p2

    4)

    Test the program on several sets of input.

    31

    a

    pA

    c

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    42/179

    :hapter K %imple nput and =utput

    32

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    43/179

    Program #e)elo"ment

    8riting or developing programs is easier when following a clear methodolog'. The main steps in the

    methodolog' are$

    "nderstand the /ro(lem :reate the lgorithm

    ;evelop the /rogram Test;e(ug the /rogram

    To help demonstrate this process in detail, these steps will (e applied to a simple pro(lem to calculate

    and displa' the period of a pendulum.

    s additional e+amples are presented in later chapters, the' will (e e+plained and presented using thismethodolog'.

    .1 6nderstand the Problem

    >efore attempting to create a solution, it is important to understand the pro(lem. Ensuring a completeunderstanding of the pro(lem can help reduce errors. The first step is to understand the what is

    reAuired and the applica(le input information. n this e+ample, the formula for the period of a

    pendulum is$

    Period 2

    L

    g

    1+

    1

    4$in

    2

    2

    8here$

    g U C0 cmsec2

    U 3.1othggravit'4 and should (e declared as a constants. The formula is a simplified version of the

    more general case. s such, for ver' large, ver' small, or @ero angle values the formula will not

    provide accurate results. or this e+ample, that is accepta(le.

    s shown, the pendulum is attached to a fi+ed point, and set into motion (' displacing the pendulum(' an angle, , as shown in the diagram. The program must define the constants forgand , declare

    the varia(les, displa' appropriate prompts, read the values forLand then calculate and displa' the

    original input and the period of the pendulum with the given length and angle of displacement.

    33

    9

    ]

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    44/179

    :hapter B K /rogram ;evelopment

    . Create the %lgorithm

    The algorithm is the name for the ordered seAuence of steps involved in solving the pro(lem. =nce the

    program is understood, a series of steps can (e developed to solve that pro(lem. There can (e multiplecorrect solutions to a given pro(lem.

    The process for creating an algorithm can (e different for different people. n general, some timeshould (e devoted to thin)ing a(out a possi(le solution. This ma' involve wor)ing on some possi(le

    solution on a scratch piece of paper. =nce a possi(le solution is selected, that solution can (edeveloped into an algorithm. The algorithm can (e written down, reviewed, and refined. This

    algorithm is the outline of the program.

    or this pro(lem, the varia(les and constants must (e declared, the applica(le headers and prompts

    displa'ed, and the values forLand read from the user. Then the period can (e calculated (ased onthe provided formula and the results displa'ed. ormali@ing this, the following steps can (e developed

    and written down as follows$

    ! declare variables

    ! real constants -> gravity, pi! reals -> angle, length! display initial header! prompt for and read the length and angle values! calculate the period! display the results

    8hile this is a fairl' straightforward algorithm, more comple+ pro(lems would reAuire more e+tensive

    algorithms. E+amples in later chapters will include more comple+ programs. or convenience, the

    steps are written a program comments. This will allow the addition of the code to the (asic algorithm.

    .! #e)elo" the Program>ased on the algorithm, the following program can (e created.

    program period! Program to calculate the period of a pendulum

    ! declare variables! real constants -> gravity, pi! reals -> angle, lengthimplicit nonereal :: angle, length, pperiodreal, parameter :: gravity=980.0, pi=3.14159

    ! display initial headerwrite (*,*) "Pendulum Period Calculation Program"write (*,*)

    ! prompt for and read the length and angle valueswrite (*,*) "Enter Length and Angle values:"read (*,*) length, angle

    3

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    45/179

    :hapter B M /rogram ;evelopment

    ! calculate the periodpperiod = 2.0 * pi * sqrt(length/gravity) * &

    ( 1.0 + 1.0/4.0 * sin(angle/2.0)**2 )

    ! display the resultswrite(*,*) "The period is:", pperiod

    end program period

    The indentation is not reAuired, (ut helps ma)e the program easier to read. !ote that the -2, -1, and

    -

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    46/179

    :hapter B K /rogram ;evelopment

    n this case, the compiler error displa'ed will appear as follows$

    c:\mydir> gfortran -o period period.f95period.f95:13.1:

    wrote (*,*)1Error: Unclassifiable statement at (1)

    The first digit, 13 in this e+ample, represents the line num(er where the error occurred. "sing a te+teditor that displa's line num(ers, the statement that caused the error can (e Auic)l' found and

    corrected.

    f the declaration for the varia(le lengthis omitted, the error would appear as follows$

    c:\mydir> gfortran -o period period.f95period.f95:17.18:

    read (*,*) length, angle 1Error: Symbol 'length' at (1) has no IMPLICIT type

    n this case, the error is shown on line 1C first digit after the -$4. However, the actual error is that thevaria(le length is not declared. Each error should (e reviewed and evaluated.

    5.4.1.2 Runtime "rror

    run6time error is something that causes the program to crash. or e+ample, if the a num(er isreAuested from the user and a letter is entered, that can cause occur.

    or e+ample, the period program e+pects two real num(ers to (e entered. f the user enters letters, +and ', in this e+ample, an error will (e generated during the e+ecution of the program as follows$

    c:\mydir> periodPendulum Period Calculation Program

    Enter Length and Angle values:x y

    At line 17 of file period.f95 (unit = 5, file = 'stdin')Fortran runtime error: Bad real number in item 1 of list input

    The program was e+pecting numeric values and letters were provided. %ince letters are not meaningful

    in this conte+t, it is an error and the program -crashes or stops with an error message.

    9ater chapters will provide additional information on how to deal with such errors. "ntil then, provingthe correct data t'pe will avoid this )ind of error.

    3

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    47/179

    :hapter B M /rogram ;evelopment

    5.4.1.3 ogic "rror

    logic error is when the program e+ecutes, (ut does not produce the correct result. or e+ample,

    coding a provided formula incorrectl' or attempting to computer the average of a series of num(ers

    (efore calculating the sum.

    or e+ample, the correct formula for the period of a pendulum is as follows$pperiod = 2.0 * pi * sqrt(length/gravity) * &

    ( 1.0 + 1.0/4.0 * sin(angle/2.0)**2 )

    f the formula is t'ped incorrectl' or incompletel' as follows$

    pperiod = 2.0 * pi * sqrt(length/gravity) * &( 1.0 + 1/4 * sin(angle/2.0)**2 )

    The 1 over < is entered as -1

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    48/179

    :hapter B K /rogram ;evelopment

    5.-.2 uggeste' Pro(ects

    >elow are some suggested proFects.

    14 T'pe in the pendulum period calculation program, compile, and e+ecute the program. Test the

    program using several different input values.

    24 :reate a program to prompt for and read the circle area from the user and calculate the

    circumference of a circle using the following formula$

    circumference 2

    Circlerea

    Test the program using several different input values.

    34 :reate a program to prompt for and read the radius of a sphere from the user and calculate thesurface area of the sphere using the following formula$

    sphere!urface rea

    4 r2

    Test the program using several different input values.

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    49/179

    8 'election 'tatements

    8hen writing a program, it ma' (e necessar' to ta)e some action (ased on the outcome of comparing

    the values of some varia(les. ll programming languages have some facilit' for decision6ma)ing.That is, doing one thing if some condition is true and optionall'4 doing something else if it is not.

    ortran statements andor :%E statements are used to allow a program ma)es decisions.

    8.1 +elational ,x"ressions

    The first step is to compare two values, often contained in varia(les. The wa' two values are comparedis with relational operators. The varia(les are often referred to as operands. *elational operators are

    used (etween varia(les or operands of similar t'pes. That is real to real, integer to integer, logical to

    logical, and characterstring to characterstring.The (asic relational operators are$

    6e&ationa&

    Operation

    6e&ationa& Operator

    @norma&A

    6e&ationa& Operator

    @a&ternateA

    reater than B .gt.

    reater than or

    eAual

    B> .ge.

    9ess than .&t.

    9ess than or eAual > .&e.

    EAual to >> .e.

    !ot eAual to -> .ne.

    The normal form will (e used for e+amples in this te+t. However, the alternate form ma' (e used at

    an' time. The alternate forms are used to support older ortran programs.

    relational operation is used to form a relational e+pression. The result of a relational e+pression must

    alwa's result in either a trueor(alseresult.

    The ->> two eAual signs4 is used to compare. The -> single eAual4 is used for assignment settinga varia(le4. The ->> does not change an' values, while the -> does.

    or e+ample, given the declaration of,

    integer :: gamelives

    it might (e useful to )now if the current value of gamelivesis greater than 0.

    3

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    50/179

    :hapter C K %election %tatements

    n this case, the relational e+pression would (e,

    (gamelives == 0)

    8hich will result in a trueor(alseresult (ased on the value of -gamelives.

    8. Logical &"erators

    9ogical operators are used (etween two logical varia(les or two logical e+pressions. The' are$

    +ogica& Operator %'p&anation

    .and. the result is true if bothoperands are true

    .or. the result is true if eitheroperand is true

    .not. logical negate if true, ma)es false and if

    false, ma)es true4

    9ogical operators are used to com(ine relational operations as needed.

    or e+ample, given the declaration of,

    integer :: gamelives, extralives

    it might (e useful to )now if the current value of gamelivesis greater than 0. n this case, the

    relational operation would (e,

    ( (gamelives == 0) .and. (extralives == 0) )

    which will result in a trueor(alseresult. %ince the !; logical operation is used, the final result will

    (e trueonl' if (oth logical e+pressions are true.

    nother wa' of chec) the status might (e,

    ( (gamelives > 0) .or. (extralives > 0) )

    which still results in a trueor(alseresult. However, since the orlogical operation is used, the final

    result will (e trueif either logical e+pressions is true.

    The relational operators have higher precedence than logical operators.

    8.! IF 'tatements

    statements are used to perform different computations or actions (ased on the result of a logicale+pression which evaluates to true or false4. There are a series of different forms of the (asic statement. Each of the forms is e+plained in the following sections.

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    51/179

    :hapter C M %election %tatements

    6.3.1 ,% 0/"N tatement

    The statement, using the relational operators, is how programs ma)e decisions. The general format

    for an statement is as follows$

    if ( ) then

    end if

    8here the Zfortran statements[ ma' include one or more valid ortran statements.

    or e+ample, given the declaration of,

    integer :: gamelives

    (ased on the current value of gamelivesis, a reasona(le statement might (e$

    if ( gamelives == 0 ) thenwrite (*,*) "Game Over."write (*,*) "Please try again."

    end if

    8hich will displa' the message -ame =ver if the value of gamelivesis less than or eAual to 0.

    6.3.1.1 ,% 0/"N tatement7 imple %orm

    dditionall', another form of the statement includes

    if ( )

    n this form, a single statement is e+ecuted if the relational e+pression evaluates to true. The previouse+ample might (e written as

    if ( gamelives == 0 ) write (*,*) "Game Over."

    n this form, no -then or -end if are reAuired. However, onl' one statement can (e e+ecuted.

    6.3.2 ,% 0/"N "" tatement

    The THE! E9%E statement e+pands the (asic statement to also allow a series of statements to (e

    performed if the logical e+pression evaluates to(alse.

    The general format for an THE! E9%E statement is as follows$

    if ( ) then

    else

    end if

    8here the Zfortran statements[ ma' include one or more valid ortran statements.

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    52/179

    :hapter C K %election %tatements

    or e+ample, given the declaration of,

    integer :: gamelives

    (ased on the current value of gamelivesis, a reasona(le THE! E9%E statement might (e$

    if ( gamelives > 0 ) thenwrite (*,*) "Still Alive, Keep Going!"

    elsewrite (*,*) "Extra Life Granted."gameslives = 1

    end if

    8hich will displa' the message -%till live, Geep oing if the value of gamelivesis greater than 0

    and displa' the message -E+tra 9ife ranted if the value of gamelivesis less than 0.

    6.3.3 ,% 0/"N "" ,% tatement

    The THE! E9%E statement e+pands the (asic statement to also allow a series of statementsto (e performed in a series.

    The general format for an THE! E9%E statement is as follows$

    if ( ) then

    else if ( ) then

    else

    end if

    8here the Zfortran statements[ ma' include one or more valid ortran statements.

    or e+ample, given the declaration of,

    integer :: gamelives

    (ased on the current value of gamelivesis, a reasona(le THE! E9%E statement might (e$

    if ( gamelives > 0 ) thenwrite (*,*) "Still Alive, Keep Going!"

    else if ( gamelives < 0 )write (*,*) "Sorry, game over."

    else write (*,*) "Extra Life Granted."gameslives = 1

    end if

    8hich will displa' the message -%till live, Geep oing if the value of gamelivesis greater than 0,

    displa' the message -%orr', game over if the value of game lives is Z 0, and displa' the message-E+tra 9ife ranted if the value of gamelivesis eAual to 0.

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    53/179

    :hapter C M %election %tatements

    8.$ ,xam"le &ne

    s previousl' descri(ed, writing or developing programs is easier when following a methodolog'. s

    the program (ecome more comple+, using a clear methodolog' is even more important. The mainsteps in the methodolog' are$

    "nderstand the /ro(lem :reate the lgorithm ;evelop the /rogram Test;e(ug the /rogram

    To help demonstrate this process in detail, these steps will (e applied to a familiar pro(lem as an

    e+ample. The e+ample pro(lem is to calculate the solution of a Auadratic eAuation in the form$

    a x2+ b x+ c ,

    Each of the steps, as applied to this pro(lem will (e reviewed.

    6.4.1 8n'erstan' the Problem

    >efore creating a solution, it is important to understand the pro(lem. Ensuring a complete

    understanding of the pro(lem can help reduce errors.

    t is )nown that the solution to the Auadratic eAuation is as follows$

    xb

    (b24 a c)

    2 a

    n the Auadratic eAuation, the term b2

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    54/179

    :hapter C K %election %tatements

    The relationship (etween the discriminant and the t'pes of solutions two different solutions, one

    repeated solution, or no real solutions4 is summari@ed in the (elow ta(le$

    )o$itive Di$criminant Eero Di$criminant egative Di$criminant

    Two real solutions =ne real solution Two comple+ solutions

    E+ample$

    3+2+3E+ample$

    2+2

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    55/179

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    56/179

    :hapter C K %election %tatements

    ! display complex root1 and root2if ( discriminant < 0 ) then

    root1 = -b / (2.0 * a)root2 = sqrt(abs(discriminant)) / (2.0 * a)

    write(*,*) "This equation has two real roots:"write(*,*) "root 1 = ", root1, "+i", root2

    write(*,*) "root 2 = ", root1, "-i", root2end if

    end program quadratic

    The indentation is not reAuired, (ut does help ma)e the program easier to read.

    6.4.4 0est9Debug the Program

    =nce the program is written, testing should (e performed to ensure that the program wor)s. The

    testing will (e (ased on the specific parameters of the program. n this e+ample, each of the three

    possi(le values for the discriminant should (e tested.

    C:\mydir> quadQuadratic Equation Solver ProgramEnter A, B, and C values2 4 2This equation has one root:root = -1.0000000

    C:\mydir> quadQuadratic Equation Solver Program

    Enter A, B, and C values3 9 3This equation has two real roots:root 1 = -0.38196602root 2 = -2.6180339

    C:\mydir> quadQuadratic Equation Solver ProgramEnter A, B, and C values3 3 3This equation has two real roots:root 1 = -0.50000000 +i 0.86602539root 2 = -0.50000000 -i 0.86602539C:\mydir>

    dditionall', these results can (e verified with a calculator.

    8.5 ',L,CT C%', 'tatement

    %E9E:T :%E statement, often referred to as a :%E statement, is used to compare a given value

    with preselected constants and ta)e an action according to the first constant to match. :%E

    statement can (e hand' to select (etween a series of different possi(ilities or cases.

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    57/179

    :hapter C M %election %tatements

    The select case varia(le or e+pression must (e of t'pe integer, character, or logical. real t'pe is not

    allowed. >ased on the selector, a set of one or more of ortran statements can (e e+ecuted.

    The general format of the %E9E:T :%E statement is$

    select case (variable)

    case (selector-1)

    case (selector-2)...

    case (selector-n) case default end select

    where Zfortran statements461[, Zfortran statements462[, Zfortran statements463[, ..., Zfortran

    statements46n[ and Zfortran statements46default[ are seAuences of one or more e+ecuta(le statements.The selector61, selector62, selector63, ..., and selector6n are called selector lists. Each :%E selector

    list ma' contain a list andor range of integers, character or logical constants, whose values ma' not

    overlap within or (etween selectors. selector6list is either a single or list of values, separated ('commas. Each selector list must (e one of the following forms.

    ( value )( value-1 : value-2 )( value-1 : )( : value-2 )

    where value, value61 and value62 are constants or literals. The t'pe of these constants must (e identical

    to that of the selector.

    The first form has onl' one value

    The second form means all values in the range of value61 and value62 inclusive4. n this form,

    value61 must (e less than value62

    The third form means all values that are greater than or eAual to value61

    The fourth form means all values that are less than or eAual to value62

    n order, each selector e+pression is evaluated. f the varia(le value is the selector or in the selector

    range, then the seAuence of statements in Zfortran statements4[ are e+ecuted.

    f the result is not in an' one of the selectors, there are two possi(ilities$

    if :%E ;E"9T is there, then the seAuence of statements in statements6;E"9T aree+ecuted, followed (' the statement following E!; %E9E:T

    if the :%E ;E"9T is not there, the statement following E!; %E9E:T is e+ecuted

    The constants listed in selectors must (e uniAue. The :%E ;E"9T is optional. >ut with a :%E

    ;E"9T, 'ou are guaranteed that whatever the selector value, one of the la(els will (e used. The

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    58/179

    :hapter C K %election %tatements

    place for :%E ;E"9T can (e an'where within a %E9E:T :%E statementP however, putting it at

    the end would (e more natural.

    or e+ample, given the declarations,

    integer :: hours24, hours12character(2) :: ampm

    the following case statement,

    select case (hours24)case (0)

    hours12 = 12ampm = "am"

    case (1:11)hours12 = hours24ampm = "am"

    case (12)hours12 = hours24

    ampm = "pm"case (1:11)

    hours12 = hours24 - 12ampm = "pm"

    end select

    might (e useful for to convert 2

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    59/179

    :hapter C M %election %tatements

    8.0 ,xam"le T*o

    t'pical pro(lem is to assign grades (ased on a t'pical grading standard.

    6.&.1 8n'erstan' the Problem

    or this e+ample, the program will assign grades using the following grade scale$

    > : ;

    [U0 C0 6 C B0 6 B 0 6 ZU5

    The program will read three test scores, compute the average, and displa' the appropriate grade (asedon the average.

    6.&.2 Create the lgorithm

    The algorithm is the name for the ordered seAuence of steps involved in solving the pro(lem.

    or this pro(lem, the varia(les will (e declared and an initial header displa'ed. Then, the test1, test2,

    and test2values will need to (e read from the user.

    ! declare variables! reals -> test1, test2, test2! integer -> testave! display initial header! read the test1, test2, and test2 values

    !e+t, the average can (e calculated. The average will (e converted to the nearest integer and, (ased onthat, the appropriate grade can (e determined and displa'ed. ormali@ing this, the following steps can

    (e developed.

    ! calculate the testave and convert to integer! determine grade! A - >= 90! B - 80 to 89! C - 70 to 79! D - 60 to 69! F - ased on the algorithm, the following program can (e created.

    program grades

    ! declare variablesimplicit none

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    60/179

    :hapter C K %election %tatements

    real :: test1, test2, test2integer :: testave

    ! display initial headerwrite (*,*) "Grade Assignment Program"write (*,*)

    write (*,*) "Enter test 1, test 2 and test 3 values"

    ! read the test1, test2, and test2 valuesread (*,*) test1, test2, test3

    ! calculate the average and convert to integertestave = nint ((test1 + test2 + test3)/3.0)

    ! determine grade! A >= 90, B 80-89, C 70-79, D 60-69, F gradeGrade Assignment Program

    Enter test 1, test 2 and test 3 values70 80 90Grade is: B

    C:\mydir>

    The program should (e tested with a series of data items to ensure appropriate grade assignment foreach grade. Test values for each grade should (e entered for the testing.

    50

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    61/179

    :hapter C M %election %tatements

    8. ,xercises

    >elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.

    6.5.1 Quiz Questions

    >elow are some Aui@ Auestions.

    14 9ist the si+ relational operatorsN

    24 9ist the three (asic logical operatorsN

    34 or each of the following, answer .true. or .:a&$e. in the space provided.

    boolean :: b1 = .true., b2=.false., b3=.true.integer :: i=5, j=10

    ( b1 .or. b2 ) ______________

    ( b1 .or. b3 ) ______________

    ( b1 .and. b2 ) ______________

    ( b1 .and. b3 ) ______________

    ( (b1 .or. b2) .and. b3 ) ______________

    ( b1 .or. (b2 .and. b3) ) ______________

    ( .not. ( i < j ) ) ______________

    ( j < i ) ______________

    ,.,

    51

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    62/179

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    63/179

    :hapter C M %election %tatements

    B4 8rite a ortran to program that reads a num(er from the user that represents a television

    channel and then uses a :%E construct to determine the call letters for that station.

    Channe& Ca&& +etter$ ::i&iation

    3 GV>: !>:

    5 GVV" =

    C G9% :>%

    10 G9V /u(lic

    13 GT!V >:

    The program should displa' an appropriate message if an invalid or unassigned channel is

    entered. Test the program on a series of input values that will show each station.

    53

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    64/179

    :hapter C K %election %tatements

    5

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    65/179

    9 Loo"ing

    8hen a series of ortran statements need to (e repeated, it is referred to as a loopor do$loop.

    ortran do$loopis a special control statement that allows a ortran statement or set of statements to (ee+ecuted multiple times. This repetition can (e (ased on a set num(er of times, referred to as counter

    controlled, or (ased on a logical condition, referred to as conditionall' controlled. Each of these

    looping methods is e+plained in the following sections.

    9.1 Counter Controlled Loo"ing

    counter controlled loop is repeats a series of one or more ortran statements a set num(er of times.

    The general format of the counting loop is$

    do count_variable = start, stop, step

    end do

    where the count varia(le must (e an integer varia(le, start, stop, and step are integer varia(les or

    integer e+pressions. The step value is optional. f it is omitted, the default value is 1. f used, the stepvalue cannot (e @ero. The Zfortran statements4[ is a seAuence of statements and is referred to as the

    bod%of the do6loop. #ou can use an' e+ecuta(le statement within a do6loop, including 6THE!6

    E9%E6E!; and even another do6loop. >efore the do6loop starts, the values of start, stop, and stepare computed e+actl' once. Iore precisel', during the course of e+ecuting the do6loop, these values

    will not (e re6computed.

    The count varia(le receives the value of start varia(le or e+pression. f the value of control6var is less

    than or eAual to the value of stop6value, the Zfortran statements4[ part is e+ecuted. Then, the value ofstep 1 if omitted4 is added to the value of control6var. t the end, the loop goes (ac) to the top and

    compares the values of control6var and stop6value.

    f the value of control6var is greater than the value of final6value, the do$loopcompletes and the

    statement following end dois e+ecuted.

    or e+ample, with the declarations,

    integer :: counter, init=1, final=10, sum=0

    the following do6loop,

    do counter = init, finalsum = sum + counter

    end dowrite (*,*) "Sum is: ", sum

    will add the num(ers (etween 1 and 10 which will result in 55. %ince the step was not specified, it is

    defaulted 1.

    55

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    66/179

    :hapter K 9ooping

    nother e+ample, with the declarations,

    integer :: counter, init=1, final=10, step=2

    and the following do6loop,

    do counter = init, final, step

    write (*,*) counterend do

    will displa' the odd num(ers (etween 1 and 10 1, 3, 5, B, 4.

    nother e+ample would (e to read some num(ers from the user and compute the sum and average of

    those num(ers. The e+ample as)s the user how man' num(ers, reads that man' num(ers, computesthe sum, and the computes the average, and displa's the results.

    program averageimplicit noneinteger :: count, number, sum, input

    real :: average

    write(*,*) "Enter count of numbers to read"read(*,*) count

    sum = 0do number = 1, count

    read(*,*) inputsum = sum + input

    end do

    average = real(sum) / real(count)write *(*,*) "Average = ", average

    end program average

    The use of the function real)*converts the sum and count varia(les from integers to real values asreAuired for the average calculation. 8ithout this conversion, sumcount division would (e interpreted

    as dividing an integer (' an integer, 'ielding an integer result.

    final e+ample of a counter controlled loop is to compute the factorial of a positive integer. The

    factorial of an integer n, written as n\, is defined to (e the product of 1, 2, 3, ..., n61, and n. Ioreprecisel', n\ U 1 Y 2 Y 3 Y ... Y n.

    integer :: factorial, n, i

    factorial = 1do i = 1, n

    factorial = factorial * iend do

    the a(ove do6loop iterates ntimes. The first iteration multiplies factorial with 1, the second iterationmultiplies factorial with 2, the third time with 3, ..., the i thtime with iand so on. Thus, the values that

    are multiplied with the initial value of factorial are 1, 2, 3, ..., n. t the end of the do6loop, the value of

    factorial is 1 Y 2 Y 3 Y ... Y nwhich is n.

    5

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    67/179

    :hapter M 9ooping

    9. ,IT and C:CL, 'tatements

    The e+it and c'cle statements are used to modif' the e+ecution of a do6loop. The exitstatement is used

    to e+it a loop. The e+it can (e used alone, (ut it is t'picall' used with a conditional statement to allowe+iting a loop (ased on a specific condition. The exitstatement can (e used in a counter controlled

    loop or a conditionall' controlled loop.

    or e+ample, given the following declarations,

    integer :: i

    the following loop,

    do i = 1, 10if (i == 5) exit

    write(*,*) iend do

    will displa' the num(ers from 1 to < s)ipping the remaining iterations. %ince the varia(le iis chec)ed(efore the write statement, the value is not displa'ed with iis 5 and the loop is e+ited without

    completing the remaining iterations.

    The c%clestatement will s)ip the remaining portion of the do6loop and start (ac) at the top. The c%cle

    statement can (e used in a counter controlled loop or a conditionall' controlled loop. f the c'clestatement is used within a counter controlled loop, the ne+t inde+ counter is updated to the ne+t

    iteration, which could terminate the loop.

    9.! Counter Controlled ,xam"le

    n this e+ample we will write a ortran program to find the difference (etween the sum of the sAuares

    and the sAuare of the sum of the first&natural num(ers.

    :.3.1 8n'erstan' the Problem

    n order to find the difference (etween the sum of the sAuares and the sAuare of the sum of the first&

    natural num(ers, we will need to find (oth the sum of the sAuares and the sAuare of the sum. or

    e+ample, the sum of the sAuares of the first ten natural num(ers is,

    12

    22

    102

    = 3C5

    The sAuare of the sum of the first ten natural num(ers is,

    1 2 102 = 552 = 3025

    Hence the difference (etween the sum of the sAuares of the first ten natural num(ers and the sAuare ofthe sum is 3025 6 3C5 U 2

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    68/179

    :hapter K 9ooping

    :.3.2 Create the lgorithm

    or this pro(lem, first we will need to read the&value. Then, we will loop from 1 to the&value and

    find (oth the sum of the sAuares and the sAuare of the sum.

    ! declare variables! integer -> i, j, n, SumOfSqrs, SqrOfSums! display initial header! prompt for and read the n value! loop from 1 to N! compute sum of squares! compute sums! square the sums! compute difference between sum of squares and square of sums! display results

    or convenience, the steps are written a program comments.

    :.3.3 Deelop the Program

    >ased on the algorithm, the (elow program could (e developed.

    program difference

    ! declare variablesimplicit noneinteger :: i, n, SumOfSqrs=0, SqrOfSums=0, difference

    ! display initial headerwrite(*,*) "Example Program"

    write(*,*) " Difference between sum of squares "write(*,*) " and square of sums"write(*,*)

    ! prompt for and read the n valuewrite(*,*) "Enter N value: "read(*,*) n

    ! loop from 1 to N

    do i = 1, n! compute sum of squaresSumOfSqrs = SumOfSqrs + i**2

    ! compute square of sumsSqrOfSums = SqrOfSums + i

    end do

    ! square the sumsSqrOfSums = SqrOfSums**2

    ! compute difference between sum of squares and square of sumsdifference = SqrOfSums - SumOfSqrs

    5C

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    69/179

    :hapter M 9ooping

    ! display resultswrite(*,*) "Difference: ", difference

    end program difference

    The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le.

    :.3.4 0est9Debug the Program

    or this pro(lem, the testing would (e to ensure that the results match the e+pected value. %ome

    e+pected results can (e determined with a calculator or a spreadsheet. f the program does not provided

    the correct result, one or (oth of the intermediate results,!um'f!qrsor!qr'f!ums, ma' (e incorrect.These values can (e displa'ed with a temporar' write statement to determine which might not (e

    correct. f the pro(lem is still not found, the intermediate values calculated during the loop can also (e

    displa'ed with a write statement. The output can (e reviewed to determine what the program is doing

    and what ma' (e wrong4.

    9.$ Conditional Controlled Loo"ing

    conditional controlled loop repeats a series of one or more ortran statements (ased on a condition.s such, the loop ma' e+ecute a indeterminate num(er of times.

    =ne form of the conditional loop is$

    do while (logical expression)

    end do

    n this form, the logical e+pression is re6chec)ed at the top of the loop on each iteration.

    more general format of the conditional loop is$

    do

    end do

    s is, this loop will continue forever. /ro(a(l' not so good. selection statement, such as an statement, and an exitstatement would (e used to provide an means to terminate the looping. or

    e+ample,

    doif (logical expression) exit

    end do

    8ould stop looping onl' when the logical e+pression evaluates to true. The e+it statement can used

    used in multiple times in different locations as needed. n statement, in an' form, can (e used foreither the e+it of c'cle statements.

    5

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    70/179

    :hapter K 9ooping

    or e+ample, a conditional loop could (e used to reAuest input from the user and )eep re6prompting

    until the input is correct.

    integer :: month

    do write (*,*) "Enter month (1-12): "read (*,*) monthif (month >= 1 .and. month

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    71/179

    :hapter M 9ooping

    unless the 'ears is evenl' divisi(le (' month, date, year! display initial header

    ! loop! request month, date, and year! read month, date, and year! check month (1-12)! check year (1970-2020)! check date! 1,3,5,7,8,10,12 31 days! 4,6,9,11 30 days! 2 if modulo of year/4 is 0 29 days ! 2 if modulo of year/4 is /= 0 28 days ! display results

    or convenience, the steps are written a program comments.

    :.-.3 Deelop the Program

    >ased on the algorithm, the (elow program could (e developed.

    program datecheck

    ! declare variablesimplicit noneinteger :: month, date, year, datemax

    ! display initial header

    write(*,*) "Date Verification Example"

    ! loopdo

    ! request month, date, and yearwrite(*,*) "Date Verification Example"

    ! read month, date, and yearread (*,*) month, date, year

    ! check month (1-12)if ( month < 1 .or. month > 12 ) then

    write(*,*) "Error, invalid month"

    cycleend if

    ! check year (1970-2020)if ( year < 1970 .or. year > 2020 ) then

    write(*,*) "Error, invalid year"cycle

    end if

    ! check date

    1

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    72/179

    :hapter K 9ooping

    ! 1,3,5,7,8,10,12 31 days! 4,6,9,11 30 days! 2 if modulo of year/4 is 0 29 days ! 2 if modulo of year/4 is /= 0 28 days

    select case (month)

    case (1,3,5,7,8,10,12)datemax = 31case (2)

    if (mod(year,4)==0) thendatemax = 29

    elsedatemax = 28

    end ifcase (4,6,9,11)

    datemax = 30end select

    if ( date < 1 .or. date > datemax ) then

    write (*,*) "Error, invalid date."cycle

    end if

    exitend do

    ! display resultswrite(*,*) "Valid Date is:", month, date, year

    end program datecheck

    The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le.

    :.-.4 0est9Debug the Program

    or this pro(lem, the testing would (e to ensure that the results match the e+pected value. This will

    reAuire entering a series of different dates and verif'ing that the displa'ed output is correct for thegiven input data.

    9.0 ,xercises

    >elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.

    :.&.1 Quiz Questions

    >elow are some Aui@ Auestions.

    14 8hat happen when an exitstatement is e+ecutedN

    24 How man' exitstatements can (e included in a loopN

    34 8hat happen when an continuestatement is e+ecutedN

    2

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    73/179

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    74/179

    :hapter K 9ooping

    34 8rite a program to calculate the range that a (all would travel when it is thrown with an initial

    velocit' v)and angle *. >ased on an initial velocit' provided (' the user, calculate the range

    ever' 5 degrees for angles (etween 5 and C5 degrees. f we assume negligi(le air friction andignore the curvature of the earth, a (all that is thrown into the air from an' point on the earths

    surface will follow a para(olic flight path.

    The range distance(etween the initial origin and

    final impact4 is determined (' the formula$

    range

    2v,

    2

    gco$ * $in*

    where v)is the initial velocit' of the (all, ` is the angle of the throw, andgis the acceleration

    due to the earth7s gravit'. The value for gravit' should (e defined as a constant and set to 6.C1meters per second.

    +ote, the intrinsic trigonometric functions wor) in radians, so the angle in degrees will need to

    (e converted to radians for the calculations. To convert degrees to radians$

    radians degrees

    1*,

    Test the program on a series of different input values.

    sumsExample Program Difference between sum of squares and square of sums

    Enter count of numbers to read:3Difference: 2640

    8hen the advance clause is included, with the setting of -no as follows$

    ! prompt for and read the n valuewrite(*,*, advance="no") "Enter N value: "read(*,*) n

    The resulting e+ecution would (e as follows$

    c:\mydir> sumsExample Program Difference between sum of squares and square of sums

    Enter count of numbers to read: 10Difference: 2640

    8hich allows the input to (e entered on the same line as the prompt.

    1;.8 ,xam"le

    This e+ample will read a date from the user month, date, and 'ear, on the same line4, determine the

    da' of wee) for that monthdate'ear4. Then, the program will displa' the original input date numericform4 and the formatted date. The original input date will (e displa'ed include leading 07s i.e.,

    010120104.

    1;.6.1 8n'erstan' the Problem

    or this pro(lem, we will read the three num(ers for the date from the user. The verification of the date

    information is left as an e+ercise.

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    80/179

    :hapter 10 K ormatted nput=utput

    To calculate the da' on which a particular date falls, the following algorithm ma' (e used the divisions

    are integer divisions4$

    a = (14 - month) / 12y = year - a

    m = month + 12*a - 2

    daynum = [ date + y + y/4 - y/100 + y/400 + (31*m/12) ] mod 7

    The value of da#numis 0 for a %unda', 1 for a Ionda', 2 for a Tuesda', etc.

    1;.6.2 Create the lgorithm

    or this pro(lem, first we will need to read the date. The verification of the date entered and error

    chec)ing is left as an e+ercise. Then, the original input date can (e displa'ed, in numeric form,formatted appropriatel'. or a date, this would mean two digits for the month, a -, two digits for the

    date, a -, and four digits for the 'ear. 8hen the date is onl' one digit, for e+ample 5, it is customar'

    to displa' a -05 so the program will ensure this occurs.

    ! declare variables! integer -> month, date, year! display initial header! prompt for month, date, and year! read month, date, and year! display formatted numeric month/date/year

    Then the program can calculate the da' of the wee) (ased on the formula4 and convert the resulting

    num(er 064 into a date string and displa' the result.

    ! calculate day of week

    ! convert day of week (0-6) to string! convert month (1-12) to string! display formatted string for day, month, and year

    or convenience, the steps are written a program comments.

    1;.6.3 Deelop the Program

    >ased on the algorithm, the (elow program could (e developed.

    program dateformatter

    ! declare variablesimplicit noneinteger :: month, date, yearinteger :: a, m, y, d,character(9) :: amonth, day_of_week

    ! ----------! display initial header

    write(*,*) "Date Formatting Example"

    B0

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    81/179

    :hapter 10 M ormatted nput=utput

    ! prompt for month, date, and yearwrite(*,*,advance="no") "Enter date (month, date, year):"

    ! read month, date, and yearread (*,*) month, date, year

    ! ----------! display formatted numeric month/date/year

    write(*,*) "----------------------------------------"write(*,*) "Input Date: "write(*,'(5x, i2.2, a, i2.2, a, i4)', imonth, "/", &idate, "/", iyear

    ! ----------! calculate day of week

    a = (14 - imonth) / 12

    y = iyear - am = imonth + 12 * a - 2d = mod ( (idate + y + y/4 - y/100 + y/400 + (31*m/12)), 7)

    ! ----------! convert day-of-week integer to day-of-week string

    select case (d)case (0)

    day_of_week = "Sunday "case (1)

    day_of_week = "Monday "case (2)

    day_of_week = "Tuesday "case (3)

    day_of_week = "Wednesday"case (4)

    day_of_week = "Thursday "case (5)

    day_of_week = "Friday "case (6)

    day_of_week = "Saturday "end select

    ! ----------! convert month (1-12) to string

    select case (month)case (1)

    amonth = "January "case (2)

    amonth = "February "case (3)

    amonth = "March "case (4)

    amonth = "April "

    B1

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    82/179

    :hapter 10 K ormatted nput=utput

    case (5)amonth = "May "

    case (6)amonth = "June "

    case (7)

    amonth = "July "case (8)amonth = "August "

    case (9)amonth = "September"

    case (10)amonth = "October "

    case (11)amonth = "November "

    case (12)amonth = "December "

    end select

    ! ----------! display formatted string for day, month, and year

    write(*,'(/a)') "Formatted Date:"write(*,'(5x, a, a, a, 1x, i2.0, a, i4/)') &

    trim(day_of_week), ", ", trim(smonth), &idate, ", ", iyear

    end program dateformatter

    The spacing and indentation is not reAuired, (ut helps to ma)e the program more easil' reada(le. The

    trim)*intrinsic function removes an' trailing spaces from the input string. dditional informationregarding handling character data t'pes in provided in the following section.

    1;.6.4 0est9Debug the Program

    or this pro(lem, the testing would (e to ensure that the output formatting is correct. %ince there is noerror chec)ing on the input, onl' correct dates should (e entered. Test the program on a series of

    different input values and verif' that the output is correct for those input values.

    1;.9 ,xercises

    >elow are some Aui@ Auestions and proFect suggestions (ased on this chapter.

    1;.:.1 Quiz Questions

    >elow are some Aui@ Auestions.

    14 8hat is the format specifier for each of the following$

    a4 integer values

    (4 real valuesc4 logical values

    d4 hori@ontal spacing i.e., spaces4

    B2

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    83/179

    :hapter 10 M ormatted nput=utput

    e4 a newline

    f4 charactersstrings

    24 ;escri(e the output of the following code fragment 1 pts each4$

    +ote, show (lan)s with an R underscore4 character.

    write (*,'(a5)') "Hello World"write (*,'(a)') "Hello World"

    34 ;escri(e the output of the following code fragment 3 pts4$

    !ote, show (lan)s with an R underscore4 character.integer :: number = 5

    write (*,'(i5.3)') number

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    84/179

    :hapter 10 K ormatted nput=utput

    34 8rite a ortran program that displa's an amorti@ation schedule. The program should read the

    loan amount, annual interest rate, and the loan term in months from a single line4.

    The formula for calculating the monthl' pa'ment is$

    pa#ment amount

    irate(

    1+ irate)

    term

    ( (

    1+

    irate)

    term

    1)

    +ote, the iratein the formula must (e converted to a monthl' rate divided (' 124 and then

    divided (' 100 to convert from percentage4. ;uring the time period term4, some of each

    monthl' pa'ment will (e used to pa' the interest and some will (e used to reduce the

    outstanding (alance. The monthl' interest amount can (e calculated (' monthl' interest ratetimes outstanding (alance. The amounts must (e lined up with onl' two digits for cents. The

    pa'ment num(er must three digits including leading @ero7s if necessar'4. Test the program on a

    series of different input values and verif' that the output is correct for those input values.

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    85/179

    11 Characters and 'trings

    ortran was originall' developed for scientific and engineering application reAuiring significant

    mathematical calculations. However, the ortran 5 language includes e+tensive character and stringhandling capa(ilities.

    11.1 Character and 'tring Constants

    character is a single character or s'm(ol, t'picall' enclosed in Auotes. or e+ample, letters -6Wand -a 6 -@4, punctuation -\, -,, -N, etc.4 , s'm(ols, -S, -, -[, etc.4, and digits -1, -2 are

    characters.

    %ome e+amples include$

    "X""z""5"

    :haracter and string constants are case sensitive. %o, character - upper6case4 is not the same as -+

    lower6case4. 8hen a digit is enclosed in Auotes, it is treated as a character and conseAuentl'

    arithmetic operations addition, su(traction, etc.4 are not allowed.

    string is a series of characters. string consists of an ar(itrar' seAuence of characters also enclosed

    in Auotes. %ome e+amples include$

    "Hello World.""456"

    "1 2 3""456?""Good bye cruel world!!""Have a nice day?"

    %ince digits enclosed in Auotes are not numeric values, the strings -1 2 3 and -

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    86/179

    :hapter 11 K :haracters and %trings

    This is performed with a t'pe declaration statement in the form of$

    ::

    or character varia(les, the t'pe is -character. or e+ample, to define an character varia(le to hold the

    da' of wee) i.e., -8ednesda'4, the following declaration,

    character(len=9) :: dayofweek

    8ould define the varia(le, da%o("ee-, with a ma+imum length of possi(le characters.

    dditional e+amples include$

    character(len=3) :: symbol1, symbol2character :: symbol3character(1) :: symbol5, symbol5character(30) :: symbol6, symbol7

    The declarations can (e entered in an' order, however the' must (e at the (eginning of the program.

    The -lenU is optional and can (e omitted. 8hen the length is omitted entirel', the default length is setto 1. This, -character, -characterlenU14, and -character14 are all the same.

    8hen multiple varia(les are included in a single declaration, the' must all (e the same length. f

    different lengths are reAuired, separate declaration lines are reAuired.

    11.! Character 3ariable Initiali(ation

    t is possi(le to declare a character varia(le and to set it is initial value at the same time. This

    initiali@ation is not reAuired, (ut can sometime (e convenient. or e+ample, to define an charactervaria(le, da%o("ee-, and set it to a da' of wee)$

    character(len=9) :: todaysdate="Wednesday"

    dditional e+amples include$

    character(9) :: thismonth="June", lastmonth, nextmonth="July"character :: ltr1="A", ltr2="b"

    %paces or no spaces (etween the varia(les, eAual signs, semicolons, and commas are allowed.Varia(les initiali@ed at declaration can (e changed during program e+ecution as needed.

    11.$ Character Constants

    t is possi(le to declare a character varia(le, set it is initial value, and ensure that the value can not (e

    changed. or e+ample, to define an character constant, lang,

    character(len=7), parameter :: lang="English"

    To save counting the characters, the -Y can (e used. or e+ample,

    character(len=*), parameter :: university="UNLV"

    This instructs the ortran compiler to count the characters and set the appropriate length.

    B

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    87/179

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    88/179

    :hapter 11 K :haracters and %trings

    11.8 Character Com"arisons

    The standard relational operators -UU, -[, -[U, etc.4 have some limitations when character data is

    used. %imple comparisons, such as,

    "A" < "D""ABC" == "ABC"

    will wor) as e+pected. That is, (oth will evaluate to true.

    However, when comparing, the following characters,

    "A" > "a""100" < "20""ABC"

  • 8/10/2019 Introduction-to-programming-using-Fortran-95.pdf

    89/179

    :hapter 11 M :haracters and %trings

    11.1; ,xam"le

    This e+ample will scan a string and convert all lower6case letter to upper6case.

    11.


Recommended