You are on page 1of 17

Computing Fundamentals – I

(0th Semester) Lab Assignment # 06


Please read the following instructions carefully.
 Study the reading material given below.
 Attempt the assignment programs given at the end of this document.
 Save your programs in your working directory …\..\g77\bin.

a. Save your programs in your assignment folder (in your Z Drive). The folder should be
named in the following manner.
Your Full Name_Your MS-ID_CF1_Lab6
e.g. Raza Ali_513912_CF1_Lab6
b. Also prepare a document in the word format. Write all the program questions and source
code you have written and also paste the screen shots of their outputs, in the document.
c. Write your full name and MS-ID in the footer of the document.
d. The document title should be “CF Lab Assignment 6”.
e. Place the completed document (with all the program codes, and their output) in
your folder.
f. Paste your folders in the path given as follows.
\\172.30.10.2\Assignments\Engineering Dept\ DNE\Awais Zahur\MS Zero\Lab 6
g. Before leaving the lab, make a backup of your codes and assignment.
h. Access this document at:
\\172.30.10.24\FacultyShare\Awais Zahur\Public\CF 2019 Zero

Important Tip:
Use as many comments in your codes as required in
order to make your programs more comprehensible.

CF – I Lab Assignment # 06 Page 1


1 Arrays
All our programs so far have required the storage of only a few values, and could therefore be
written using only a few variables. For example, the average mark program required only variables
for a mark, the total mark, the count of the marks and the average. When large numbers of values
have to be stored, it becomes impractical or impossible to use different variables for them all. If
the average mark program were rewritten to compute average marks for five subjects, we should
require five variables, say MARK1 ... MARK5 for the marks, five variables for the totals, and five
for the averages. This could be done, but the program would be rather repetitive. The situation is
even worse if, after computing the averages, the program is required to print a list showing, for
each student and subject, the student's mark and the difference between the mark and the average.
This could conceivably be done if the number of students were given in advance, but the program
would be extremely cumbersome. If the number of students is not given but determined by
counting, the task is impossible, as there is no way of knowing how many variables will be
required.
We need to store all the marks in order in a list or other structure to which we can apply a name,
and refer to individual marks by a combination of the name and a number or numbers indicating
the position of a mark in the list or structure.
In mathematics, an ordered list of n items is called a vector of dimension n. If the vector is denoted
by v, the items, usually called the components or elements of the vector, are denoted by v1, v2,
v3, ... , vn.
Fortran uses a structure similar to a vector called an array. An array A of dimension N is an
ordered list of N variables of a given type, called the elements of the array. In Fortran, the subscript
notation used for the components of a vector is not available. Instead the elements are denoted by
the name of the array followed by an integer expression in parentheses. Thus, the elements of A
are denoted by A(1), A(2),... A(N). The parenthesized expressions are called array
subscripts even though not written as such.
A subscript can be any arithmetic expression which evaluates to an integer. Thus, if A, B, and C are
arrays, the following are valid ways of writing an array element:
A(10)
B(I+4)
C(3*I+K)

CF – I Lab Assignment # 06 Page 2


1.1 Array declarations
Since an array is a list of variables, it obviously requires several words or other units of storage.
Each array must therefore be declared in a statement which tells the compiler how many units to
reserve for it. This can be done by including the array name in a type specification followed by its
dimension in parentheses. For example:

INTEGER AGE(100),NUM(25),DEG

This reserves 100 words of storage for array AGE, 25 for array NUM, and one word for the
variable DEG. All three items are of type INTEGER.

Space can also be reserved for arrays by the DIMENSION statement, which reserves storage using
a similar syntax, but includes no information about type. Thus, if this method is used, the type is
either determined by the initial letter of the array or assigned by a separate type specification.
Therefore, the equivalent to the above using a DIMENSION statement is:

INTEGER AGE,DEG
DIMENSION AGE(100),NUM(25)

(NUM is typed as INTEGER by default).

DIMENSION statements, like type specifications, are non-executable and must be placed before
the first executable statement.

