Fortran Lecture

Download as pdf or txt
Download as pdf or txt
You are on page 1of 116

FORTRAN

The first higher level language to gain widespread acceptance was FORTRAN.
It was developed at IBM (International Business Machine) by John Backus
and his team.
Fortran is a general purpose programming language, mainly intended for
mathematical computations in e.g. engineering. Fortran is an acronym for
FORmula TRANslation, and was originally capitalized as FORTRAN.
However, following the current trend to only capitalize the first letter in
acronyms, we will call it Fortran.
By convention, a Fortran version is denoted by the last two digits of the year
the standard was proposed. Thus we have:
 Fortran 66
 Fortran 77
 Fortran 90 (95)
The most common Fortran version today is still Fortran 77, although Fortran
90 is growing in popularity. Fortran 95 is a revised version of Fortran 90.
Why will we learn Fortran?
 Fortran is the dominant programming language used in
engineering applications. It is therefore important for engineering
graduates to be able to read and modify Fortran code. From time
to time, so-called experts predict that Fortran will rapidly fade in
popularity and soon become extinct. These predictions have
always failed. Fortran is the most enduring computer
programming language in history.
 Fortran is especially suited to numeric computing and scientific
computing.
 Fortran came to dominate thin area of programming early on and
has been in continual use for over half a century in
computationally intensive areas such as numerical weather
prediction, finite element analysis, computational fluid
dynamics, computational physics, and computational
chemistry.
Problem Solving Steps
The following steps which are usually identified in
the computer-aided problem-solving process are
given below:
1. Problem analysis
2. Algorithm development [(PDL), Pseudocode]
3. Program coding
4. Program compilation and execution
5. Program debugging and testing
6. Program documentation
Answer Please!
• What is an algorithm? What are the essential characteristics
and features of a good algorithm?
• What is a flow chart? List the various commonly used flow
chart symbols with their significance.
• Difference between Algorithm and flowchart.
• Draw the layout of a FORTRAN 77 coding sheet.
• Discuss the use of various columns in the FORTRAN
coding sheet.
• Explain the difference between compilation and execution.
• Briefly describe four levels of debugging or errors detected
in a program coding statement.
Algorithm Development
• Algorithm: A step by step procedure that must be
followed in solving a particular problem on computer
is called algorithm.
• Flowchart: A graphical representation of a specific
sequence of steps of an algorithm.
• Symbols: 1. Terminal 2. Input/output 3. Computation
or process 4. Flow line 5. Decision 6. Connector
7. Loop structure 8. Sub-procedure 9. Annotation
10. Replacement
Features of an algorithm:
1. Finite number of inputs
2. It terminates after a finite number of steps
3. Actions specified in each step are precise and unambiguous
4. All operations specified can be done exactly and in a finite
amount of time
5. Having one or more outputs derived from inputs

Quality of an algorithm:
1. An algorithm should be relatively fast. The number of
operations required for solving a problem should be minimal.
2. An algorithm should require minimal computer memory to
produce the required output in an acceptable amount of
time.
Programs do not execute successfully for first time, programs contain
few errors or bugs.
The programs are, therefore debugged or errors or bugs are eliminated
till programs execute successfully.

Four levels of debugging:


1. Desk- checking: Locates and corrects as many errors as possible by
open eyeing before entering into computer.
2. Compile-time errors: Errors detected during compilation a
program such as incorrect punctuations or misspelling of key
words.
3. Run-time/ execution-time error: Errors detected during
execution a program such as an attempt to divide an arithmetic
expression by zero.
4. Logical errors: Errors arise in design of an algorithm or in coding
of program, are not detected by computers.
Modular design of programs
A program module is defined as the part of a program that performs separate
function.

Parts of a program:
1. Initialization that establishes initial values for some variables, prints
headings, messages.
2. Input that performs input of data required by the program.
3. Validation that performs validation of input data to detect errors or omissions.
4. Processing that performs computation or data manipulation.
5. Output that performs output of data to be provided by program.
6. Error handling that performs analysis of error condition and outputs error
messages.
7. Closing procedure that performs procedures to end the execution of the
program.
Structure of program
1. Sequential Structure consists of
- one action followed by another
- perform operation A and then B and so on.
REAL A, B
READ*, A, B
SUM=A+B
AVG=SUM/2
PRINT*, SUM, AVG
STOP
END
2. Selective structure: It consists of a test for a
condition followed by two or more alternative paths
for the program to follow. The program selects one
of the paths depending on the test of the condition.

3. Repetitive or Iterative structure: In the


repetitive structure, an operation or a set of
operations is repeated as long as some condition is
satisfied.
Sequential structure
Five ForTran statements sufficient to write
simple but complete Fortran programs:
1. Assignment statement

2. List directed input statement

3. List directed output statement

4. STOP statement

5. END statement
6.3 Assignment statement
--Assigns the value of expressions to variable
Variable = expression

Where, expression: --a constant


--another variable to which
a value has previously been
assigned
--a formula which the computer
can evaluate

A=B → assigns the value of B to A, B=A assigns the


value of A to B.
Assignment to numeric variables
Suppose, A : real variable
N: integer variable =5
A= 2*N/4 (integer expression)
= 2*5/4
=10/4
=2.5 → 2.5 assigns the real constant 2.5 to A

M: integer variable
M= 2.21 → 2 assigns the integer constant 2 to M

Mixed mode operation:


M= 2 * 3.0/4 = 2.0*3.0/4.0=6.0/4.0=1.5 →1
If a real expression is assigned to an integer
variable , the fractional part is truncated and the
integer part is assigned to the variable.
X= 7.41, I= 3.1416, J= X/3.0, K= 1.0/3.0 +
1.0/3.0
Results are X= 7.41, I=3, J= 2, K=0
Valid ForTran assignment statements:
15=N
X+4.3=3.14
N=4//7
A=B=1
6.4.1 List directed input statement

