Week 2
Week 2
Module Introduction
This module provides introductions to the rudiments of BASIC and FORTRAN programming
language. In this module we introduce BASIC Programming; explained more programming
statements in BASIC, and introduce you to FORTRAN Language. Also covered in the module
are FORTRAN Keywords and Library Functions.
Contents
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
BASIC Variables and Characters
Reserved Words or Keywords in BASIC
4.0 Self-Assessment Exercise(s)
5.0 Conclusion
6.0 Summary
7.0 Tutor Marked Assignment
Further Readings
Introduction
This Unit is aimed at introducing you to the rudiments of BASIC language. As you
already know in the previous unit, BASIC stands for Beginner's All-purpose Symbolic
Instruction Code. The language was developed in the early 1960s by John Kemeny and
Thomas Kurtz of Dartmouth College, as a teaching language. There are many versions
of the language. Examples are:
Versions like BASICA and GW BASIC are already taken over by other versions listed
above. Visual BASIC is a version of the language specially designed for Windows
platforms and is today one of the programming tools with very high preference among
programmers. However, it is interesting to know that BASIC language remains one of
the best programming tools gaining wide acceptance even in the face of rapid
developments of various computing platforms.
For example, SmallBASIC has been designed to run on various platforms including
Windows, Linux and Pocket PC platforms. Gambas is designed for Linux operating
system, while most of the versions listed in (vi) — (xvi) are for Windows platforms and
they compete favourably with Visual Basic. Specifically, SpeedBASIC is an attempt to
create an object oriented BASIC style language, similar to Visual Basic, with its own
Integrated Development Environment (IDE). The Basic source code is converted to C++
while a compiler is used to compile and link the C++ source with libraries handling
Graphic User Interface (GUI), File I/O and etc. For example, below, is a screen shot of
KBASIC Professional, Version 1.4, released May 2006, to show you that BASIC has
worn a beautiful object oriented look and it's yet reigning alongside other programming
languages today. II
In brief, this unit will concentrate on the variables and characters employed in BASIC
programming. Since every language has its Reserved Words, this unit will also introduce
you to some BASIC reserved words that are common with most BASIC interpreters and
compilers.
Main Content
• Numeric Variables
• String Variables
NUMERIC VARIABLES
Generally, in BASIC, variable names must start with a letter and can be followed with
numbers or other letters, for example, a variable name can be as long as 40 characters (as
in MS QBasic). So, examples of variables names are Al, B3, AB4, JONH, REJ2, Y5, and
so on.
Numeric variables are simply those that represent numbers. In BASIC, such numbers can
be whole numbers, decimals, zero, positive or negative integers. In other several
programming languages, you may need to identify specifically the type of the variable,
either as REAL, INTEGER, LOGICAL, COMPLEX or CHARACTER. However,
BASIC is a more accommodating language and most versions may not bother you on
identifying the variable type.
STRING VARIABLES
Variable names are also employed to represent character data in memory. Character
variable names are similar to numeric variable names, but they refer to memory locations
containing character strings, where collections of characters are called String Variables.
To specifically distinguish a string variable, the dollar symbol $ is used at the end of the
variable name. Examples of string variable names are therefore as follows:
A$, JOHN$, B2$, REJ$, etc.
It is good for you to also know that the dollar signs $ also appears at the end of almost
every BASIC reserved word that deals with strings. Now, while the values of numeric
variables are simply numbers, the values of string variables are given as characters
enclosed between double quotes, such as "NAME", "OK", etc. the space character can
also be made as part of the string.
You may find the following points very helpful as you choose your variable names:
• Keep your variable name as short as possible since you need to type it every time
you need it in your program code (though you can copy and paste, every time).
• Select a meaningful variable name to assist you in remembering what it represents
Below, you will now see the meanings of some characters or symbols used in BASIC
language.
ALPHABETIC CHARACTERS
a — z or A — Z
NUMERIC CHARACTERS
DATA-TYPE SUFFIXES
$ String
! Single Precision
# Double Precision
% Integer
& Long Integer
MATHEMATICAL OPERATORS
You will see the use of some of the above symbols and characters in subsequent units on
BASIC in this course. In the next section, you will now be introduced to some keywords
or reserved words in BASIC
Reserved Words Or Keywords In Basic
Just as words have their meanings in the natural language, the same thing applies in
programming languages, reserved words generally describe the operations to be
performed by the computer. If your reserved words are wrongly coded, you will
definitely receive syntax error message during the running of the program. As a vital
programming rule, it is essential to avoid using any of the reserved words as a variable
name to avoid program errors during execution. Now, for your understanding, the BASIC
reserved words are grouped below according to their programming tasks.
What a long list! Yes, but you may not use most of the above keywords in your
programming lifetime! Some programmers don't even know that some of the above
keywords exist in BASIC since their program demands do not necessitate their use.
The above list of keywords simply shows you that BASIC is a very rich language in
terms of programming tools. Getting grounded in BASIC will help you a lot in studying
other object oriented versions BASIC such as Visual Basic.
Some of the reserved words as seen above appear under more than one programming
task. In the subsequent units, you will see the use of some of the commonly used
keywords in some examples.
Self-Assessment Exercise(s)
Identify the following variables as acceptable or unacceptable, giving your reason(s) if
unacceptable in BASIC.
i. ADA
ii. $x iii. TAX iv. 8BIG v. W.3
Answers
i. Acceptable
ii. Unacceptable — the dollar sign ($) must be placed after the name.
iii. Acceptable
iv. Unacceptable — a letter must begin the name and not a number.
v. Unacceptable (for common versions) — only letters and numbers are allowed in
the name.
Conclusion
This unit has introduced you to the two common types of variables used in BASIC
programming, namely:
• Numeric Variable
• String Variable
The unit also shows you the various types of characters generally employed in
BASIC. As in natural language and in other programming languages, there are specific
meanings to keywords in BASIC and the unit has provided you a very extensive list of
reserved words used in BASIC
6.0 Summary
BASIC language is still today a good language with its wide range of programming
tools for the development of a wide range of applications. Its basic knowledge is very
essential for programmers who want to quickly understand for example other object
oriented versions of BASIC such as Visual Basic, KBASIC, etc.
What you have learnt in this unit on BASIC will be employed in various examples you
will come across in subsequent units on the language in this course.
Tutor-Marked Assignments
1. State four (4) types of variables including the two types commonly
associated with BASIC programming.
2. Using the appropriate symbols, write the following expressions in BASIC code:
3. State three reserved words in BASIC that can be used under more than one
programming task
Microsoft Corporation, MS DOS Quick Basic Version 1.1, 1992. KBASIC Software
Corporation, KBASIC Professional Edition, 2006 http://www.kbasic.com
http://www.freeprogranmmingresources.com
Unit 2: STARTING WITH BASIC PROGRAMMING
Contents
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
Commonly Used BASIC Statements
BASIC Programming Environment Limits
4.0 Self-Assessment Exercise(s)
5.0 Conclusion
6.0 Summary
7.0 Tutor Marked Assignment
8.0 Further Readings
Introduction
Having been introduced to the common types of variables used in BASIC and a
summarized grouping of its reserved words, this unit is aimed at leading you gently into
BASIC programming. The unit will therefore introduce you to the most commonly used
statements you can hardly do without in BASIC code.
As already learnt in the last unit, BASIC programming has its peculiar features. For
example, you have learnt that a variable name can be as long as forty (40) characters in
BASIC programming. That simply suggests to you that BASIC Programming language
has its own environment bounds. This unit will therefore also introduce you to the limits
that characterize BASIC Programming environment before you go into in-depth
programming using the language
Main Content
The Quick BASIC program is a DOS program usually shipped with MS-DOS operating
system. Thus the program is readily available on any computer system running on fully
installed MS-DOS Version 5 for example.
As you can see in the above figure, the Interpreter is a menu-driven environment where
you can type your BASIC code and run the program immediately. With this version of
BASIC coding environment, you cannot compile your program into an executable form
as you can do in Turbo Basic environment shown below.
The Turbo Basic Interpreter or Compiler environment is as seen in the following figure
(as presented in Unit I of this Module)
As you can observe from the above figure, the environment is also menu-driven but with
available option to compile the source program into an EXEcutable file. This is shown in
the next figure below:
The editing window changes to the window when you are ready to type your BASIC
source code
Now, you will be introduced to the following very common statements:
• REM Statement
• Assignment or LET Statement
• INPUT Statement
• PRINT Statement
• GOTO Statement
• IF... THEN... ELSE Statement
• END Statement.
Before you see the forms of the above BASIC statements, it is good to state that a BASIC
statement has the following general form:
In other versions of BASIC like GW-BASIC, you must number every statement, but in
MS-QUICKBASIC or Turbo Basic, line number is optional. Line numbers are necessary
when your program contains GOTO statement(s) or GOSUB statement(s). Now, get
started with BASIC statements stated above.
REM Statement
The REM or REMark statement is simply a comment statement that provides information
about the program or any of its segments to the programmer. The REM statement
provides no information to the computer itself and hence the statement is never executed
during the execution of the program.
For example, a REM statement may explain what a variable name represents or what
program segment (or module) does. Example of a REM statement is as follows:
10 REM This program finds the average of 'two number
The above code has a REM statement broken into two lines. In line 20, the single quote
character is used in place of the reserved word REM. You may have a REM statement
without any comment just to create an empty line within the code for good readability.
Thus you may have REM statements that look like the following:
40 REM
50 REM ***************
The assignment or what is also called the LET statement is simply used to assign values
to variables. The general format is as follows:
In BASIC, the equality (=) sign is the assignment symbol. In the above general format,
the expression on the right hand side can be any of the following:
• A constant
• An Arithmetic formula
• A variable.
As you can see in the above general format, some versions of BASIC (such as MS-Quick
BASIC and Turbo Basic) do not require the reserved word LET in an assignment
statement. Hence it is optional.
Examples of assignment statements are as follows:
10 X = 25 B$ = "NOUN"
20 Y=X^2 + 3*X-4
30 N$ = B$
40 T = Y
INPUT Statement
When a computer program is designed to run many times, each time working with
different input data, an INPUT statement is necessary in the code. In using INPUT
statement, a single statement can be used for multiple variables in place of multiple
INPUT statements.
Examples of INPUT statements are as follows:
SCORE =?
The question mark (?) simply indicates that the program is requesting for an input from
the keyboard.
PRINT Statement
Very central to the output phase of any BASIC program is the PRINT statement. This is
used to display the results of computer processing. To send an output to a printer, you use
LPRINT instead of the PRINT statement.
The expression in the above statement can take the form of the following:
• Variables
• Arithmetic expressions
• Literals
• Combination of the above three types.
10 PRINT X : PRINT
20 PRINT A, B
30 ? C; D
40 PRINT ―VALUE=‖, V
50 PRINT 3* A — B
60 PRINT T$
70 PRINT "THE SOLUTION IS"
80 LPRINT W
In line 10, the second PRINT statement prints an empty line. This is necessary to provide
a good space between output lines. In line 30, the question mark (?) is used in place of the
reserved word PRINT. In QuickBasic, the symbol is automatically changed to the word
PRINT when you move out of the line to the next. When line 80 is executed, the value of
the numeric variable W is sent to the printer.
Now, you will observe that semicolon (;) is used in the PRINT statement instead of the
comma (,) symbol. These two characters give different formats to the result output of a
PRINT statement. Assuming that the values of A, B, C and D are as follows: A = 2, B =
1, C = 23, D = 0. When line 20 is executed, you will have an output like this:
2 1
230
You will observe that the values of C and D are printed immediately after the other while
the values of A and B are printed with spaces between them, specifically, there will be 14
spaces between them. Generally, BASIC divides your output screen into what are called
PRINT ZONES. There are five (5) of them, the first starting at column 1, the second at
15, the third at 29, the fourth at 43, the fifth at 57. Using semicolon in your PRINT
statement is a way of giving enough space between the printed values. However, a more
flexible way to format your output is to use the TAB function which will be introduced to
you in the next unit.
GOTO Statement
Very often, when you use an IF ... THEN statement, one condition causes the computer to
execute the next line of BASIC code whit? another condition requires it to execute some
code somewhere else if the program. Therefore, in order to move or branch to the code
that doesn't follow the IF... THEN statement, you need an unconditional branch
statement, which is the GOTO statement. That means that, every time the computer
encounters a GOTO statement, it branches to the specified program line irrespective of
any condition in the program. As you will remember, you have learnt in this course that
structured programming discourages GOTO statements.
10 CLS : INPUT A
20 IF A <3 THEN GOTO 40
30 ? : PRINT
40 END
This statement works just like IF ... THEN statement used in the above BASIC code,
except that the ELSE part is executed if the condition is not satisfied.
An example is as follows:
10 CLS
20 INPUT X
30 IF X> 0 THEN PRINT "POSITIVE" ELSE? X
40 END
END Statement
Every program has a terminal point. In BASIC, the END statement signifies the end of
the program as used in the above immediate two BASIC codes. Since line numbers are
optional in some BASIC versions, therefore an END statement can appear anywhere in
the BASIC program where the program logically ends. Some Basic versions don't even
require an END statement, such as QuickBASIC.
• Names
• Strings
• Numbers
• Arrays
• Procedures
• Files
Array Limits
Procedure and File Limits
The knowledge of the above limits is very essential as you develop programs using the
BASIC language. Some of the BASIC versions mentioned in Unit 1 of this module might
have their limits a bit varied from the above. You will now round up this unit.
.
Answer
.
For your observation, line 10 has two statements combined into one line by using the
colon (:) symbol
2. Study the following flowchart and provide the equivalent BASIC code:
Answer
7.0 Conclusion
In this unit, you have been introduced to the common statements you are going to
frequently use in BASIC programming. The most common BASIC Interpreters today
are the Microsoft QuickBasic and Turbo BASIC Interpreters with the latter having a
menu facility to compile your BASIC code into an executable file. Remember that in
Unit 1 Module 2, you were introduced to many other versions of BASIC Interpreters
and Compilers.
The Unit has introduced to you the various limits that characterize the BASIC
programming environment.
6.0 Summary
The unit having shown you some common statements in BASIC programming, you are
now ready to get started with programming in BASIC language. You were equally
introduced to the programming environments of the most two common BASIC
Interpreters, namely, the MS-QUICKBASIC and the Turbo BASIC interpreters.
As you have learnt in this unit, there are same programming limits in BASIC associated
with the following:
• Names
• Strings
• Numbers
• Arrays
• Procedures
• Files
Knowledge of these limits is very essential for your successful running of your BASIC
programs. In the next unit, you will be introduced to more BASIC statements that are not
covered in this unit
2. (a) Give the 1 — character alternatives you can use in place of the
following statements.
(b) When is GOTO statement needed in BASIC programming?
3. What do you observe from the programming environment limits for Single and
Double Precision Numbers?
Mandell, S.L., Computers and Data Processing West Publishing Company, 1985.
Contents
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
Data Entry Statements
Using Loops in BASIC
4.0 Self-Assessment Exercise(s)
5.0 Conclusion
6.0 Summary
7.0 Tutor Marked Assignment
8.0 Further Readings
Introduction
In the previous two units, you have been introduced to how to get started with BASIC
programming. Definitely, as you have seen under the reserved words in BASIC, there is
so much to learn about BASIC statements that cannot be covered in this course since
you are expected to learn some fundamental concepts in other programming languages
as well.
In this unit, you will therefore be introduced to some additional BASIC statements that
are frequently encountered, while a good number of other BASIC statements would
definitely be studied by you as you make progress in your computer programming
courses or as you are confronted with programming problems that might require their
use. If you remember what you learnt under Structured Programming, there are basically
three types of structures, namely, sequence, selection and looping structures. As you will
observe, the first two types of structures have been encountered in the last unit in the use
of some of the BASIC statements. For example, IF... THEN... ELSE statement describes
a selection structure while the sequence structure is inherent in almost all programming
statements.
Now in this unit, you will be introduced to BASIC statements that describe looping
structures. However, in the process of introducing one particular BASIC statement,
attempt would be made to also introduce you to more statements in order to cover a good
number of BASIC statements. The first part of this unit will first of all show you
additional method of entering data into BASIC programs.
Main Content
• INPUT Statement
• LET or Assignment Statement
• READ/DATA Statement.
Good enough, you have been introduced to the first two types of statements in the last
unit. You will therefore be taught in this unit the use of the READ/DATA statement as
another way of entering data into your BASIC program. Before then, see below the
general guidelines on using the three statements given above.
• Use the LET or Assignment statement when the data to be used by your program
are constant. Moreover, the LET statement is often used to assign a starting value
to a variable, such as zero. This is normally called an INITIALIZATION.
Remember that, you can simply state your assignment without the LET keyword.
• Use READ/DATA statement when you are to enter many data values. This is the
same method you use when entering data into arrays.
The READ and DATA statements always work together because values contained in the
DATA statements are usually assigned to variables listed in the READ statements. The
general format for the READ and DATA statements is as follows:
A DATA statement can have one or several data items and each of the data is known as a
Data Element. DATA statements are not executed but only provide information to the
program. Because of this, you can place a DATA statement anywhere in a program with
the corresponding READ statement.
Now examples of READ/DATA statements are as follows:
10 READ B, C, D$
20 READ X, Y
.
.
.
60 DATA 20, 40.2, "DAY"
70 DATA 60, 32.
Generally, the READ statement tells the computer to search through the BASIC program
to locate the first DATA statement. The computer then assigns your data values
consecutively to the variables in the READ statement. You will therefore see the reason
why the third value in line 60 in the above code is a string constant, because the third
variable in line 10 is a string variable.
BASIC maintains what is called Data Pointer. The pointer simply keeps track of the next
data element to be read. Thus if a READ statement is attempted after the data list has
been exhausted, a message is going to alert you that the end of the data list has been
reached. The BASIC Interpreter or Compiler takes all the data items in all the DATA
statements and forms one combined data list, ordering the DATA statements from lowest
line number to the highest and then using the data from left to right.
Now, though you have already been told that DATA statements may appear anywhere in
a program, however it is a common programming practice to group them together either
at the beginning or the end of a program. Such a practice makes program debugging
easier.
10 CLS
20 READ DS, ER, B$
30 PRINT TAB (2); DS; TAB (4); ER; TAB (8); B$
40 DATA 23, 45.5, “BIRTH =”
50 END
Do you notice any error(s) in the above code? There is no any error at all. The interesting
thing about DATA statement is that it is the only place where character strings do not
have to be enclosed within quotation marks as used in line 40 above for the string
variable (B$) value.
In the above code, attempt has been deliberately made to introduce you to the TAB
function which is normally used with PRINT statement to provide flexibility in your
output format. The general format for the TAB function statement is as follows:
TAB (expression)
where the expression in the parentheses may be a numeric constant, numeric variable or
arithmetic expression, to tell the computer the column at which printing is to start. For
example, in the above code, the computer is to tab to column 2 before printing the value
for variable DS. The semi colon after the TAB function simply instructs the computer to
start printing at the next column, i.e. column 3
line # (optional) FOR loop variable initial value TO terminal value STEP step value
.
.
.# (optional) NEXT loop variable.
In the above general format, the loop variable is also called the INDEX variable. The
STEP statement is optional but only necessary when step value is different from the
default value 1. As you have already learnt in unit 5, the step size can indicate increment
or decrement.
An example of FOR ... NEXT statement is seen below:
10 PRINT
20 FOR X = 1 TO 3 STEP 0.5
30 Y = SQR (X)
40 W = INT (X)
50 PRINT Y, W
60 NEXT X
70 END
Again, the above program has included two BASIC Library functions:
There are cases when you can have nested loops. That is, all of one loop can be within
another loop. See an example below:
10 FOR 1 = 1 TO 4
20 FOR J = 1 TO 9
30 PRINT I; J
40 NEXT J
50 NEXT 1
As you can observe above, it is customary to indent the inner loop to enhance
readability. In the nested FOR and N F XT statements as you have in the above example,
always be careful o to mix the FOR from one loop with the NEXT from another. In other
words, one loop must be completely inside another. In the above example the J loop is the
Inner Loop which is completely inside the I loop which is the Out Loop.
It is interesting for you to also know here that FOR... NEXT loops equally help you to
enter successive data items into a program instead of using the INPUT statements.
Now, below are very essential rules you should remember when using FOR... NEXT
loops.
a. The initial value must be less than or equal to the terminal value when using a
positive step value, i.e. when implementing an increment.
b. When implementing a decrement, i.e. when the step value is negative, the initial
value must be greater than or equal to the terminal value.
c. The step value should never be o, since this would result in an endless loop.
d. Transfer can be made from one statement to another within a loop. However, you
cannot make a transfer from a statement within a loop to the FOR statement.
e. The value of the index (or loop) variable should not be modified by program
statements within the loop.
f. The initial, terminal and step expressions can be made up of any numeric variable,
constant or arithmetic expression (or formula)
g. .
h. Each FOR statement must have an associated NEXT statement.
i. FOR and NEXT loops can be nested. However, the NEXT statement of the inner
loop must precede the NEXT statement of the outer loop.
It is usually valuable to be able to store many values under the same variable name.
Though these data values are not stored in the same memory locations, but they have the
same identifier. Such variable are called Subscripted Variables. But more precisely, a set
of variables with the same name and different subscripts is called an ARRAY.
By the above definition, it then means that simple variables are Unsubscripted Variables.
Usually, the BASIC interpreter or compiler is designed to assume that an array will have
no more than ten (10) or eleven (11) elements or subscripts (depending on the BASIC
version). But a programmer can specify the number of elements in an array for which
memory space must be reserved, if he needs more than 10. You can do this by using the
DIM statement or the DIMension statement, with the general format as follows:
Line # DIM variable I (limit 1), variable 2 (limit 2), variable 3 (limit 3),
...
The variables are the array names while each limit is an integer constant that represents
the maximum number of memory locations required for a particular array. You don't
actually require a DIM statement for arrays of ten or fewer elements.
As a programming rule, DIM statements must appear in a program before the first
reference to the arrays they describe, and as a good practice, you should place the DIM
statements at the beginning of your program.
As you can see above, the subscript of an array variable can be:
• a Number
• a Numeric variable c
• an Arithmetic expression.
Now, back to FOR and NEXT statements. They can be an efficient method of reading
data into an array. Look at the following example:
10 FOR T = 1 TO 9 STEP 2
20 Y (T) T + 3
30 Y (T+1) T * 3
40 NEXT
From the above code, you have the following results of processing:
10 DIM N$ (20)
20 FOR J = 1 TO 3
30 READ P(J)
40 N$(J) = "PRICE"
50 PRINT N$(J); J, P(J)
60 NEXT J : GOSUB 200
70 DATA 2.23, 4.5, 6.3
80 END
200 REM Below is a SUBROUTINE
210 PRINT "PRICES INSUFFICIENT"
220 PRINT
230 RETURN.
PRICE 1 2.23
PRICE 2 4.5
PRICE 3 6.3
PRICE INSUFFICIENT
In the above program code, you have been introduced again to another statement, namely,
the GOSUB statement which is a special case of the GOTO statement. The GOSUB
statement is specifically used to transfer control to a program SUBROUTINE, which is a
block of code that performs one task each time it is executed. When you divide your
BASIC program into sections such as subroutines, you are using a form of structured
programming which you already know is called Modular Programming. Usually, you end
a subroutine with a RETURN statement while it is a good custom to begin your
subroutine block with a REM statement as seen in the above code.
Answer
The printing will be done in the pre-defined Print Zones, ignoring the columns
specified in the TAB function expression.
2. What other expression can you use in place of the SQR function?
Answer
SQR(X) = X ^ 0.5
3. What are the two basic steps taken by the computer when it encounters a FOR
statement?
Answer
Answer
Conclusion
In this unit, you have been taken through additional BASIC statements such as:
• READ/DATA statements
• FOR.. .NEXT statements
• DIM statements.
• GOSUB...RETURN statements
• Some library function statements.
The unit has explored different ways of using some of the statements to enter data into
your program apart from the INPUT and the assignment statements treated in the
previous unit.
Specifically, this unit has also introduced you to how to implement loops by using the
FOR…NEXT statements with the associated rules when using the statements.
Summary
This unit, apart from introducing you to more BASIC statements has equally treated
the fundamental concept of an ARRAY and how it is treated in BASIC. Though the
examples shown focused mainly on One-Dimensional arrays, you can equally
encounter Two-Dimensional arrays such as matrices in your programming
assignments. Two-Dimensional arrays are simply represented as follows:
You have already learnt in this unit that the DIM statement is normally used to specify
the number of array elements. The unit has also introduced you to the GOSUB statement
which is a special case of GOTO statement.
With this unit, being the third unit dedicated to BASIC programming, you can now get
started with BASIC programming problems while the table of reserved words in unit 6
will help you to develop yourself in BASIC programming beyond what you have
covered in this course.
1. State the various types of BASIC statements you can use to enter data into your
program.
2. State an important rule to be followed when using nested loops in BASIC.
3. Identify the error(s) in the following program:
10 PRINT
20 FOR I = I TO 4 STEP -2
30 PRINT 2 *1
40 FOR J = I TO 5
50 PRINT J
60 NEXT I
70 NEXT J
Mandell, S.L., Computers and Data Processing West Publishing Company, 1985.
Contents
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
Getting Started with FORTRAN Programming
FORTRAN Variables and Constants
4.0 Self-Assessment Exercise(s)
5.0 Conclusion
6.0 Summary
7.0 Tutor Marked Assignment
Further Readings
Introduction
In this unit, you are going to be introduced to the fundamentals of FORTRAN language.
FORTRAN, as you will remember is an acronym for FORmula TRANslator which was
developed by John Backus and his team between 1953 and 1957. Since the appearance
of its first compiler in 1957, FORTRAN has undergone various revisions as follows:
• FORTRAN II - in 1958
• FORTRAN IV - in 1962
• FORTRAN 66- in 1966
• FORTRAN 77 - in 1978
• FORTRAN 90/95 - in the 90s.
FORTRAN is the first High-Level Language which was designed principally for
scientific and engineering environments. In order to favourably compete with other
programming languages which are well structured, an ANSI committee was inaugurated
in 1980 to formulate a new standard for FORTRAN. This led to the FORTRAN 90
version which incorporates all of FORTRAN 77 features and can compete well with
structured languages such as Pascal and C++. However, presently, FORTRAN 90
compiler is still uneasy to come by and so, the most commonly used compilers are still
for Fortran 77.
To start with, this unit will give you a snapshot of FORTRAN language features,
especially, some rules guiding its program coding before introducing you to descriptions
of variables and constants in FORTRAN. Your study objectives are as
Main Content
• Microsoft Fortran 77
• FORTE — Fortran Environment
• Fortransoft
• ProFortran
• WATFOR 77— Interpretive Fortran Version.
Each line of Fortran code can be typed using any ASCII (text) editor such as Microsoft
Notepad editor. However, the code lines must be entered according to the following
rules:
It is good to state here that Fortran 90 allows free form source coding, that is, there is no
restriction on where Fortran statements are to be located as specified in the above Fortran
77 rules. Moreover, a comment can be placed at the end of a statement provided an
exclamation mark (!) precedes the comment.
Before you get introduced to the Fortran variables and constants, below are the common
characters recognized by Fortran language:
FORTRAN Operators
• Arithmetic Operators
• Relational Operators
• Logical Operators.
Arithmetic Operators
+ - Addition
- - Subtraction
* - Multiplication
/ - Division
** - Exponentiation
= - Assignment.
Relational Operators
(Please, take note of the dots (.) before and after the two characters)
Logical Operators
You will start with the variables since a great deal of flexibility is gained when you allow
a quantity to be referred to by a name rather than a constant value. Generally, the major
aim of any computation is to find unknown values from known ones.
Just as in any other programming languages, variables in Fortran can be given names
consisting of several alphanumeric characters, but for most compilers of Fortran 77, the
number of characters can be as many as six, the first being a letter as in BASIC language.
In FORTRAN, there are several types of variables as follows:
• REAL
• NTEGER
• OUBLE PRECISION
• OGICAL
• COMPLEX
• CHARACTER
Among all the types of Fortran variables, the most common two are the REAL and
INTEGER types. A very peculiar characteristic of Fortran is that it assumes that the type
of a variable is implied by its spelling. The integer and real variables are identified as
follows:
The above method of specifying variable types in FORTRAN is one of the rigid rules you
find in Fortran. Care should always be taken in handling variables in FORTRAN
especially in assignment statements. Mixing of different types of variables in the same
expressions can easily lead to errors without conversion functions.
Though FORTRAN assumes the type of a variable by its first letter, it however gives you
the opportunity to change the presumed type by using declaration statements such as
follows:
INTEGER X, Y, ZERO
REAL 12, JOS, NUM.
By default, variable name ZERO for example, is a real variable since it starts with Z, but
with the above declaration statement, ZERO will be treated as an integer variable in the
statements following such declaration. As a common practice, DECLARATION
statements are usually given at the beginning of your program before the first references
to the names defined in the declaration statements.
In case you intend to have mixed-type expressions, that is expressions containing
different types of variables, you will need to use the Fortran Intrinsic functions such as
REAL and NT for real and integer expressions respectively.
B = (3/5) * (F — 32)
NUM = R *J/3
The above two FORTRAN assignment statements will definitely give you errors when
executed. The errors can be corrected as seen in the modified expressions below:
From what you can see above, it is always advisable to use decimal points in real
numbers to avoid mixed-type errors.
FORTRAN constants
The most commonly used constants in FORTRAN are the real and integer constants.
An Integer Constant is a positive, negative or zero whole number without a decimal point
or commas. Therefore, FORTRAN assumes your number having no decimal point as an
integer. Examples are 4, 32,
6932, ...
A Real Constant on the other hand is a positive, negative or zero number with a decimal
point. You can express real constants in
Just as there are several types of variables apart from the real and integer variables, there
are also other constants allowed in FORTRAN in addition to the real and integer
constants. For example, in FORTRAN, you also have the following types of constants (to
be treated later in other units):
• Complex Constants
• Logical Constants
• String Constants.
Answer
The variable NUM is an integer variable name and therefore represents a memory
location to be occupied by an integer value. Therefore, the expression on the right hand
side should be completely of an integer type.
By writing:
R *REAL (J)/3.0
the expression on the right hand side can now be assigned to NUM, which is an integer.
Another way of carrying out the conversion on the right hand side is by writing the
whole assignment as follows:
This last form of expression is simpler and may still yield the same result like the other
one but INT function is a Truncator.
2. Identify the error(s) in each of the following, if any, and attempt correcting them:
Answers
i. Variables: The variable names SAB and 62A are not Fortran valid
variable names while X4+2 is containing an operator.
ii. Assignments:
a. A = X**2 + REAL (J) **2
b. No any error
c. NAT = TNT (REAL (I) **2 I- 4.5 * REAL (J).
5.0 Conclusion
In this unit, you have been taken through the fundamental rules guiding Fortran
programming and coding. As you have learnt in this unit there are some rules to be
followed while coding your Fortran source programs. For example, column 1 is
specially reserved for character "C" to enter . your comment. This is analogous to using
REM in BASIC language. Your Fortran statements are to be entered between columns
7 and 72. However, the column rules that exist in Fortran 77 are rather non-existent in
the Fortran 90 version whose compiler is not yet widely available.
This unit has equally shown you the types of variables and constants employed by
Fortran. While emphasis has been laid on the most commonly used types, that is, the
real and integer types, you will be introduced to the other types later in the course.
6.0 Summary
As you have learnt in this unit, Fortran is very quick to assume the type of your
variable by the first letter of the variable. Every variable name that starts with I, J, K,
L, M and N is assumed to be an integer unless you change the presumed type by using
the declaration statement keyword REAL or its form of intrinsic function. Starting a
variable name with other letters is assumed that the variable is real by Fortran.
Remember that the unit also introduced you to the types of operators used in Fortran
language programming. These operators will be used in some examples in the
subsequent units. With all that you have learnt in this unit, you are now ready to start
using some simple statements in the next unit.
Contents
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
FORTRAN Reserved Words and Library Functions
Using READ, WRITE and FORMAT Statements
4.0 Self-Assessment Exercise(s)
5.0 Conclusion
6.0 Summary
7.0 Tutor Marked Assignment
8.0 Further Readings
Introduction
In this unit, you are going to be introduced to the common reserved words or keywords
available in most Fortran compilers. During your study of the BASIC language, you
have seen the need of having a good knowledge of a language's keywords since they
provide commands to the compiler of the language. The keywords or reserved words
also provide the tools needed to solve your programmable problems.
Library functions are very essential in most programming problems since they are the
same as quick methods of processing a number of program statements in a single
statement. In this unit, you are also going to be introduced to Fortran library functions.
A very simple program statement characterized by simple data entry and output of
processing will also be introduced in this unit using the common FORTRAN statements
acceptable by most compilers.
Main Content
Now, get started with learning the most frequently used Fortran Statements in the next
section.
Using READ, WRITE and FORMAT Statements
One of the most common and simple statements in programming is one that directs you
to enter some few data into the program to see some results of processing an assignment
statement. This you will see below, using the READ and WRITE statements which are
the Fortran standard INPUT and OUTPUT statements. You can also use the PRINT
ATiement in place of the WRITE statement.
Now, for, accepting data during the execution of a program, Fortran employs the READ
statement in a list directed form as follows:
READ * [, list]
Please, you should remember that the square brackets are not part of Fortran but simply
denote an optional item. That is, the comma and the list are optional.
READ*, X, Y, Z
causes the computer to request for real value data inputs from the keyboard, that is, the
STANDARD INPUT DEVICE. Remember that X, Y. 7 are assumed to represent real
numbers by Fortran. So, when entering the values, they must contain decimal points.
READ(*, *) [, list]
This form of READ statement requests for input data list from the keyboard, giving you
no specified data format. A more general form of this variant of READ statement is as
follows:
where 'unit' identifies the INPUT device from which the data list is to be read. The
parameter `f" indicates format description which is usually a number that locates the
FORMAT statement to be used. The 'unit' parameter is also a number specified in an
OPEN statement where the path and the name of the input data file is specified. Before
you see some examples, see the general forms of WRITE or PRINT statements also
below:
Now, look at the following example as shown in the two figures below, using the
WATFOR77 interpretive environment. The WATFOR 77 acts like an Interpreter and
helps you to receive immediate results of executing your FORTRAN program.
By typing 'run' or 'RUN' at the command prompt, the program gives you an input
prompt of blinking cursor to enter your data. In the above program, two real values are
requested whose sum of squares is to be assigned to Z. Entering:
X = 12.4
Y = 45.78
the result yields Z = 2249.5680000
Below, you will now see the use of FORMAT statement, which is usually used to add
flexibility to READ and WRITE statements. See this in the FORTRAN program code
below, using the WATFOR 77 program editor and interpreter.
In the above program, There are three output statements: the first prints the string:
The second prints an empty line while the third prints the values of X, Y and Z, using a
FORMAT statement in line number 2. The FORMAT statement directs the computer to
print 1 blank space before printing the first real or what is also called Floating Point
number X. The number should be of length 5 and 2 decimal places. Usually the decimal
point is part of the length. The specification is given by "F5.2".
You will observe that even though the value of X is read into the program as 12.4, but it
is finally printed as 12.40 to obey the FORMAT statement specification. You will also
see that though the value of Y is read in as 45.78, it is finally printed as 45.8 because of
the specification "F5.1" in the FORMAT statement. The value of Y is to be printed after
2 blank spaces as specified by 2X in the statement.
Below is the general format for the FORMAT specification for each of the variable
types allowed in Fortran:
i. kIm: for Integers, where k specifies the number of integer fields, each
occupying m spaces.
ii. kFl.j : for floating point or real numbers, where k specifies how many real
numbers in I space each with j decimal places.
iii. IcEl.j: for k real numbers in scientific notation each of length 1 and j
decimal places.
iv. kDI.j: for k Double Precision numbers, each of length 1 and j decimal
places.
v. kAw: for k characters of length w.
vi. nZd: for n consecutive items in a hexadecimal system, each with field
length d
vii. nOd: for n consecutive items in an Octal system, each with field length
viii. Lw: for logical value of field length w.
Look at the following example before you round up this unit.
INTEGER A, B
C Program To Calculate Average of Two
Numbers READ *, A, B
MEAN = (A +B)/2
WRITE (*,*)
PRINT 5, A,B, MEAN
5 FORMAT (11Cl2,13,14)
END.
The above program converts A and B into integer variables from their presumed real
type. Here you see that the PRINT statement is used with the FORMAT statement with
line label 5. In the FORMAT statement, A is to be printed as an integer of length 2, B of
length 3 and MEAN of length 4. To take care of the length specification, Fortran adds
blank spaces behind the values to make up for the number of spaces.
You will now round up this unit after this exercise below:
Self-Assessment Exercise(s)
State the FORTRAN equivalent keyword or symbol for the follow BASIC language
keywords and symbols:
i. REM
ii. INPUT
iii. SQR
iv. ^
v. PRINT
Answers
i) C — in the first column
ii) READ
iii) SQRT
iv) **
v) PRINT or WRITE.
5.0 Conclusion
In this unit, you have been introduced to the reserved words in Fortran and the generic
intrinsic functions. Just like BASIC language, you need to be acquainted with the
Fortran keywords to be able to use the rich resources of its programming features.
And you have seen in the list of library functions, Fortran somehow "discriminates"
between the types of the functions according to their data type. Like in variable names,
the first letter of the function name specified the type of value you should expect when
using the function. Fortran is very unique in its way of accepting input data and
producing the output of results. FORMAT statement is usually employed in
conjunction with the READ and WRITE statements to provide flexibility.
6.0 Summary
In this unit, you have really got started with Fortran programming with the introduction
to the reserved words and library functions. Get acquainted with the common keywords
to start with and you will soon discover that Fortran is not difficult to learn.
In the next unit, you will be introduced to additional Fortran keywords as employed in
some examples.
Tutor-Marked Assignments
1. State the differences between the following Fortran reserved words:
a. COMPLEX and CMPLX
b. INTEGER and INT
c. DOUBLE PRECISION and DBLE.
2. a. Classify the following functions into integer, real, complex and
double precision types:
i) DSIN ii) AMOD iii) IDIM iv) CABS
b. What are the meanings of the above functions in (a)?
3. Write a Fortran program that requests for three real numbers from the keyboard,
subtracts 48 from their sum and then divides the result by 6 before sending the
output to the screen. In the input statement, let the program use the following
specification for the three numbers: length is 8, decimal places are 3. The output
should be unformatted.