When this form of declaration is used in a type or DIMENSION statement the upper and lower
bounds for the subscript are 1 and the dimension respectively. Thus, AGE in the above example
may have any subscript from 1 to 100. Arrays can also be declared to have subscripts with a lower
bound other than 1 by using a second form of declaration in which the lower and upper bounds are
given, separated by a colon. For example:

REAL C(0:20)
INTEGER ERROR(-10:10)

CF – I Lab Assignment # 06 Page 3


reserves 21 words of storage for each of the arrays C and ERROR and stipulates that the subscripts
of C range from 0 to 20 inclusive, while those of ERROR range from -10 to 10.

Although the declaration stipulates bounds for the subscript, not all compilers check that a
subscript actually lies within the bounds. For example, if NUM is declared as above to have a
subscript from 1 to 25, a reference to NUM(30) may not cause an error. The compiler may simply
use the 30th word of storage starting from the address of NUM(1) even though this is outside the
bounds of the array. This can cause unpredictable results. Care should therefore be taken to make
sure that your subscripts are within their bounds.

1.2 Use of arrays and array elements

Array elements can be used in the same way as variables, their advantage being that different
elements of an array can be referenced by using a variable as a subscript and altering its value, for
example by making it the control variable of a DO loop. This is illustrated in the following sections.

The array name without a subscript refers to the entire array and can be used only in a number of
specific ways.

1.3 Initializing an array


Values can be assigned to the elements of an array by assignment statements, e.g.

NUM(1) = 0
NUM(2) = 5
If all the elements are to have equal values, or if their values form a regular sequence, a DO loop
can be used. Thus, if NUM and DIST are arrays of dimension 5:
DO 10, I = 1,5
NUM(I) = 0
10 CONTINUE
initialises all the elements of NUM to 0, while:
DO 10, I = 1,5
DIST(I) = 1.5*I
10 CONTINUE

CF – I Lab Assignment # 06 Page 4


Assigns the values 1.5, 3.0, 4.5, 6.0 and 7.5 to DIST(1), DIST(2), DIST(3), DIST(4) and DIST(5)
respectively.
By convention, Fortran arrays are indexed from 1 and up. Thus the first number in the array is
denoted by a(1) and the last by a(20). However, you may define an arbitrary index range for your
arrays using the following syntax:
real b(0:19), weird(-162:237)
Here, b is exactly similar to a from the previous example, except the index runs from 0 through
19. weird is an array of length 237-(-162)+1 = 400.
The type of an array element can be any of the basic data types. Examples:
integer i(10)
logical aa(0:1)
double precision x(100)
Each element of an array can be thought of as a separate variable. You reference the i'th element
of array a by a(i). Here is a code segment that stores the 10 first square numbers in the array sq:

A common bug in Fortran is that the program tries to access array elements that are out of bounds
or undefined. This is the responsibility of the programmer, and the Fortran compiler will not detect
any such bugs!

1.4 Two-dimensional arrays


Matrices are very important in linear algebra. Matrices are usually represented by two-dimensional
arrays. For example, the declaration
real A(3,5)
defines a two-dimensional array of 3*5=15 real numbers. It is useful to think of the first index as
the row index, and the second as the column index. Hence we get the graphical picture:
(1,1) (1,2) (1,3) (1,4) (1,5)
(2,1) (2,2) (2,3) (2,4) (2,5)
(3,1) (3,2) (3,3) (3,4) (3,5)
Two-dimensional arrays may also have indices in an arbitrary defined range. The general syntax
for declarations is:

CF – I Lab Assignment # 06 Page 5


name (low_index1 : hi_index1, low_index2 : hi_index2)

The total size of the array is then

size = (hi_index1-low_index1+1)*(hi_index2-low_index2+1)

It is quite common in Fortran to declare arrays that are larger than the matrix we want to store.
(This is because Fortran does not have dynamic storage allocation.) This is perfectly legal.
Example:

The elements in the submatrix A(1:3,4:5) are undefined. Do not assume these elements are
initialized to zero by the compiler (some compilers will do this, but not all).