READ*, v1,v2,v3………….vn
Where, v1→ a variable name that refers to the first input
data item

6.4.2 List directed output statement

PRINT*, v1,v2,v3………….vn
Where, v1→ a variable name that refers to the first output
data item
PRINT*, ‘sum=’, s

6.5 STOP: Stops execution of the program


6.6 END: The last statement in a program
ForTran provides two types of input/output statements
Formatted: programmer must specify the format in which the data is input or
in case of output, the format in which it is to be displayed.
Unformatted/List directed/Format free: Predetermined formats which match
the types of data in input/ output list.

Card-oriented mode of operation: Input data is entered on data cards. The


order of the variable names in READ statement must correspond to the order in
which the data values appear in the data card. When a READ statement is
encountered, the values from data cards will be retrieved automatically and
assigned to the variables.

Interactive mode of operation: values assigned to variables in the READ


statement are entered from terminal. When a READ statement is encountered,
program execution remains suspended until terminal operator enters values for
all the variables in the READ statement.
First data card: ‘ANIL’ READ*, NAME, DEPTNO, RATE, HOURS, REGULAR
Second data card: 111 NAME= ANIL, DEPTNO=111, RATE= 10.0, HOURS= 40.5
Third data card: 10.0 REGULAR=.TRUE.
Fourth data card: 40.5
Fifth data card: .TRUE.

READ*, NAME
READ*, DEPTNO
READ*, RATE
READ*, HOURS
READ*, REGULAR

First data card: ‘ANIL’, 111, 10.0, 40.5, .TRUE.


NAME= ‘ANIL’
First data card: 11 22 3.3 4.4
Second data card: 5.5 6.6 77
Third data card: 88 99 2.34
Fourth data card: 5.67 8.90 123 456

(1)READ*, J, K, A , B, C *ANS: J=11, K=22, A=3.3, B= 4.4, C=


5.5
(2)READ*, L, M, X, Y * ANS: L= 88, M=99, X=2.34, Y= 5.67

(1)READ*, J, K, A *ANS: J=11, K=22, A=3.3


(2) READ*, B, C, L, M *ANS: B=5.5, C= 6.6, L= 77, M= 88
(3)READ*, X, Y *ANS: X=5.67, Y=8.90
Difference between STOP and END statement
Selective Structure (Chapter 7)
---The program selects one of the alternative paths
depending on the test of the condition
Relational Expression: Character strings are connected by relational
operator that defines the nature of relation or condition to be tested.
Six relational operator in Fortran. .LT. , .LE. , .EQ. , .NE. , .GT. , .GE.

Relational In Fortran Meaning


operator
.LT. A.LT.B A is less than B
.LE. A.LE.B A is less than or equal B
.EQ. A.EQ.B A is equal to B
.NE. A.NE.B A is not equal to B
.GT. A.GT.B A is greater than B
.GE. A.GE.B A is greater than or equal to B
7.1 Relational expressions
 The value of a relational expression is one of the
logical values .TRUE. Or .FALSE.
 All relational operator have equal precedence.

 Number comparisons
Assume
X+5 .GT. M*Y X=20.0
→ 20.0 + 5.0 .GT. 5.0 * 4.0 Y=4.0
M=5.0
→ 25.0 .GT. 20.0
The value of the relational expressions is .TRUE.

Table 7.1
Character comparison:
‘computer’ .GT. ‘compute’ ‘computer’ .GT. ‘compute$’ is
.TRUE.
‘WINK’ .EQ. ‘WINK’ .TRUE.
‘WINK’ .EQ. ‘WIN’ .FALSE.
‘WINK’ .EQ. ‘WINK$$’ .TRUE.
‘WINK’ .EQ. ‘WINKLE’ .FALSE.

Logical Expression: A logical constant, logical


variable or a relational expression. Logical operators
used are .AND. , .OR. , .NOT. , .EQV. , .NEQV.
Symbol Expression Meaning Logical value

.NOT. .NOT. A Negation .TRUE. If and only if A is .FALSE.

.AND. A. AND. B Conjunction .TRUE. If and only if A and B are


both .TRUE.
.OR. A. OR. B Disjunction .TURE. If and only if at least one of
A and B is .TRUE.

.EQV. A. EQV. B Equivalence .TRUE. If and only if A and B are


both .TRUE. Or both are .FALSE.

.NEQV. A. NEQV. B Non .TRUE. If and only if one of A or B


Equivalence is .TURE. And the other is .FALSE.
TRUTH TABLE
A .NOT. A

.TRUE. .FALSE.

.FALSE. .TRUE.
A B A. AND. B A. OR. B A. EQV. B A. NEQV.
B

T T T T T F

T F F T F T

F T F T F T

F F F F T F
7.2 Logical expression: Table 7.3, 7.4
7.3 precedence of relational and logical operations
Arithmetic>Relational>Logical
.NOT.> .AND.> .OR.> .EQV.> .NEQV

Assume, A=5.0, B=3.0, C=2.0


A .LT. B .OR. A*C .GT. B
= 5.0 .LT. 3.0 .OR. 5.0*2.0 .GT. 3.0
= 5.0 .LT. 3.0 .OR. 10.0 .GT. 3.0
= .FALSE. .OR. 10.0 .GT. 3.0
Operations having
= .FALSE. .OR. .TRUE. same precedence,
= .TRUE. will be executed
from left to right .
A=3.0, B=4.1, C=11
A.GT. B HAS THE VALUE OF
.FALSE.
A.EQ. B HAS THE VALUE OF
.FALSE.
B. NE. C HAS THE VALUE OF
.TRUE.
A.GT.B .AND.(A.LE.C.OR.B.NE.C).OR.NOT.(A.EQ.B)

