DDP 105 Note
DDP 105 Note
1 ALGORITHMS
The term algorithm originally referred to any computation performed via a set of rules applied
to numbers written in decimal form. The word is derived from the phonetic pronunciation of the
last name of Abu Ja'far Mohammed ibn Musa al-Khowarizmi, who was an Arabic mathematician
who invented a set of rules for performing the four basic arithmetic operations (addition,
subtraction, multiplication and division) on decimal numbers.
This breaks down 'Making Chinese egg custard' into smaller steps. To make the product one still
needs to know how to execute each of the steps in the procedure and understand all of the terms.
FLOWCHARTS
Flowcharting is a tool developed in the computer industry, for showing the steps involved in a
process. A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by
arrows - each shape represents a step in the process, and the arrows show the order in which they
occur. Flowcharting combines symbols and flowlines, to show figuratively the operation of an
algorithm.
In computing, there are dozens of different symbols used in flowcharting (there are even national
and international flowcharting symbol standards). In business process analysis, a couple of
symbols are sufficient. A box with text inside indicates a step in the process, while a diamond
with text represents a decision point. See the figure for an example. If the flowchart is too messy
to draw, try starting again, but leaving out all of the decision points and concentrating on the
simplest possible course. Then the session can go back and add the decision points later. It may
also be useful to start by drawing a high-level flowchart for the whole organisation, with each
box being a complete process that has to be filled out later.
From this common understanding can come a number of things - process improvement ideas will
often arise spontaneously during a flowcharting session. And after the session, the facilitator can
also draw up a written procedure - a flowcharting session is a good way of documenting a
process. Process improvement starts with an understanding of the process, and flowcharting is
the first step towards process understanding.
Flowcharting Symbols
There are 6 basic symbols commonly used in flowcharting of assembly language programs:
Terminal, Process, input/output, Decision, Connector and Predefined Process.
This is not a complete list of all the possible flowcharting symbols, it is the ones used most often
in the structure of Assembly language programming.
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown
as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
• From one page to another page.
• From the bottom of the page to the top of the same page.
• An upward flow of more then 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
Flowcharting uses symbols that have been in use for a number of years to represent the type of
operations and/or processes being performed. The standardised format provides a common
method for people to visualise problems together in the same manner. The use of standardised
symbols makes the flow charts easier to interpret, however, standardising symbols is not as
important as the sequence of activities that make up the process.
Flowcharting Tips
• Chart the process the way it is really occurring. Do not document the way a written
process or a manager thinks the process happens.
• People typically modify existing processes to enable a more efficient process. If the
desired or theoretical process is charted, problems with the existing process will not be
recognised and no improvements can be made.
Note all circumstances actually dealt with.
• Test the flow chart by trying to follow the chart to perform the process charted. If there
is a problem performing the operation as charted, note any differences and modify the
chart to correct. A better approach would be to have someone unfamiliar with the process
try to follow the flow chart and note questions or problems found.
Example 1. Design an algorithm and the corresponding flowchart for adding the test
scores as given below: 26, 49, 98, 87, 62, 75
a) Algorithm
1. Start
2. Sum = 0
3. Get the first testscore
4. Add first testscore to sum
5. Get the second testscore
6. Add to sum
7. Get the third testscore
8. Add to sum
9. Get the Forth testscore
10. Add to sum
11. Get the fifth testscore
12. Add to sum
13. Get the sixth testscore
14. Add to sum
15. Output the sum
16. Stop
Example 2: The problem with this algorithm is that, some of the steps appear more than
once, i.e. step 5 get second number, step 7, get third number, etc. One could shorten the
algorithm or flowchart as follows:
1. Start
2. Sum = 0
3. Get a value
4. sum = sum + value
5. Go to step 3 to get next Value
6. Output the sum
7. Stop
This algorithm and its corresponding flowchart are a bit shorter than the first one. In this
algorithm, step 3 to 5 will be repeated, where a number is obtained and added to sum.
Similarly the flowchart indicates a flowline being drawn back to the previous step indicating that
the portion of the flowchart is being repeated. One problem indicates that these steps will be
repeated endlessly, resulting in an endless algorithm or flowchart. The algorithm needs to be
improved to eliminate this problem. In order to solve this problem, we need to add a last value to
the list of numbers given. This value should be unique so that, each time we get a value, we test
the value to see if we have reached the last value. In this way our algorithm will be a finite
algorithm which ends in a finite number of steps as shown below. There are many ways of
making the algorithm finite.
The new list of numbers will be 26, 49, 498, 9387, 48962, 1, -1. The value –1 is a unique number
since all other numbers are positive.
1. Start
2. Sum = 0
Corresponding flowchart
PSEUDOCODE
Pseudocode is one of the tools that can be used to write a preliminary plan that can be developed
into a computer program. Pseudocode is a generic way of describing an algorithm without use of
any specific programming language syntax. It is, as the name suggests, pseudo code —it cannot
be executed on a real computer, but it models and resembles real programming code, and is
written at roughly the same level of detail. Pseudocode, by nature, exists in various forms,
although most borrow syntax from popular programming languages (like C, Lisp, or
FORTRAN). Natural language is used whenever details are unimportant or distracting.
Computer science textbooks often use pseudocode in their examples so that all programmers can
understand them, even if they do not all know the same programming languages. Since
pseudocode style varies from author to author, there is usually an accompanying introduction
explaining the syntax used. In the algorithm design, the steps of the algorithm are written in free
English text and, although brevity is desired, they may be as long as needed to describe the
particular operation. The steps of an algorithm are said to be written in pseudocode. Many
languages, such as Pascal, have a syntax that is almost identical to pseudocode and hence make
the transition from design to coding extremely easy.
2 Computer Organization
Before writing programs, it is useful to understand some basics about how a computer is
organized. This section provides a brief, high-level overview of the basic components of a
computer and how they interact.
2.2 Compiler
Programs can be written in the Fortran programming language. However, the CPU does not read
Fortran directly. Instead, the Fortran program that we create will be converted into binary (1's
and 0's) by the compiler. These 1's and 0's are typically referred to as machine language. The
CPU will read the instructions and information, represented in binary as machine language, and
perform the commands from the program.
The compiler is a program itself and is required in order to create the files needed to execute
programs written in Fortran 95/2003/2008.
Which means,
1234 = 1×1000 2×100 3×10 4×1
1234 = 1×103 2×102 3×101 4×100
The decimal system is base 10 using the digits 0 through 9.
In base 2, we put the digits 0 or 1 in columns 20, 21, 23, and so on. For example,
11012 = 1×23 1×22 0×21 1×20 = 841
Which in decimal is 1310.
A set of 8 bits is a referred to as a byte. Computer data is typically allocated in bytes or sets of
bytes.
3 Getting Started
3.2.2 Comments
Comments are information for the programmer and are not read by the computer. For example,
comments typically include information about the program. For programming assignments, the
comments should include the programmer name, assignment number, and a brief description of
the program. In Fortran, the exclamation mark (!) denotes a comment. Any characters after the
exclamation mark (!) are ignored by the compiler and thus are comments as shown in the
example.
Will display the message Hello World to the screen. Additional information regarding the write
statement and outputting information is provided in later chapters.
In this example, the program is named 'first'. This file, provided as input to the compiler, is
typically referred to as the source file.
3.4 Compiling
Once the program is typed into a file, the file must be compiled. Compiling will convert the
human readable Fortran program, or source file, into a computer readable version (in binary).
In order to compile, the command prompt (Windows) or terminal interface (Unix, MAC) is
required. This interface will allow commands to be typed directly into the computer (instead of
using a mouse).
Once started, it is typically necessary to change directories (from the default location) to the
location of where the hw.f95 source file was located (form the previous steps). Changing
directories is typically done with a cd <directoryName> command. For example, cd fortran
(which is the name of the directory used in this example). The prompt typically changes to
include the current directory location.
In the example below, the commands typed by the user are displayed in bold. The regular (non-
bolded) text refers to prompts or other information displayed by the computer (which will not
need to be typed). To compile the example program, the following command would be entered:
3.5 Executing
To execute or run a program on a Windows based machine, type the name of the executable file.
For example, to execute or run the hw.exe program:
C:\fortran> hw
Hello World.
C:\fortran>
It is not necessary to type the extension (i.e., “.exe”) portion of the file name. It should be noted
that the space prior to the “H” is not produced by the program, but is how the system displays
output. To execute or run a program on a Unix or MAC based machine, type “./” and the name of
the executable file. For example, to execute or run the hw program:
c:\fortran> ./hw
Hello World.
c:\fortran>
The output ('Hello World.' as displayed on the screen) will be the same for Windows, Unix, or
MAC based machines.
4.1 Variables
The basic concept in a program is the concept of a variable. Variables in a program are like
variables in an algebraic expression. They are used to hold values and then write mathematical
expressions using them. Fortran allows us to have variables of different types. A variable can
hold one value at a time. If another value is placed in the variable, the previous value is over-
written and lost.
DDP 105 CLASS NOTE COMPILED BY FOLORUNSO, S. O Page 11 of 150
Variable Name → 42
Variables must be declared at the start of the program before they are used.
x
today
next_month
summation10
Note that the space (between next and month) or the special character, @, is not allowed.
Additionally, each variable must have a type associated as explained in the following sections.
4.1.2 Keywords
In programming, a keyword is a word or identifier that has a special meaning in a programming
language. For example, in the “hello world” Fortran program from the previous chapter, the
word program has a special meaning in that it is used to note the start or beginning of a program.
Additionally, the word write has a special meaning to note an output action (e.g., writing some
information to an output device, like the screen). Such keywords are reserved in that they cannot
be used for anything else such as variable names. That is, a variable name of program or write is
not allowed. As additional Fortran 95/2003/2008 statements and language constructs are
explained, more keywords will be identified. In general, words used for Fortran language
statements, attributes, and constructs will likely be keywords. A complete list of keywords or
reserved words is located in Appendix F.
Type Description
4.2.1 Integer
An integer1 is a whole number (not a fraction) that can be positive, negative, or zero. Examples
include the numbers 10, 0, -25, and 5,148. Integers are the numbers people are most familiar
with, and they serve a crucial role in mathematics and computers. All integers are whole
numbers, so operations like one divided by two (1/2) is 0 since the result must be a whole
number. For integer division, no rounding will occur as the fractional part is truncated.
4.2.2 Real
A real number2 includes the fractional part, even if the fractional part is 0. Real numbers, also
referred to as floating point numbers, include both rational numbers and irrational numbers.
Examples of irrational numbers or numbers with repeating decimals include π, 2 and e.
Additional examples include 1.5, 5.0, and 3.14159. Fortran 95/2003/2008 will accept 5. as 5.0.
All examples in this text will include the “.0” to ensure clarity.
4.2.3 Complex
A complex number3, in mathematics, is a number comprising a real number and an imaginary
number. It can be written in the form of a + bi, where a and b are real numbers, and the i is the
standard imaginary unit with the property that i2 = −1.0. The complex numbers contain the
ordinary real numbers, but extend them by adding in extra numbers like an extra dimension. This
data type is not used extensively, but can be useful when needed.
4.2.4 Character
A character4 is a symbol like a letter, numerical digit, or punctuation. A string5 is a sequence or
set of characters. Characters and strings are typically enclosed in quotes. For example, the upper
case letter “Z” is a character and “Hello World” is a string. The characters are represented in a
standardized format referred to as ASCII.
4.2.5 Logical
A logical6 is only allowed to have two values, true or false. A logical can also be referred to as a
boolean. In Fortran, the true and false values are formally expressed as .true. or .false. which are
also called logical constants. The leading and trailing . (period) are required for the true and false
constants.
integer :: today
4.3.4 Initialization
It is possible to declare a variable and set its initial value at the same time. This initialization is
not required, but can sometime be convenient. For example, to define an integer variable
todaysdate and set it to the 15th of the month:
integer :: todaysdate=15
Additional examples include:
integer :: todaysday=15, tomorrow=16, yesterday=14
real :: ave = 5.5
4.3.5 Constants
A constant is a variable that cannot be changed during program execution. For example, a
program might declare a variable for π and set it to 3.14159. It is unlikely that a program would
need to change the value for π. The parameter qualifier will declare the variable as a constant, set
the initial value, and not allow that initial value to be altered during the program execution.
For example, the declarations:
will set the variable pi to 3.14159 and width to 1280 and ensure that they cannot be changed
while the program is executing.
4.4 Comments
Comments are information for the programmer ignored by the compiler. In general, comments
typically include information about the program. For example, a comment might include the last
modification date, programmer name, and details about the update. For programming
assignments, the comments might include the programmer name, assignment number, and a
description of the program.
4.5.1 Example
The following trivial program illustrates the program formatting requirements and variable
declarations.
! Example Program
program example1
implicit none
integer :: radius, diameter
integer :: height=100, width=150
real :: area, perimeter
real :: length = 123.5, distance=413.761
real, parameter :: pi = 3.14159
character(11) :: msg = "Hello World"
write (*,*) "Greeting: ", msg
end program example1
In this example, a series of variables are defined (as examples) with most not used. The program
will display Greeting: Hello World when executed. The following chapters will address how to
4.6.1 Integers
As previously noted, the range of an integer value can range between −2,147,483,648 and
+2,147,483,647. In the unlikely event that a larger range is required, a special declaration can be
used to extend the range. The kind specifier is used with the integer declaration.
For example, to declare a variable bignum with an extended range, the integer declaration would
be as follows:
integer(kind=8) :: bignum
The extended range of integer variables declared with the kind=8 is –9,223,372,036,854,775,808
to 9,223,372,036,854,775,807.
4.6.2 Real
As previously noted, the range is approximately ±1.7×10±308 which supports about 15 digits of
precision. If more precision is required, the kind specifier can be used. For example, to declare a
variable rnum with an extended range, the integer declaration would be as follows:
real(kind=16) :: rnum
The extended precision of real variables declared with the kind=16 is approximately
±1.7×10±308 which supports about 31 digits of precision.
5 Expressions
This section describes how to form basic Fortran 95/2003/2008 expressions and perform
arithmetic operations (i.e., add, subtract, multiple, divide, etc.). Expressions are formed using
literals (actual values), variables, and operators (i.e., +, -, *, /, etc.). The previous chapter
provides an explanation of what variable is and a summary of the five Fortran data types.
5.1 Literals
1.0
0.25
3.14159
The real number should include the decimal point (i.e., the “.”). A real number includes the
fractional part, even if the fraction is 0. Fortran will accept a number with the “.” and no further
digits. For example, 5. is the same as 5.0. All examples in this text will include the “.0” to ensure
clarity.
5.1.2.1 E-Notation
For larger real numbers, e-notation may be useful. The e-notation means that you should
multiply the constant by 10 raised to the power following the "E". This is sometimes referred to
as scientific notation.
2.75E6
3.3333E1
(3.2, 4.1)
(1.0, 9.9E1)
The first number denotes the real part and the second the imaginary part. Although a complex
number always consists of two elements, it is considered a single value.
"X"
"Hello World"
"Good bye cruel world!"
"Have a nice day"
The double-quote is sometimes referred to as an escape character. Strings and characters must be
associated with the character data type.
5.2.1 Assignment
In programming, assignment is the term for setting a variable equal to some value. Assignment is
performed with an equal (=) sign. The general form is:
variable = expression
The expression may be a literal, variable, an arithmetic formula, or combination of each. Only
one assignment to a single variable can be made per line.
For example, to declare the variable answer1 as a real value,
The value for answer1 can be changed as often as needed. However, it can only hold one value
at a time.
5.2.2 Addition
The Fortran addition operation is specified with a plus sign (+). For example, to declare the
variables,
5.2.3 Subtraction
5.2.4 Multiplication
The Fortran multiplication operation is specified with an asterisk (*). For example, to declare the
variables, ans, value1, value2, and value3,
5.2.5 Division
The Fortran division operation is specified with a slash symbol (/). For example, to declare the
variables, ans, value1, value2, and value3,
5.2.6 Exponentiation
Exponentiation means “raise to the power of”. For example, 2 to the power of 3, or 23 is (2 * 2 *
2) which is 8. The Fortran exponentiation operation is specified with a double asterisks (**).
For example, to declare the variables, ans and value1,
For operations of the same precedence level, the expression is evaluated left to right. Parentheses
may be used to change the order of evaluation as necessary. For example, declaring the variables
real :: z
real, parameter :: pi = 3.14159
and then performing the calculation of the cosine the variable pi as follows,
z = cos(pi)
which will set z to -1.0. The variable pi is the input argument.
rnum1 = real(inum1)
inum2 = int(rnum2)
inum3 = nint(rnum3)
5.4.3 Summary
A summary of some of the more common intrinsic functions include:
1/2 = 0
1.0 + 1/4 = 1.0
1.0 + 1.0/4 = 1.25
Any integers values are converted to real only when mixed-mode is encountered on the same
operation type. Conversion may also occur on assignment.
Unexpected conversions can cause problems when calculating values. In order to avoid such
problems, it is strongly recommended to not use mixed-mode. There are a series of rules
5.6 Examples
Below is an example program that calculates velocity based on acceleration and time. The
program declares the appropriate variables and calculate the velocity.
program findvelocity
! Program to calculate the velocity from the
! acceleration and time
! Declare variables
implicit none
real :: velocity, acceleration = 128.0
real :: time = 8.0
! Display initial header
write (*,*) "Velocity Calculation Program"
write (*,*)
! Calculate the velocity
velocity = acceleration * time
write (*,*) "Velocity = ", velocity
end program findvelocity
b = 2 π (n − 81) / 365
Where, n is the day number. For example, n = 1 for January 1, n = 2 for January 2, and so on.
The program should read the value for n (1-365) from the user as an integer. The program should
perform the appropriate type conversions, perform the required calculations, and display the
original n value, the calculated b (for reference), and final e value which represents the time
difference in minutes. Test the program on a series of different values. Note, the formulas
provided are an approximation.
write (*,*)
will display a blank line.
Multiple variables and strings can be displayed with one write statement. For example, using the
previous declarations;
num1, num2,
integer :: ans1, ans2
6.3 Example
Below is an example program that calculates the area of a circle. The program will declare the
appropriate variables, read the radius, calculate the circle area, and display the result.
Program circle
! Program to calculate the area of a circle
! Declare variables
implicit none
real :: radius, area
real, parameter :: pi = 3.14159
! Display initial header and blank line
write (*,*) "Circle Area Calculation Program"
write (*,*)
! Prompt for and read the radius
write (*,*) "Enter Circle Radius"
read (*,*) radius
! Calculate the circle area
area = pi * radius**2
! Display result
write (*,*) "Circle Area: ", area
end program circle
The comments are not required, but help make the program easier to read and understand. If the
program does not work at first, the comments can aid in determining the problem.
7 Program Development
Writing or developing programs is easier when following a clear methodology. The main steps in
the methodology are:
● Understand the Problem
● Create the Algorithm
● Implement the Program
● Test/Debug the Program
To help demonstrate this process in detail, these steps will be applied to a simple problem to
calculate and display the period of a pendulum.
As additional examples are presented in later chapters, they will be explained and presented
using this methodology.
Period = 2 π √ Lg
Where:
g = 980 cm/sec2
π = 3.14159
L = Pendulum length (cm)
α = Angle of displacement (degree)
Then the period can be calculated based on the provided formula and the results displayed.
Formalizing this, the following steps can be developed and written down as follows:
! declare variables
! real constants >
gravity, pi
! reals >
angle, length, alpha
! display initial header
! prompt for and read the length and angle values
! convert degrees to radians
! calculate the period
! display the results
While this is a fairly straightforward algorithm, more complex problems would require more
extensive algorithms. Examples in later chapters will include more complex programs. For
convenience, the steps are written as program comments. This will allow the addition of the code
to the basic algorithm.
program period
! Program to calculate the period of a pendulum
! declare variables
! real constants >
gravity, pi
! reals >
angle, length, alpha
The indentation is not required, but helps make the program easier to read. Note that the “2”,
“1”, and “4” in the algorithm are entered as 2.0, 1.0, and 4.0 to ensure consistent data typing (i.e.,
all reals). If the 1 over 4 is entered as “1/4” instead of “1.0/4.0”, it be incorrect since “1/4” would
provide a result of 0 (since this would be integer division).
C:\mydir> period
Pendulum Period Calculation Program
Enter Length and Angle values:
120.0 15.0
The Period is: 2.20801973
K:\mydir>
As before, input typed by the user is shown in bold. For this program, the results can be verified
with a calculator. A series of different values should be used for testing. If the program does not
work, the program comments provide a checklist of steps and can be used to help debug the
program.
c:\mydir> gfortran o
period period.f95
period.f95:13.1:
wrote (*,*)
1
The first digit, 13 in this example, represents the line number where the error occurred. Using a
text editor that displays line numbers, the statement that caused the error can be quickly found
and
corrected. If the declaration for the variable length is omitted, the error would appear as follows:
c:\mydir> gfortran o
period period.f95
period.f95:17.18:
read (*,*) length, angle
1
Error: Symbol 'length' at (1) has no IMPLICIT type
In this case, the error is shown on line 18 (first digit after the “:”). However, the actual error is
that the variable length is not declared. Each error should be reviewed and evaluated.
c:\mydir> period
Pendulum 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 expecting numeric values and letters were provided. Since letters are not
meaningful in this context, it is an error and the program “crashes” or stops with an error
message.
Later chapters will provide additional information on how to deal with such errors. Until then,
proving the correct data type will avoid this kind of error.
The 1 over 4 is entered as “1/4” which are interpreted as integers. As integers, “1/4” results in 0.
The compiler will accept this, perform the calculations, and provide an incorrect result.
The program would compile and execute as follows.
c:\mydir> period
Pendulum Period Calculation Program
Enter Length and Angle values:
120.0 15.0
However, an incorrect answer would be generated as shown. This is why testing the program is
required. Logic errors can be the most difficult to find. One of the best ways to handle logic
errors is to avoid them by careful developing the algorithm and writing the code. If the program
has a logic error, one way to find the error is to display intermediate values.
7.5 Exercises
Below are some quiz questions.
1) What are the four program development steps?
2) What are the three types of errors?
3) If a program to compute the area of a rectangle uses a formula, height × height × width, what
type of error would this be?
4) Provide an example of that would generate a compiler error.
circumference = 2 √ π CircleArea
Test the program using several different input values.
3) Create a program to prompt for and read the radius of a sphere from the user and calculate the
surface area of the sphere using the following formula:
sphereVolume = (4 π / 3)r 3
Test the program using several different input values.
8 Selection Statements
When writing a program, it may be necessary to take some action based on the outcome of
comparing the values of some variables. All programming languages have some facility for
decision-making. That is, doing one thing if some condition is true and (optionally) doing
something else if it is not. Fortran IF statements and/or CASE statements are used to allow a
program to make decisions.
integer :: gameLives
it might be useful to know if the current value of gameLives is greater than 0. In this case, the
conditional expression would be,
(gamelives > 0)
Which will result in a true or false result based on the value of the variable gameLives.
Logical operators are used to combine conditional expressions as needed to form a more
complex
conditional expression. For example, given the declaration of,
it might be useful to know if the current value of gameLives and extraLives are both 0 which
would indicate the game is over. In this case, the relational operator would be AND with the
complete conditional expression,
which still results in a true or false result. However, since the OR logical operation is used, the
final result will be true if either conditional expressions is true. The relational operators (e.g., <,
<=, >, >=, ==, /=) have higher precedence than logical operators
(AND, OR, NOT). This means each of the smaller conditional expressions will be completed
before the local operation is applied. A conditional expression can be a combination of multiple
conditional expressions combined with logical operators.
8.3 IF Statements
IF statements are used to perform different computations or actions based on the result of a
conditional expression (which evaluates to true or false). There are a series of different forms of
the basic IF statement. Each of the forms is explained in the following sections.
Where the <fortran statements> may include one or more valid Fortran statements. For example,
given the declaration of,
integer :: gameLives
based on the current value of gamelives is, a reasonable IF statement might be;
if ( gameLives == 0 ) then
write (*,*) "Game Over."
write (*,*) "Please try again."
end if
which will display the message “Game Over.” and “Please try again.” on the next line if the
value of gameLives is equal to 0.
In this form, only a single statement is executed if the conditional expression evaluates to true.
The
previous example might be written as;
In this form, no “then” or “end if” are required. However, only one statement can be executed.
Where the <fortran statements> may include one or more valid Fortran statements.
For example, given the declaration of,
integer :: gameLives
based on the current value of gameLives is, a reasonable IF THEN ELSE statement might be:
Which will display the message “Still Alive, Keep Going!” if the value of gameLives is greater
than 0 and display the message “Extra Life Granted.” if the value of gameLives is less than or
equal to 0.
Where the <fortran statements> may include one or more valid Fortran statements.
For example, given the declaration of,
integer :: gameLives
based on the current value of gameLives is, a reasonable IF THEN ELSE IF statement might be:
Which will display the message “Still Alive, Keep Going!” if the value of gameLives is greater
than 0,
display the message “Sorry, game over.” if the value of game lives is < 0, and display the
message
“Extra Life Granted.” if the value of gameLives is equal to 0.
46
Chapter 8 ◄ Selection Statements