1.5 Storage format for 2-dimensional arrays


Fortran stores higher dimensional arrays as a contiguous sequence of elements. It is important to
know that 2-dimensional arrays are stored by column. So in the above example, array element (1,2)
will follow element (3,1). Then follows the rest of the second column, thereafter the third column,
and so on.
Consider again the example where we only use the upper 3 by 3 submatrix of the 3 by 5
array A(3,5). The 9 elements (of 3 by 3 matrix) will then be stored in the first nine memory
locations, while the last six are not used. This works out neatly because the leading dimension is
the same for both the array and the matrix we store in the array. However, frequently the leading
dimension of the array will be larger than the first dimension of the matrix. Then the matrix
will not be stored contiguously in memory, even if the array is contiguous. For example, suppose
the declaration was A(5,3) instead. Then there would be two "unused" memory cells between the

CF – I Lab Assignment # 06 Page 6


end of one column and the beginning of the next column (again we are assuming the matrix is 3
by 3).

1.6 Multi-dimensional arrays


Fortran 77 allows arrays of up to seven dimensions. The syntax and storage format are analogous
to the two-dimensional case, so we will not spend time on this.

Practice the given programs


Program – 01: Type the following program and understand its working.

This program declares two arrays and prints them using DO loop. As the arrays are not defined so
garbage value will be printed. Now change the program and save some numbers in arrays and then
print them.

CF – I Lab Assignment # 06 Page 7


Program – 02: Type the following program and understand its working.

This program calculates the average of numbers and print its result.
Program – 03: Type the following program and understand its working.

This program finds the maximum value from an array and print it.

CF – I Lab Assignment # 06 Page 8


2 File Opening
Files are associated with specific unit numbers using the OPEN statement. The general form of
this statement is:
OPEN (UNIT=integer-expression, control-list)
The control-list is a set of keyword/value pairs which define the characteristics of the file to be
opened. The unit number must always be given. The file name also must be given except in the
case of scratch files. Syntax of OPEN statement is as follows:
OPEN (UNIT=nn, FILE=filename, ACCESS=accesstype,
FORM=formtype, STATUS=stattype, IOSTAT=intvar,
ERR=statementlabel, BLANK=blanktype, RECL=mm)
Where,
 The UNIT= clause requires a unit number nn, which can be from zero up to some limit
imposed by the system. The unit number is associated with the file from the time it is
opened until it is closed.
 The FILE= clause requires a filename enclosed in apostrophes (this clause is not needed
if STATUS=‘SCRATCH’).
 The ACCESS= clause requires an accesstype, which can be either ‘SEQUENTIAL’ or
‘DIRECT’ (the default is ‘SEQUENTIAL’).
 The FORM= clause requires a formtype, which can be either ‘FORMATTED’ or
‘UNFORMATTED’ (the default is ‘FORMATTED’ for sequential-access files,
‘UNFORMATTED’ for direct-access files).
 The STATUS= clause requires a stattype, which can be ‘OLD’, ‘NEW’, ‘UNKNOWN’ or
‘SCRATCH’ (the default is ‘UNKNOWN’).
 The IOSTAT= clause requires an integer variable intvar, in which is stored a code number
indicating the outcome of executing the OPEN statement (the value 0 indicates success).
 The ERR= clause requires a statement label to which control branches immediately if the
file cannot be OPENed.
 The BLANK= clause requires a blanktype, which can be ‘NULL’ or ‘ZERO’. The default
is ‘NULL’.

CF – I Lab Assignment # 06 Page 9


 The RECL= clause requires an integer value specifying the length of direct-access records