IF, A=3.0, B=4.1, C=12.5

(.FALSE.) .AND. ((.TRUE.) .OR. (.TRUE.)).OR.


.NOT.(.FALSE.)

(.FALSE.) .AND. (.TRUE.) .OR. .NOT. (.FALSE.)

(.FALSE.) .AND. (.TRUE.) .OR. (.TRUE.)

(.FALSE.) .OR. (.TRUE.)

( .TRUE.)
NEGATION
Relational operator Negated operator
.EQ. .NE.
.NE. .EQ.
.GT. .LE.
.GE. .LT.
.LT. .GE.
.LE. .GT.
7.5 GOTO STATEMENT

1. The unconditional/assigned GOTO


statements
GOTO n
where, n= statement number of an executable
statement

2. Computed/conditional GOTO statement


GOTO (n1,n2,…..ni), integer expression

GOTO (10, 20, 30) M, N


7.6 THE IF STATEMENT

Three forms of IF statement


 Logical IF
 Block IF
 Arithmetic IF
Logical IF statement
IF (logical expression) statement
 IF (A .LT. B) PRINT*,A

If the value of logical


expression is determined
and if it is TRUE, the
designated statement is
executed.
P-118 A program which read two integer values from
the input and print the larger of the two values.

Program using logical IF:

INTEGER V1,V2, LARGER

READ*,V1,V2

LARGER=VI

IF(V2.GT.V1) LARGER=V2

PRINT*, LARGER

STOP

END
7.6.2 BLOCK IF STATEMENT

IF (logical expression) THEN


statement-1
statement-2 statement set 1
Flowchart: Fig:
…… 7.3

ELSE
statement-3
statement-4 statement set 2
…….
ENDIF
A program which read two integer values from the input and print
the larger of the two values.

Program using Block IF


INTEGER V1,V2, LARGER
READ*,V1,V2
IF(V1 .GT. V2) THEN
LARGER=V1
ELSE
LARGER=V2
ENDIF
PRINT*, LARGER
STOP
END
7.6.3 Arithmetic IF Statement
IF (arithmetic expression) S1, S2, S3
-
0 Compare two equal and unequal numbers
+ Program using arithmetic IF
INTEGER V1,V2, LARGER
READ*,V1,V2
Arithmetic IF causes transfer
of control depending on the IF(V1 - V2) 10, 20, 30
value of arithmetic expression.
10 PRINT*, ‘LARGER IS’, V2
STOP
20 PRINT*, ‘TWO NUMBERS ARE EQUAL’
STOP
30 PRINT*, ‘LARGER IS’, V1
STOP
END
NESTED BLOCK IF STRUCTURE
-ONE BLOCK IF INTO ANOTHER BLOCK IF

IF (logical expression) THEN


statement SET-1

ELSE

IF (logical expression) THEN


statement SET-2
ELSE
statement SET-3
ENDIF

statement SET-4

ENDIF
Compare two equal and unequal numbers
using nested block IF
INTEGER V1,V2,LARGER
READ*,V1,V2

IF(V1 .GT. V2) THEN


PRINT*, ‘LARGER IS’, V1

ELSE

IF(V2 .GT. V1) THEN


PRINT*, ‘LARGER IS’, V2
ELSE
PRINT*, ‘TWO NUMBERS ARE EQUAL’
ENDIF

ENDIF

STOP
END
MULTI ALTERNATIVE SELECTIVE STRUCTURE
Block IF statement using an ELSE IF
IF (logical expression 1) THEN
statement SET-1
ELSEIF (logical expression 2) THEN
statement SET-2
ELSEIF (logical expression 3) THEN
statement SET-3
…..
….
ELSE
statement SET N
ENDIF
Compare two equal and unequal numbers
Program using Block IF with ELSEIF
READ*,V1,V2

IF (V1 .GT. V2) THEN


PRINT*, ‘LARGER IS’, V1

ELSEIF (V2 .GT. V1) THEN


PRINT*, ‘LARGER IS’, V2
ELSE
PRINT*, ‘TWO NUMBERS ARE EQUAL’

ENDIF

STOP
END
Practice Program

Prob: 1
Prob:
Solution
REAL LOAN, INTS
READ*, LOAN

IF(LOAN .LE. 5000.0) THEN


INTS = LOAN*0.0875 Practice using logical IF
ELSE statement, and
INTS = LOAN*0.125 Arithmetic IF statement
ENDIF

PRINT*, ‘Interest of loan = ‘, INTS


STOP
END
Practice Program

Prob: 2
Prob:
Solution
READ*, X
IF(X .LE. 0.0) FX=-X
IF((X .GT. 0.0) .AND. (X .LT. 1.0))FX= X
IF(X .GE. 1.0) FX=1.0-X
PRINT*, ‘F(X)=‘, FX
STOP
END
Practice Program
 Prob: 3
Suppose the health insurance premium (P) is deducts
from an employee’s salary according to the following
rule.
P = 10.0 if TYPE = 1
P = 15.0 if TYPE = 2
P = 25.0 if TYPE = 3
Write a FORTRAN program, which will read pay, type
and ID and calculate net = pay – P, which is a real
variable, the output will show employee’s ID and NET
amount.
[Use logical IF statement, Arithmetic IF statement,
Computed GOTO statement]
Repetitive structure/Iterative
structure/Program Loop- Ch. 8
A set of program statements Entry Point
are executed many times and
initialization
while having that set of
program statements appear
only once in the program. Body of the
repetition
(loop)

 Using DO statement Exit point


 Using IF and GOTO statement
IF AND GOTO STATEMENT
• Problem: Input and add two
100 READ*, A, B numbers 50 times also draw
SUM=A+B
PRINT*,SUM
flowchart.
GOTO 100 Program:
STOP ICOUNT=1
END
100 IF (ICOUNT.GT.50) GOTO 99
100 READ*, A, B READ*, A,B
IF(A.LE.0.AND.B.LE.0) GOTO 99 SUM=A+B
SUM=A+B PRINT*, SUM
PRINT*,SUM ICOUNT=ICOUNT+1
GOTO 100
99 STOP
GOTO 100
END 99 STOP
END
Using IF And GOTO Statement

Self study: Topics 8.1 Example 8.1, 8.2


All flowcharts

DO LOOP: Fortran has capabilities for handling


counter-controlled repetitive structures or program
loop by a single statement called DO statement. Such a
program loop is called DO LOOP.
8.2.1 The DO statement

Starting Terminal
value of u value of u

Reference No. Increment


(statement label) parameter
of the terminal DO control
statement, in the variable
loop
8.2.4 Flowchart of the DO loop

DO 10 I = 1, 5

Body of the
DO Loop
DO 40 k = 10, 1, -1
N=?
10
Statements Comment
1. DO 10 I=1,5 VALID

2. DO 10 I=1,10,1 ?

3. DO 10 I= 4.0, 10.0, 0.2 ?

4. DO 10 I= -10, 10, 4 ?
5. DO 10 I= -10, -20, -3 ?
6. DO 10 I= M, M+N, K ?

7. DO 10, I= -10, 10, 4 ?


Terminal statement of DO LOOP: Continue statement is used as the
terminal Statement of DO LOOP. The continue statement has no effect other than to
act as a place to attach a statement label.
S CONTINUE
Where s is the reference number of the terminal statement specified in the DO
LOOP.

Execution of a DO LOOP:
1. If the computed execution number N is a real number, it is
truncated to nearest integer. (If N is 9.9, then N=9)
2. If N<= 0, DO LOOP is not executed
3. If N>0, initial value of DO control variable u is set to us.
4. The steps 5 through 6 are repeated N times.
5. All statements beginning immediately after DO statement upto,
and including, the statement whose reference number is s are
executed.
6. u= u + ui
7. The statement continues
Program: Read and print sum 50 times
Program:
DO 100 ICOUNT=1, 50, 1
READ*, A,B
SUM=A+B
PRINT*, SUM
100 CONTINUE
STOP
END
NESTED DO LOOP:
1. Several DO loops can be executed within same
program, they follow one another.
2. There is no specified limit to the number of DO
loops that can be nested.
3. When nesting one DO loop inside another, the inner
loop must be contained within the range of outer loop
4. There must be no overlapping of statements, each
loop must have its own unique control variable,
5. The loops have same terminal statement to provide a
clear style.
8.3 NESTED DO LOOP

DO 30 V1 ……

Outer loop DO 20 V2……


DO 10 V3 …..
Middle loop Inner Loop
10 CONTINUE
20 CONTINUE
30 CONTINUE

Innermost loop is executed first, then the next……


Execution of Nested DO Loops

INTEGER CAPITAL, RATE, YEAR


REAL INTRST
DO 30 CAPITAL= 1000, 10000, 1000
DO 20 RATE= 10, 15
DO 10 YEAR= 1, 3
INTEREST= CAPITAL*(RATE/100.0)* YEAR
PRINT*, CAPITAL, RATE, YEAR, INTEREST
10 CONTINUE
20 CONTINUE
30 CONTINUE
STOP
END
EX-3: Three positive integer a, b, c where a<b<c form a
Pythagorean triplet if a*a + b*b=c*c (for example 3,4,5). Write a
program that generates all Pythagorean triplets a, b, c where a, b<=25.
Solution: INTEGER FINAL, A,B,C, CSQR
FINAL=25
DO 10 A=1, FINAL-1
DO 20 B= A+1, FINAL
CSQR= A*A+B*B (A**2+B**2)
C= INT(SQRT(REAL(CSQR)))
IF(C*C.EQ.CSQR) PRINT*,A,B,C
20 CONTINUE
10 CONTINUE
STOP
END Flowchart (page 168)

Self study: Example (2, 3, 4) (Flowchart + Coding)


Page: 158, 160, 162
Problem 01: Write a Fortran program to find the sum of
series
1+2+3+……………+N 1+3+5+……………+99
Program:
INTEGER SUM Program:
PRINT*, ENTER NUMBER integer sum
READ*, N sum=0
SUM=0
DO 12 K=1, N do 7 k=1,99,2
SUM =SUM+ K sum =sum + k
12 CONTINUE 7 continue
PRINT*,‘SUM=',SUM
STOP print*,'sum=',sum
END stop
end
Problem 02: Write a Fortran program to find the sum of
series

12+22+32+……………+N2
Program:
integer sum
read*, n
sum=0
do 200 k=1,n
sum =sum + k**2
200 continue
print*,'sum=', sum
stop
end
Problem 03: Write an algorithm and draw a flowchart to
find the sum of series and implement it into FORTRAN.

 1+3+32+……upto 20
terms
Program:
integer sum
sum=0
do 100 k = 0, 19
sum = sum + 3**k
100 continue
print*,'sum=',sum
stop
end

 1+3+5+……………+ (2N-1)
Problem 04: Write an algorithm and draw a flowchart to
find the sum of series and implement it into FORTRAN.

1-2+3-……………-100 2+4+6+……………+2N
Program: Program:
integer sum integer sum
sum=0 read*, n
j=1
sum=0
do 12 k = 1, 100
sum = sum + j*k do 7 i = 1, n, 1
j = -j sum =sum + 2 * i
12 continue 7 continue
print*,'sum=',sum print*,'sum=',sum
stop stop
end end
Problem 05: Write an algorithm and draw a flowchart to
find the sum of series and implement it into FORTRAN.