(used only with ACCESS=‘DIRECT’).
The UNIT= clause is the only one always required. If the FILE= clause is not given, the filename
defaults to some system-dependent name. The default access is ‘SEQUENTIAL’, so the default
form is ‘FORMATTED’. The clauses can be listed in any order, with one condition: if the
UNIT=nn clause is listed first, the keyword UNIT= is optional. So the following are all legal.
OPEN( UNIT=23, FILE=‘MYFILE’)
OPEN( 23, FILE=‘MYFILE’)
OPEN(FILE=‘MYFILE’, UNIT=23)
But the following statement will generate error.
OPEN(FILE=‘MYFILE’, 23)
The STATUS= clause is used to specify whether we are dealing with an existing file or creating a
new one. For example, if we are OPENing an existing file to read some data from it, we would use
STATUS=‘OLD’. In this case, if the file cannot be found, FORTRAN will generate an error code
for use in the IOSTAT= clause, and we can branch to an error trap with the help of ERR= clause.

On the other hand, when writing data to a new file we want to be sure the file doesn’t already exist,
because if it does, we will overwrite the data already there. So when creating a new file with
STATUS=‘NEW’, we watch for error codes.

CF – I Lab Assignment # 06 Page 10


If we don’t care whether the file already exists, we use STATUS=‘UNKNOWN’. In this case if file
is already there, our program will make a new file of same name and old file shall be deleted
automatically.
If we specify STATUS=‘SCRATCH’, the system sets up a temporary file for use during the run.
The file is automatically given a system-dependent name and we must not specify a filename in
OPEN statement. This file evaporates when we close the unit or when the program terminates.

ENDFILE Statement
ENDFILE unit-number
Writes an end-of-file (EOF) record (one line of input/output is one record) at the current position
in a sequential file.
After an EOF record is written to the file, only the data records before EOF can be read, whether
access is sequential or direct.

3 The Close Statement


A CLOSE statement has four possible arguments: the unit number to be disconnected, an optional
clause specifying the disposition of the file being disconnected, and two error-trapping clauses.
Following is the detailed syntax:
CLOSE( UNIT=nn, STATUS=stattype, IOSTAT=intvar, ERR=statement-label )
Where nn is a unit number currently open and stattype can be ‘KEEP’ (the file is preserved after
being closed) or ‘DELETE’ (the file is deleted after being closed). The default is ‘KEEP’ for all
but ‘SCRATCH’ files.
It is an error to try to close a unit that isn’t open, or to close with STATUS=‘KEEP’ a
‘SCRATCH’ unit (such files are always deleted).
4 DIRECT-ACCESS FILES
Direct-access files, or “random-access” files as they are sometimes called, can be accessed to read
any record directly instead of reading sequentially. Once a file is opened for direct access, its
records can be written or read in any order, by specifying the record numbers. This has terrific
advantage when maintaining large data files. But in order to operate in this way, all records in the
file must be the same length – the maximum length needed for any record.

CF – I Lab Assignment # 06 Page 11


A direct-access file is created by OPENing it as a new file, specifying
ACCESS=’DIRECT’, and giving it a record length:
OPEN ( unit=nn, FILE=filename, STATUS=‘NEW’, ACCESS=‘DIRECT’,
FORM=formtype, RECL=mm)
If you forget to write FORM of a direct-access file, the default is ‘UNFORMATTED’. The record
length mm must be specified and is the maximum number of characters in one record if the file is
formatted.
Other than the change in the OPEN statement, the only other thing that is different from sequential
access is that READ and WRITE statements must specify the number of records to be accessed.
Here is a statement that reads the 27th record of a formatted direct-access file connected to unit 24,
with provision for error-checking:
READ ( 24, ‘(F5.2, I4)’, REC=27, IOSTAT=ERRCOD ) WEIGHT, MILES
Following is an example to open a file with direct-access.
OPEN ( 24, FILE=FIL, STATUS=‘OLD’, ACCESS=‘DIRECT’, IOSTAT=ERRCOD, RECL=13)

Here the record length=13 is specified.


The record length is calculated in bytes. For instance, if we have 20 characters, followed by a
real number, the record length will be 20 + 4 = 24. Since one characters occupies 1 byte and one
real number occupies 4 bytes.

CF – I Lab Assignment # 06 Page 12


Assignment
Program – 01: Write a FORTRAN program to read some numbers from the terminal, save
them in a 1-dimensional array and then print them back on the screen.

Program – 02: Modify Program – 01 to copy the content of input vector into another vector in
reverse order .i.e. 1st element of vector A shall be stored in last location of vector B. And then
display the 2nd vector.

Program – 03: Write a FORTRAN program to calculate sum of all the numbers stored in a 1-
dimensional array.

Program – 04: Write a FORTRAN program that asks user to enter 10 integers in an array and
then as output gives the largest element in the array and the index at which that element was found.

Program – 05: Write a FORTRAN program that asks the user to enter 15 integers in an array
and computes how many integers are greater than 10.

Program – 06: Write a step-wise program to calculate following parameters.

a. Write a function to calculate mean in 1-dimensional array.


b. Write a function that uses the above function and calculate variance in an array.
c. Write third function that uses above functions to calculate covariance in an array.
d. Write fourth function to calculate Correlation coefficient in X and Y using above functions.

n n n

 xi  ( xi  x )2  ( x  x )( y  y )
i i
x i 1
; var( X )  i 1
; cov( X , Y )  i 1

n n n

cov( X , Y )
 ( X ,Y ) 
var( X ) var(Y )

CF – I Lab Assignment # 06 Page 13


Program – 07: Find the parameters of Intercept and Slope by using Least Square Regression
formula as given. Take x and y arrays as input from user.
n n n
n xi yi   xi  yi
a1  i 1
n
i 1
n
i 1

n xi2  ( xi ) 2
i 1 i 1

a0  y  a1 x
Program – 08: Implement the following procedure to generate prime numbers from 1 to 100
into a program. This procedure is called “Sieve of Eratosthenes”.
Step 1: Fill an array prime[100] with numbers from 1 to 100
Step 2: Starting with the second entry in the array, set all its multiples to zero.
Step 3: Proceed to the next non-zero element and set all its multiples to zero.
Step 4: Repeat step 3 till you have set up the multiples of all the non-zero elements to zero.
Step 5: At the conclusion of step 4, all the non-zero entries left in the array would be prime
numbers, so print out these numbers.
Program – 09: Sort an array of 25 elements in ascending order using Selection Sort Algorithm.
The logic of the algorithm is given in the figure below:

i.e at the end of iteration 1, the smallest value will be at first location and at the end of 2nd
iteration the second smallest value will be at second location and so on.

CF – I Lab Assignment # 06 Page 14


Program – 10: Sort an array of 25 elements in ascending order using Bubble Sort Algorithm.
The logic of the algorithm is given in the figure below:

i.e at the end of iteration 1, the largest value will be at last location and at the end of 2nd iteration
the second largest value will be at second location and so on.
Program – 11: Write a program that reads the file ‘In.txt’ (file provided) which contains the
columns NAME, MID Marks and Final Marks. Then sort (ascending) the names and store the
result in the file ‘sorted.txt’ (as shown in figure below).

Program – 12: Read the file ‘sorted.txt’ and assign the roll numbers (serial number) to the
students and write the output as a sequential file ‘roll.txt’ with columns of Roll No., Name, Mid
and Final Marks (as shown in figure below).

CF – I Lab Assignment # 06 Page 15


Program – 13: Read the file ‘roll.txt’ and calculate the total marks of each student (mid + final)
and GPA of the student. Use following table for GPA calculation.
Total Marks GPA
Above 80 4.0
75-79 3.67
70-74 3.33
65-69 3
60-64 2.67
55-59 2.33
50-54 2.0
45-49 1.0
0-44 0.0

Create a direct access formatted output file ‘Final.txt’ having the data of Roll No., Name, Mid,
Final, Total Marks and GPA (as shown in figure below).

CF – I Lab Assignment # 06 Page 16


Program – 14: Read the entire file in RAM, get interactively the student name from the user
and apply binary search to find if the name exists or not, and display the detailed information of a
student on screen if found.
Program – 15: Take Name as input from the user and find whether the student’s record exists
in the file by reading one record at a time from the direct access file. If record found, then display
the results otherwise display “Record not found”.

CF – I Lab Assignment # 06 Page 17

You might also like