1 + x + x2 +……………+ xk
Program:
integer sum
read*, k, x
sum=0
do 12 i = 0, k
sum = sum + x**i
12 continue
print*,'sum=', sum
stop
end
Problem 06: Write an algorithm and draw a flowchart to find the
product of series and implement it into FORTRAN.

Problem: Write an algorithm and draw a flowchart to print the


positive odd numbers less than 100, compute their sum and
implement it into FORTRAN.
Format-Directed Input and Output
Chapter-10
It is desired to have a complete control over printed
output or to process data which has not been dealt
with in list-directed or format free or unformatted
Input/output system as a guiding influence, or to
input data in a predetermined form.

In format-directed instructions, requires a pair


of statements:
1. Input/output statement
2. FORMAT statement
I/O Statements Explanatory Remarks

Read values for X, Y, M in that


READ (5, 710) X, Y, M order from unit 5 using
FORMAT statement number 710

Writes values for X, Y, M in that


WRITE (6, 810) X, Y, M order from unit 6 using
FORMAT statement number 810

Read values for X, Y, M in that


READ (NREAD, 720) X, Y, M order from unit NREAD using
FORMAT statement number 720
For Format directed input/output
Unit- designation form Name-designation form

READ (5, 710) X, Y, M READ 710, X, Y, M


WRITE (6, 810) X, Y ,M PRINT 810, X, Y, M

For List directed input/output


Unit- designation form Name-designation
form

READ (5, *) X, Y, M READ*, X, Y, M


WRITE(6, *) X, Y ,M PRINT*, X, Y, M
Format-Directed Input and Output

1. There are two basic input/output statements


READ (u, fs) list
WRITE (u, fs) list

Unit number assigned


to input/output device Format statement
List of variable
label numbers
names
FORMAT STATEMENT: The format statement specifies the
form of data being read or written. It can be used for more than
one input/output statements. The format statement can be written
anywhere before or after the input/output statements but is
usually placed immediately after the first input/output statements
referencing it.

The format statement consists of the statement number, the


word FORMAT and then the sets of specifications separated by
commas
10.2 Format statement
Statement number FORMAT (sets of specifications)

Edit descriptor Field size Decimal location


Specify type of (w) (d)
data Maximum Number of
Real data: F number of places from the
Exponent data: E character right of the field
Integer data: I position
Character data: A
Logical data: L Format specification
Fw.d
Ew.d
F 10 . 2 Iw
Aw
I (Integer) – format output specification Iw
Rules: 1. The integer value is displayed right justified
2. For a negative quantity, a minus sign is printed but the plus sign
is not printed for a positive quantity
3. If the field size is too small for the integer value, the output for
the field consists of *** to indicate the overflow error
.
Specification Data Output
I3 123 123

I5 123 $$123
I5 -1234 -1234
I5 1234 $1234

I3 1234 ***
I3 -123 ***
10.3 Format-Directed Output
I – format output specification Iw

WRITE (6, 800) X, Y, Z


800 FORMAT (I8, I5, I6)
Where, X = -234
Y = -12
Z = 324

OUTPUT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
- 2 3 4 - 1 2 3 2 4

X Y Z
F (Real) – format output specification Fw.d

Where, F is the edit descriptor specifying the data is of real (floating)


type, w an integer indicating the field size, d the decimal point
location expressed as the number of places from right of the field.
1. The real value is right justified. The integer digits are positioned to
left of the decimal point and the fractional part to the right.
2. If digits in integer part don’t fill all available positions to the left
of decimal point, the unused portions are filled with blanks. If
fractional part don’t fill all available positions to the right of
decimal point, the remaining positions are filled with zeros.
3. If the digits in integer portion exceeds the available field size, the
output consists of ** to indicate overflow error, if fractional part
exceeds fractional field size, the excess digits are truncated after
rounding.
Specification Data Output
F10.3 123456.789 123456.789

F10.2 45.89 $$$$$45.89

F10.5 8734.65 8734.65000

F10.4 8734.65 $8734.6500

F10.6 8734.65 **********

F10.6 -45.89 -45.890000

F10.7 -45.89 **********


10.3 Format-Directed Output
F – format output specification Fw.d

WRITE (6,700) A, B, C
700 FORMAT (F8.2, F8.4, I3)
Where, A = 2.136
B = -3.124
C = 21

OUTPUT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
2 . 1 4 - 3 . 1 2 4 0 2 1

A B C
10.3.3 E – format output specification (Self study)
10.8 Horizontal positioning specifications
Controls horizontal spacing between data items.

1. nX specification, which causes n positions to


be skipped
2. Tn specification, which positions the input or
output device at the nth position.
10.8 Horizontal positioning specifications

WRITE (6 ,20) N, Y
20 FORMAT (4X, I3, T10, F5.1)
Where, N = 123
Y = 9876

OUTPUT

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
1 2 3 9 8 7 . 6

4X I3 F5.1
T10
10.8 Horizontal positioning specifications

READ (5, 10) M, N


10 FORMAT (T5, I5, 4X, F6.3)

INPUT DATA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

M=? N=?
Chapter 11
Subprograms
A subprogram is a separate program unit used
(called) by a main program, or by other
subprogram.
 Advantage
 ‘A subprogram is complete and independent’-
explain (11.1.3)
Classification of subprograms
1. Function subprogram
2. Subroutine subprogram
Purpose and use of subprogram: 1. Repetition: Used to avoid rewriting the same
sequence of code at two or more locations in a program.
2. Universal use: some procedures might be needed in more than one program. By
writing a subprogram and making it available to others who need it, the duplication
of effort can be avoided.
3. Modularity: A program for complex problems can be developed in modular
fashion by designing individual modules or subprograms.
4. Team work: Programming is done by programing team. If the problem is divided
into subprograms, each subprograms can be written by one or two members of the
team.

Terminology: All programs we have written so far is called main program, they
are not invoked by any other program. The subprogram can not be run by
themselves, they are only run when main program invokes or calls them by
including a statement “CALL”
Main program is generally reserved for program which is not invoked by any other
program.
Calling program and called program are frequently used in place of main
program and subprogram.
Communication and argument: Most of the communication between calling and
called program takes place through different parameters and different arguments.
Function subprogram: Returns a single value to program where it is invoked.
Also required to write subprograms that return more than one value.
Subroutine subprogram: used in such a situation and invoked by a CALL
statement that contains the subroutine name.

Library function: Also called intrinsic or built-in functions are special,


independent program modules, usually supplied by computer manufacturers to
enable the programmers to incorporate some very common computations easily
into a program.
For example:
A= MAX(X, Y, Z) L= MIN(5, M, N/3)
Statement function: It may be necessary at several points to evaluate
some expression in a program that is not given by Fortran library
functions. It may be possible to implement this operation as a statement
function.
Name= (X1, X2……)= expression where expression may contain
variables, constants etc…….

HYPO (X, Y)= SQRT(X**2+Y**2) defines a real valued function.


NUMBER(M, N, A)= M*INT(A)-N/INT(A)

The name used for arguments in function statement may also be used
elsewhere in the same program, otherwise the arguments used to define
a function are dummy.
POLY(X, Y)= X*X+X*Y+Y*Y
X= POLY(B, A)- B**2- A**2
Y= POLY( X+4, X-4)
Statement function
Dummy Argument

NAME (A, B, J) = Arithmetic expression


Example 1
Statement function name

Statement function B (A, C) = SQRT (A**2 + C **2)


READ*, X, Y
R = B(X, Y) + 5*X*Y
B (X, Y) = SQRT (X**2 + Y**2)
PRINT*, R, B (X,Y)
STOP
END
Function subprogram: A function subprogram begins with function, naming,
statement of the form.
General form
Symbolic name of the function Dummy arguments

FUNCTION name (X1, X2,…….., XN)


Name = arithmetic expression
RETURN
END

Example 2

READ*, P, Q FUNCTION SQRE (X, Y)


SUM = SQRE (P, Q) + 2*P*Q SQRE = X**2 + Y ** 2
PRINT*, SUM RETURN
STOP END
END
SUBROUTINE: It has a very similar form to that of function subprogram
begins with an identifying statement called SUBROUTINE statement
SUBROUTINE name (X1, X2,…..XN)
………… 11.3.1(self study)
CALL statement.
RETURN
END
Corresponding to the
dummy arguments
11.3.1 Call statement Actual argument
X1, X2, ….XN of the
CALL S (a1, a2,…..an) subroutine

Example 3
SUBROUTINE CALC (A, B, SUM,, PROD)
READ*, X, Y
SUM = A + B
CALL CALC (X, Y, SUM, PROD)
PROD = A* B
PRINT*, SUM, PROD
RETURN
STOP
END
END

10.11 Difference between function subprogram and subroutine subprogram.


MAIN PROGRAM
REAL X, Y, SUM, PROD
COMMON X, Y, SUM, PROD
READ*, X, Y
CALL CALC
PRINT*, SUM, PROD
STOP
END

SUBROUTINE CALC
REAL A, B, PLUS, PROD
PLUS= A+B
PROD= A*B
RETURN
END
Problem 01: Write a FORTRAN program to compute the
binomial co-efficient (nCr) defined as n!/(r!(n-r)!) by using a user
defined function subprogram FACT(X) where X is integer.

Program:

MAIN PROGRAM
READ*, N, R
FACT (N, R, (N-R))
NCR = FACT (N)/ (FACT (R) * FACT (N-R))
PRINT*, NCR
STOP
END

FUNCTION SUBPROGRAM
FUNCTION FACT (X)
FACT = 1
DO 10 I = 1, X
FACT = FACT * I
10 CONTINUE
RETURN
END
Problem 02: Write a function subprogram to calculate area
of a triangle, where a, b, c are the three sides of the
triangle.
FUCTION AREA (A, B, C)
P=A+B+C
S=P/2
AREA=SQRT(S*(S-A)*(S-B)*(S-C))
RETURN
END

MAIN PROGRAM
PRINT*,’ENTER THREE SIDES OF THE TRIANGLE’
READ*,X, Y, Z
TAREA=AREA(X, Y, Z)
PRINT*,’TAREA=’, TAREA
STOP
END
Problem 03: Write a subroutine subprogram to find largest
of three numbers and sum of the numbers.

SUBROUTINE RESULT (A, B, C, LARGE, SUM)


INTEGER A, B, C, SUM
SUM=A+B+C
LARGE=A
IF(LARGE.LT.B) THEN LARGE=B
IF(LARGE.LT.C) THEN LARGE=C
RETURN
END

MAIN PROGRAM
INTEGER SUM
READ*, X, Y, Z
CALL RESULT (X, Y, Z, LARGE, SUM)
PRINT*,’SUM=’, SUM
PRINT*,’LARGE=’,LARGE
STOP
END
Subscripted Variables (Chapter-09)
A single memory location can store COST = 4.00
only one value at a time. SUM = 10.00

Do 100 data need 100 variables?


So use subscripted variable/Array to store list of
data, all of the same type.

9.2 Array:
A collection of values, or data, that are related in some
way can often be processed conveniently by storing the
data items in consecutive memory locations, each of
which can be accessed directly.
Subscript Notation: Test score of 100 students using the subscript
notation as
score1, score2, score3…………………………score100 where s is
single group name for all students, subscript (1,2,3…..100)
identifies the test score, score1 is the score of 1th student, score10
is the score of 10th student and so on…..subscript also can be
written as score(1), score(2)………….

Subscript Variable: The variable name, so obtained, representing


individual item of data in an array is called Subscript Variable
name simply Subscript Variable.
Arrays, whose variables are specified by
(1). One subscript, single subscript called linear or one-dimensional
array.
(2). Two subscript, two-dimensional array.
(3). Three subscript, three-dimensional array.
1 41
Class test score of ME 181
2 97 1 2 3 4

3 91

4 89
s

5 37
Score(3,4)
6 53

7 48

Score(5,2)
8 76

Two-dimensional array score


One-dimensional array score Three-dimensional array score (180,4,5)?
Some examples of array names:

Array Comment
Names
A(5) Valid, 5th element of array A

A(NAME) Valid, Name is an integer variable, value of name must


be known before to locate the element.
A(2,4) Valid

A(M,3) Valid

A(7*2, 6) ?

A(N+2,6) ?

A(M,N,B)? A(X)? B(N,Y)?


9.3 Dimension statement
Arrays are declared, like variables, in type statements
which is called as DIMENSION statement.

DIMENSION list
Where list is a sequence of array declarations of the
form.
Array name(m1:n1, m2:n2,….., mk:nk)
Subscripted
DIMENSION score(100) variable
Array declaration: 1. The number of dimension can be at most 7, each pair
(m, n) of integer constants, usually called parameters.
2. Minimum value of subscript with colon need not be specified, if minimum
value is 1
DIMENSION TEST (1:10) , DIMENSION RESULT (10) , DIMENSION TEST
(1:5, 1:4)
DIMENSION TEST (5:4), DIMENSION SCORE (1:30, 31:60, 61:100)
DIMENSION RESULT (10) TEST (5:4) SCORE (1:30, 31:60, 61:100)

DIMENSION statement only provides instructions to compiler to reserve


specified number of locations in memory for the element in array being
declared.
9.3 Dimension statement
DIMENSION score(100)
Address: Score 1 -15 Print*, score (2)
Score 2 20 Output: 20
……..
Address:
DIMENSION pay(2,3) pay (1,1), pay(1,2), pay (1,3),
[2 subscripts and 2 rows 3 columns] pay (2,1), pay(2,2), pay (2,3)

DIMENSION sum(2,3,4) Array size: 2*3*4 = 24


Example: Test Number
Serial 1 2 3 4

1
DIMENSION score(10,4) 12 18 16 19

2 13 19 17 11
3 14.5 18 12 13
10 students: 4 CT Marks 4 4.5 5 15 5
40 memory place whose address: 5 18 16 0 14
Score(1,1), (1,2), (1,3), (1,4)
6 17 18 3 15
(2,1)……….(10,4)
7 8.5 18 10 20
8 9 20 3 20
Print*, score (4,3), 9 8.5 14 0 10
(7,4), (10,2), (11,4), 10 9 19 2 17
(2,5)
Output: ? Fig.: The two-dimensional array SCORE.
INTEGER A
DIMENSION A (3,3) [2 subscripts and 3 rows 3 columns]

9.4 Input/output of arrays


9.4.1 Input/output using the array name
If the data entries for
INTEGER A(3,3) A to be read are:10,
READ*, A 20, 30, 40, 50, 60, 70,
80, 90

Column-wise Ordering
9.4.2 Input/output using a DO loop

INTEGER X(5)
DO 10 I = 1, 5 To use only a part of
READ*, X(I) the declared array by
using the statements
10 CONTINUE

 X(2), X(3), and X(4) to be read from input.


INTEGER X(5)
DO 20 I= 1, 5
PRINT*, X(I)
20 CONTINUE

INTEGER X(2,3)
DO 10 J= 1, 3 data element of array
DO 20 I= 1, 2 X=0, 2, 4, 6, 8, 10

READ*, X(I, J)
20 CONTINUE
10 CONTINUE
Column wise X(1,1)=0, X(2,1)=2, X(1,2)=4, X(2,2)=6,
X(1,3)=8, X(2,3)=10
9.4.2 Input/output using a DO loop
2 dimensional array If the data entries for X to be read are

X to be read column wise 0


2
4
INTEGER X(2,3) 6
8
DO 10 J = 1,3 10
DO 20 I = 1,2 The result in the computer
READ*, X(I, J) memory would be?

20 CONTINUE X(1,1) = 0
10 CONTINUE X(2,1) = 2
X(1,2) = 4
X(2,2) = 6
X(1,3) = 8
X(2,3) = 10
9.4.2 Input/output using a DO loop
2 dimensional array
X to be read row wise The result in the computer
memory would be?
INTEGER X(2,3)
X(1,1) = 0
DO 10 I = 1, 2 X(2,1) = 6
DO 20 J = 1, 3 X(1,2) = 2
X(2,2) = 8
READ*, X (I, J) X(1,3) = 4
20 CONTINUE X(2,3) = 10
10 CONTINUE

INTEGER X(2,3) All input values from the


READ*, (( X (I,J), J = 1,3), I = 1,2) same line:
END 0 6 2 8 4 10
INTEGER X(2, 3, 2)
DO 10 I= 1, 2
DO 20 J= 1 ,3
DO 30 K= 1, 2
30 CONTINUE
20 CONTINUE
10 CONTINUE

The data element of array X= 0, 2,4,6,8,10,12,14,16,18,20,22


X(1,1,1)=0, X(2,1,1)= 2, X(1,2,1)=4, X(2,2,1)=6, X(1,3,1)=8, X(2,3,1)=10 , X(1,1,2)=12,
X(2,1,2)= 14, X(1,2,2)= 16, X(2,2,2)=18, X(1,3,2)=20, X(2,3,2)=22
9.4.3 Input/output using Implied DO loop

DO 10 I = 1,5
The READ statement to
READ*, X(I) be executed 5 times and
requires 5 lines of input
10 CONTINUE

Implied DO loop
READ*, (X (I), I = 1,5) 5 values of input data to be read into:
X(1), X(2), X(3), X(4) and X(5)

 The statement makes it possible to input all the


values from the same line
1.Write a FORTRAN program of addition of two matrices P
and Q, where the matrix P and Q are of (3×3) order matrix.
Solution:
INTEGER P(3,3), Q(3,3), R(3,3)
PRINT*,'ENTER MATRIX P ROW WISE'
DO 20 I= 1, 3
DO 30 J=1, 3
READ*, P(I, J)
30 CONTINUE
20 CONTINUE

PRINT*, 'ENTER MATRIX Q ROW WISE'


DO 40 I= 1,3
DO 50 J= 1,3
READ*,Q(I, J)
50 CONTINUE
40 CONTINUE

DO 200 I= 1,3
DO 300 J= 1,3
R(I, J)=P(I, J)+Q(I, J)
300 CONTINUE
200 CONTINUE

PRINT*, 'MATRIX P+Q=R'


DO 70 I=1, 3
DO 60 J=1, 3
PRINT*, R(I, J)
60 CONTINUE
70 CONTINUE
STOP
END
2. Write a FORTRAN program of addition of two matrices P and Q,
where the matrix P and Q are of (3×4) order matrix.
Solution:
INTEGER P(3,4), Q(3,4), R(3,4)
PRINT*,'ENTER MATRIX P ROW WISE'
DO 20 I= 1, 3
DO 30 J=1, 4
READ*, P(I, J)
30 CONTINUE
20 CONTINUE

PRINT*, 'ENTER MATRIX Q ROW WISE'


DO 40 I= 1,3
DO 50 J= 1,4
READ*,Q(I, J)
40 CONTINUE
50 CONTINUE

DO 200 I= 1,3
DO 300 J= 1,4
R(I, J)=P(I, J)+Q(I, J)
300 CONTINUE
200 CONTINUE

PRINT*, 'MATRIX P+Q=R'


DO 50 I=1, 3
DO 60 J=1, 4
PRINT*, R(I, J)
60 CONTINUE
50 CONTINUE
STOP
END
3. Write a ForTran program to find addition of two matrixes
(P, Q) of order (3, 3) showing all inputs and outputs both in
matrix form.
INTEGER P(3,3), Q(3,3), R(3,3)
PRINT*,'ENTER MATRIX P ROW WISE'
DO 10 I= 1, 3
DO 11 J=1,3
READ*, P(I,J)
11 CONTINUE
10 CONTINUE
PRINT*,'DISPLAY MATRIX P ROW WISE'
DO 12 I= 1,3
PRINT*,P(I,1),P(I,2),P(I,3)
12 CONTINUE
PRINT*, 'ENTER MATRIX Q ROW WISE'
DO 13 I= 1,3
DO 14 J= 1,3
READ*,Q(I,J)
14 CONTINUE
13 CONTINUE
PRINT*,'DISPLAYS MATRIX Q ROW WISE'
DO 15 I= 1,3
PRINT*,Q(I,1),Q(I,2),Q(I,3)
15 CONTINUE
DO 16 I= 1,3
DO 17 J= 1,3
R(I, J)=P(I, J)+Q(I, J)
17 CONTINUE
16 CONTINUE
PRINT*, 'MATRIX P+Q=R'
DO 18 I=1, 3
PRINT*, R(I, 1), R(I, 2), R(I, 3)
18 CONTINUE
STOP
END
4. Write a ForTran program to find multiplication of two matrixes
(P, Q) of order (3, 3) showing all inputs and outputs both in matrix
form.
INTEGER P(3,3), Q(3,3), C(3,3), D
PRINT*,'ENTER MATRIX P ROW WISE'
DO 10 I= 1, 3
DO 11 J=1, 3
READ*, P(I,J)
11 CONTINUE
10 CONTINUE
PRINT*,‘DISPLAY MATRIX P ROW WISE'
DO 20 I= 1,3
PRINT*,P(I,1),P(I,2),P(I,3)
20 CONTINUE
PRINT*, 'ENTER MATRIX Q ROW WISE'
DO 30 I= 1,3
DO 31 J=1, 3
READ*,Q(I, J)
31 CONTINUE
30 CONTINUE
PRINT*,‘DISPLAY MATRIX Q ROW WISE'
DO 40 I= 1,3
PRINT*,Q(I,1),Q(I,2),Q(I,3)
40 CONTINUE
DO 50 I= 1,3
DO 60 J= 1,3

D=0
DO 70 L= 1,3
D=D+Q(I,L)*P(L,J)
70 CONTINUE
C(I,J)=D
60 CONTINUE
50 CONTINUE
PRINT*, 'RESULT OF MALTIPLICATION'
DO 80 I=1, 3
PRINT*, C(I, 1), C(I, 2), C(I, 3)
80 CONTINUE
STOP
END
5.Write a program which reads a 3 by 4 matrix M Column
wise and prints the elements row wise.
Solution:
DIMENSION M(3,4)
DO 20 J= 1,4
PRINT*, 'ENTER MARTIX M COLUMN WISE'
READ*, (M(I, J), I=1,3)
20 CONTINUE
DO 10 I=1,3
PRINT 30, (M(I, J), J=1,4)
30 FORMAT(1X, 4I8)
10 CONTINUE
STOP
END
Self study for practise

1. Write a FORTRAN program of Subtraction of


two matrices P and Q, where the matrix P and
Q are (3×3) and (3×4) order matrix showing
all elements in matrix form.
2. Write a FORTRAN program to find the
multiplication of two matrices of order (2×4)
and (4×2) showing all elements in matrix
form.

You might also like