Fortran Programming

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

Fortran Programming

Follow any book on Fortran


Acronym for​ FOR​mula ​TRAN​slator
High level language C, C++, Pascal, Algol, Python
Most scientific programs are written in Fortran.
Program: Set of instructions written to solve a particular
problem.
Compiler: A program to convert program written in high
level language to machine level language.
GNU Fortran compiler
Various versions of FORTRAN exist: ​Fortran 77​, Fortran
90, Fortran 95 etc.
In GNU Fortran many facilities of 90/95 are incorporated.
We shall write the programs following conventional
format (one can write also in free format!)
Any editor – like notepad – can be used to write, edit and
save a program.

123456789012345678901234567890123456789012345678901234567890123456789012

→ | |
Columns 1 to 5 are used to write statement numbers
7 to 72 are used to write executable statements
6 is reserved for continuation statement (if any)
Any integer is written there
Once a program is saved, it is called ​source file​ or code.
abc.f (name usually of 8 characters)
This source file is compiled by the compiler program to
produce the ​run file​ or ​exe file​. abc.exe
This exe file is run to get the result.
Without describing the features of FORTRAN, its syntax
etc first, then write a program using some of those
features we shall follow a different approach.
Consider a problem, write a program to solve it, explain
the meaning of the statements used, run the program,
supply data and get result.

● P1-hello.f:
C THIS IS MY FIRST PROGRAM
WRITE(*,*)'HELLO! THIS IS MY FIRST PROGRAM'
STOP
END
OUTPUT:
HELLO! THIS IS MY FIRST PROGRAM
● P2-add1.f:
C PROGRAM TO ADD TWO FIXED INTEGER NUMBERS
INTEGER A, B, SUM
A=15
B=17
SUM=A+B
WRITE(*,*)'SUM OF INTEGERS 15 AND 17 IS=', SUM
STOP
END

OUTPUT OF THE ABOVE PROGRAM:


SUM OF INTEGERS 15 AND 17 IS= 32

● P3-add2.f:
C PROGRAM TO FIND SUM OF ANY TWO INTEGER NUMBERS
C NUMBERS ARE TO BE INPUT FROM THE KEY BOARD
INTEGER A,B,SUM
WRITE(*,*)'ENTER THE TWO INTEGER NUMBERS'
READ(*,*)A,B
SUM=A+B
WRITE(*,*)'SUM OF',a,b,' IS=',SUM
STOP
END

OUTPUT-1:
C:\G77\work>p3-add2
ENTER THE TWO INTEGER NUMBERS
15
12
SUM OF 15 12 IS= 27
OUTPUT-2:
ENTER THE TWO INTEGER NUMBERS
-7 22
SUM OF -7 22 IS= 15
● P4-mathop.f:
!PROGRAM TO FIND A+B, A-B, A×B, A/B AND A^B; A and B are two real
numbers
REAL A,B,S1,S2,S3,S4,S5 ​default integers I-N
WRITE(*,*)'PROGRAM TO FIND THE VALUES OF
A+B,A-B,A*B,A/B,A^B'
WRITE(*,*)'ENTER THE VALUES OF A AND B'
READ(*,*)A,B
S1=A+B
S2=A-B
S3=A*B
S4=A/B
S5=A**B
WRITE(*,*)'A+B=',S1
WRITE(*,*)'A-B=',S2
WRITE(*,*)'A*B=',S3
WRITE(*,*)'A/B=',S4
WRITE(*,*)'A**B=',S5
STOP
END

OUTPUT:
C:\G77\work>p4-mathop
PROGRAM TO FIND THE VALUES OF A+B,A-B,A*B,A/B,A^B
ENTER THE VALUES OF A AND B
5.0 10.0
A+B= 15.
A-B= -5.
A*B= 50.
A/B= 0.5
A**B= 9765625.

● P5-hier1.f:
C HIERARCHY OF ARITHMETIC OPERATIONS
REAL A,B,C,D,E,F
A=1
B=2
C=3
D=12
E=4
F=8
EXP1=A-B*C+D/E a 1 b 2 c 3 d 12 e 4 f 8
EXP2=A+D/E-B*C
EXP3=A+B*C-D/E+A**B-(B-F)
EXP4=A+A**B-(B-F)-D/E+B*C
WRITE(*,*) EXP1,EXP2,EXP3,EXP4
STOP
END
OUTPUT:
-2. -2. 11. 11.

● P6-hier2.f:
C HIERARCHY OF ARITHMETIC OPERATIONS
S1=2*30/4
s2=2*(30/4)
s3=2*30./4
s4=2*(30./4)
write(*,*) s1,s2,s3,s4
STOP
END

OUTPUT:
15. 14. 15. 15.

● P7-temp.f:
! PROGRAM TO CONVERT TEMPERATURE FROM CENTIGRADE TO
FAHRENHEIT
REAL C, F
CHARACTER (20) NAME
WRITE(*,*)'WHAT IS YOUR NAME?'
READ(*,*)NAME
WRITE(*,*)'HELLO ',NAME,'ENTER THE TEMPETATURE IN
CENTIGRADE'
READ(*,*)C
F=C*9.0/5.0+32.0
WRITE(*,*) ‘TEMPETATURE IN CENTIGRADE=', C, 'IN
FAHRENHEIT=',F
END
OUTPUT:
WHAT IS YOUR NAME?
AMIT
HELLO AMIT ENTER THE TEMPETATURE IN CENTIGRADE
40
TEMPETATURE IN CENTIGRADE 40.000000 IN FAHRENHEIT=
104.000000

● P11-area.f:
! calculate area, circumference of a circle
! calculate volume, surface area of a sphere
real r, area, circum, vol, sa
pi=4*atan(1.0)
write(*,*) 'input radius'
read(*,*) r
area=pi*r**2
circum=2*pi*r
vol=4.0*pi*r**3/3.0
sa=4.0*pi*r**2
write(*,*) 'Pi:',pi
write(*,*) 'circle: area=',area,' circumference=',circum
write(*,*) 'Sphere: volume=',vol,' surface area=',sa
stop
end
OUTPUT:
C:\G77\work>p11-area
input radius
5.2
Pi: 3.14159274
circle: area= 84.9486618 circumference= 32.6725616
Sphere: volume= 588.977356 surface area= 339.794647

Compilation error
C:\G77\work>fc p11error-area
C:\G77\work> No error
! calculate area, circumference of circle
! volume, surface area of a sphere
pi=4*atan(1.0)
real r, area, circum, vol,sa
write(*,*) 'input radius'
read(*,*) r
area=pi*r**2
circum=2pi*r
vol=4.0*pi*r**3/3.0
sa=4.0*pi*rad**2
write(*,*) 'Pi:,pi
write(*,*) 'circle: area=',area,' circumference=',circum
write(*,*) 'Sphere: volume=',vol' surface area=',sa
stop
end
While compiling we get the following long list of error messages:
C:\G77\work>fc p11error-area
p11error-area.f: In program `MAIN__':
p11error-area.f:3:
pi=4*atan(1.0)
1
p11error-area.f:4: (continued):
real r, area, circum, vol,sa
2
Statement at (2) invalid in context established by statement at (1)
p11error-area.f:5:
write(*,*) 'input radius'
1
p11error-area.f:6: (continued):
read(*,*) r
2
Invalid radix specifier `ead' at (2) for typeless constant at (1)
p11error-area.f:6:
read(*,*) r
^
Missing first operand for binary operator at (^)
p11error-area.f:6:
read(*,*) r
^
Missing first operand for binary operator at (^)
p11error-area.f:6:
read(*,*) r
^
Concatenation operator at (^) must operate on two subexpressions of
character ty
pe, but the subexpression at (^) is not of character type
p11error-area.f:6:
read(*,*) r
^
Invalid form for WRITE statement at (^)
p11error-area.f:8:
circum=2pi*r
^
Invalid form for assignment statement at (^)
p11error-area.f:11:
write(*,*) 'Pi:,pi
1 2
Character constant at (1) has no closing apostrophe at (2)
p11error-area.f:13:
write(*,*) 'Sphere: volume=',vol' surface area=',sa
1 2
Invalid radix specifier `vol' at (1) for typeless constant at (2)
p11error-area.f:13:
write(*,*) 'Sphere: volume=',vol' surface area=',sa
^
Invalid form for WRITE statement at (^)
Consider only this part
p11error-area.f:3:
pi=4*atan(1.0)
1
p11error-area.f:4: (continued):
real r, area, circum, vol,sa
2
Statement at (2) invalid in context established by statement at (1)
C:\G77\work>fc p11error-area
This time following error messages are obtained.
C:\G77\work>fc p11error-area
p11error-area.f: In program `MAIN__':
p11error-area.f:5:
write(*,*) 'input radius'
1
p11error-area.f:6: (continued):
read(*,*) r
2
Invalid radix specifier `ead' at (2) for typeless constant at (1)
p11error-area.f:6:
read(*,*) r
^
Missing first operand for binary operator at (^)
p11error-area.f:6:
read(*,*) r
^
Missing first operand for binary operator at (^)
p11error-area.f:6:
read(*,*) r
^
Concatenation operator at (^) must operate on two subexpressions of
character ty
pe, but the subexpression at (^) is not of character type
p11error-area.f:6:
read(*,*) r
^
Invalid form for WRITE statement at (^)
p11error-area.f:8:
circum=2pi*r
^
Invalid form for assignment statement at (^)
p11error-area.f:11:
write(*,*) 'Pi:,pi
1 2
Character constant at (1) has no closing apostrophe at (2)
p11error-area.f:13:
write(*,*) 'Sphere: volume=',vol' surface area=',sa
1 2
Invalid radix specifier `vol' at (1) for typeless constant at (2)
p11error-area.f:13:
write(*,*) 'Sphere: volume=',vol' surface area=',sa
^
Invalid form for WRITE statement at (^)

Correct error in Read statement

C:\G77\work>fc p11error-area
p11error-area.f: In program `MAIN__':
p11error-area.f:8:
circum=2pi*r
^
Invalid form for assignment statement at (^)
p11error-area.f:11:
write(*,*) 'Pi:,pi
1 2
Character constant at (1) has no closing apostrophe at (2)
p11error-area.f:13:
write(*,*) 'Sphere: volume=',vol' surface area=',sa
1 2
Invalid radix specifier `vol' at (1) for typeless constant at (2)
p11error-area.f:13:
write(*,*) 'Sphere: volume=',vol' surface area=',sa
^
Invalid form for WRITE statement at (^)
C:\G77\work>fc p11error-area
C:\G77\work> ​No compilation error
OUTPUT:
C:\G77\work>p11error-area
input radius
5.2
Pi: 3.14159274
circle: area= 84.9486618 circumference= 32.6725616
Sphere: volume= 588.977356 surface area= 0.
Algorithm
An algorithm is a step-by-step procedure for solving a problem.
One should write the algorithm first, then write the program to
implement the program.
TO FIND CSA, TSA AND VOLUME OF A CYLINDER
In this problem the algorithm shall be like this:
1. Read the radius and height of the cylinder
2. Assign value of π to the variable pi as 22./7.
3. Calculate curved surface area of the cylinder using the formula,
csa=2*pi*r*h
4. Calculate base area using the formula, ba =pi*r*r
5. Calculate total surface area using the formula, tsa=csa+2*ba
6. Calculate volume using, vol=ba*h
7. Write the calculated values to output device using appropriate heading

P12-cylinder.f:
C PROGRAM TO FIND CSA, TSA AND VOLUME OF A CYLINDER
REAL R,H,PI,CSA,TSA,VOL
WRITE(*,*) 'Input radius and height of the cylinder'
READ(*,*) R,H
PI=22./7. !note in this case pi value calculated differently
CSA=2*PI*R*H
BA=PI*R*R
TSA=CSA+2*BA
VOL=BA*H
WRITE(*,*) 'CYLINDER RADIUS',R,' HEIGHT',H
WRITE(*,*) 'CURVED SURFACE AREA',CSA,' TOTAL SURFACE AREA',TSA
WRITE(*,*) 'VOLUME',VOL
STOP
END
OUTPUT:
Input radius and height of the cylinder
5 15
CYLINDER RADIUS 5. HEIGHT 15.
CURVED SURFACE AREA 471.428558 TOTAL SURFACE AREA
628.571411
VOLUME 1178.57141

P13-triangle.f

! Calculate area of a triangle


real a,b,c,s,area
write(*,*) 'input sides'
read(*,*) a,b,c
s=(a+b+c)/2
area=sqrt(s*(s-a)*(s-b)*(s-c))
write(*,*) 'triangle: area=',area
stop
end
OUTPUT:
C:\G77\work>p13-triangle
input sides
456
sides of the triangle are: 4. 5. 6.
triangle: area= 9.92156696

write a program using base height formula, (a) given base and height
(b) given a, b, c

…………………………………………………………………………………………………………………………..
LIBRARY FUNCTIONS:
Function Description

SQRT(X) Square root of x

EXP(X) Exponentiation (power of e)


LOG(X) Natural logarithm (base e)
LOG10(X) Common logarithm (base 10)
ABS(X) Absolute value of x

MOD(X1, X2) Remainder of division (X1/X2) when X1>X2,


when X1<X2, result is X1
MAX(X1, X2, ....) Maximum value of the numbers
MIN(X1, X2, …..) Minimum value of the numbers
where X, X1, X2 etc. are integer or real numbers
REAL(X1,X2…) Convert to real numbers
where X, X1, X2 etc. are integer or real numbers

Trigonometric Functions

SIN(X) sine of angle X


COS(X) cosine of angle X

TAN(X) tangent of angle X


where X is in radian

Inverse Trigonometric Functions

ASIN(X) sin-1x
ACOS(X) cos-1x
ATAN(X) tan-1x
answer is in radian

Hyperbolic Functions

SINH(X) sinh(x) (Hyperbolic sine)

COSH(X) cosh(x) (Hyperbolic cosine)


TANH(X) tanh(x) (Hyperbolic tangent)
where X is in radian

…………………………………………………………………………………………………………………………..

We want to find sine, cosine and tangent values for theta equal to 0, 30, 45 and 60 degrees.

P14-trig1.f

C PROGRAM TO FIND TRIGONOMETRIC FUNCTION VALUES


REAL X1,X2,X3,X4,X1R,X2R,X3R,X4R
X1=0.
X2=30.0
X3=45.0
X4=60.0
PI=ATAN(1.0)*4. fac=4*atan(1.0)/180.
X1R=X1*PI/180. X1r=x1*fac
X2R=X2*PI/180.
X3R=X3*PI/180.
X4R=X4*PI/180.
WRITE(*,*) 'THETA SINTH COSTH TANTH'
WRITE(*,*) X1,SIN(X1R),COS(X1R),TAN(X1R)
WRITE(*,*) X2,SIN(X2R),COS(X2R),TAN(X2R)
WRITE(*,*) X3,SIN(X3R),COS(X3R),TAN(X3R)
WRITE(*,*) X4,SIN(X4R),COS(X4R),TAN(X4R)
STOP
END

OUTPUT:

THETA SINTH COSTH TANTH


0. 0. 1. 0.
30. 0.5 0.866025388 0.577350259
45. 0.707106769 0.707106769 1.
60. 0.866025448 0.49999997 1.7320509

P15-root1.f

C PROGRAM TO FIND nth ROOT OF A REAL NUMBER


WRITE(*,*)'Input the number'
READ(*,*) A
WRITE(*,*) 'Input which root to find (e.g. input 5 to find 5th root)'
READ(*,*) N
CNR=A**(1./n) No type declaration

WRITE(*,*) n,'th root of',a,' is',CNR Note variable names


STOP CNR=A**(1/n) ?
END

OUTPUT:
Input the number
23
Input which root to find (e.g. input 5 to find 5th root)
7
7.th root of 23. is 1.56506562
15.67 1.73385906

P16-mod.f:

C program to use MOD, MAX and MIN functions


x1=24
x2=36
write(*,*) MOD(X1,X2), MOD(X2,X1)
WRITE(*,*) MAX(23,14,5,-10,36)
WRITE(*,*) MIN(23,14,5,-10,36)
STOP
END
OUTPUT:

C:\G77\work>P16-mod

24. 12.

36

-10
DATA STATEMENT:

1. By assignment statement
2. By READ statement

………………………………………………………………………………………………………………………………………………..

DATA V1, V2, V3, …../X1, X2, X3, ……../

Where,
V1, V2, V3,….. are variable names and X1, X2, X3, …….. are their values.
➢ Note that the type of variables V1, V2,…etc. must match with the type of their values.

DATA I, A, B, C,NAME/15, 2.3, 5.6, 1.0,’Fortran’/

This assigns I=15, A=2.3, B=5.6, C=1.0 and NAME=’Fortran’

…………………………………………………………………………………………………………………………..

P17-data.f:
C PROGRAM TO DEMONSTRATE THE USE OF DATA STATEMENT

INTEGER AGE

REAL HEIGHT

CHARACTER NAME*15
DATA AGE,HEIGHT,NAME/28,6.1,'Pran'/

WRITE(*,*)'**PROGRAM TO DEMONSTRATE THE USE OF DATA STATEMENT**'

WRITE(*,*) ????

WRITE(*,*)'Name:',NAME

WRITE(*,*)'Age',AGE

WRITE(*,*)'Height=',HEIGHT,’ FEET’

STOP

END

OUTPUT:
**PROGRAM TO DEMONSTRATE THE USE OF DATA STATEMENT**

Name: Pran

Age 28

Height= 6.0999999 FEET

simple mechanics problem:


Three men fall at the same instance freely from the top of three separate buildings of heights
50m, 75m and 100m. After what time will they hit the ground?

Free fall under gravity, with zero initial velocity, s=½.gt2


t=sqrt(2s/g).

P18-time.f
C Calculation of time of free fall
real s,g,t1,t2,t3
g=9.8

s1=50
t1=sqrt(2*s1/g)
s2=75
t2=sqrt(2*s2/g)
s3=100
t3=sqrt(2*s3/g)

write(*,*) 'Time for 1st man ',t1,' sec'


write(*,*) 'Time for 2nd man ',t2,' sec'
write(*,*) 'Time for 3rd man ',t3,' sec'
stop

end
OUTPUT:
C:\G77\work>p18-time

Time for 1st man 3.19438291 sec

Time for 2nd man 3.91230392 sec

Time for 3rd man 4.5175395 sec

Modify this program (a) to use data statement (b) read values of the
heights while running the program

CONTROL STATEMENTS:

1. Arithmetic IF statement
2. Logical IF statement
3. Unconditional GO TO statement
4. Computed GO TO statement
5. IF-THEN-ENDIF statement
6. IF-THEN-ELSE-ENDIF statement
7. Nested IF-THEN-ELSE-ENDIF statement
8. PAUSE statement
CONTROL STATEMENTS:

1. Arithmetic IF statement
2. Logical IF statement
3. Unconditional GO TO statement
4. Computed GO TO statement
5. IF-THEN-ENDIF statement
6. IF-THEN-ELSE-ENDIF statement
7. Nested IF-THEN-ELSE-ENDIF statement
8. PAUSE statement

Arithmetic IF statement
The general form is
IF (EXPRESSION) N1, N2, N3

where (EXPERSSION) is a valid FORTRAN expression enclosed within parenthesis. N1, N2 and N3
are statement numbers.

The value of the expression is evaluated first. If the value is negative the control goes to the
statement number N1; if it is zero, the control goes to N2 and if it is positive, the control goes
to N3.

f(x) = x2 + sin(2x) when x < 3


= x2 - sin(2x) x=3
= x3 - cos(3x) x>3

P20-function1.f:
C PROGRAM TO EVALUATE A FUNCTION FOR THREE DIFFERENT CONDITIONS
C USE OF ARITHMATIC IF STATEMENT
WRITE(*,*)'*** THE FUNCTION IS***'
WRITE(*,*)'F=X*X+SIN(2X) IF X<3'

WRITE(*,*)'F=X*X-SIN(2X) IF X=3'
WRITE(*,*)'F=X**3-COS(3X) IF X>3'
WRITE(*,*)''
WRITE(*,*)'ENTER THE VALUE OF X'

READ(*,*)X
A=X-3
IF(A)10,20,30
10 F=X*X+SIN(2*X)

WRITE(*,*)'GIVEN VALUE IS < 3'


WRITE(*,*)'THE VALUE OF THE FUNCTION IS=',F
STOP
20 F=X*X-SIN(2*X)
WRITE(*,*)'GIVEN VALUE IS = 3'

WRITE(*,*)'THE VALUE OF THE FUNCTION IS=',F


STOP
30 F=X**3-COS(3*X)
WRITE(*,*)'GIVEN VALUE IS > 3'
WRITE(*,*)'THE VALUE OF THE FUNCTION IS=',F
STOP
END
OUTPUT-1:
*** THE FUNCTION IS***

F=X*X+SIN(2X) IF X<3

F=X*X-SIN(2X) IF X=3

F=X**3-COS(3X) IF X>3
ENTER THE VALUE OF X

GIVEN VALUE IS < 3

THE VALUE OF THE FUNCTION IS= 3.24319744

OUTPUT-2:
*** THE FUNCTION IS***

F=X*X+SIN(2X) IF X<3

F=X*X-SIN(2X) IF X=3

F=X**3-COS(3X) IF X>3

ENTER THE VALUE OF X

GIVEN VALUE IS = 3

THE VALUE OF THE FUNCTION IS= 9.27941513

OUTPUT-3:
*** THE FUNCTION IS***

F=X*X+SIN(2X) IF X<3

F=X*X-SIN(2X) IF X=3

F=X**3-COS(3X) IF X>3

ENTER THE VALUE OF X

GIVEN VALUE IS > 3

THE VALUE OF THE FUNCTION IS= 125.759689

We want to evaluate the roots of a quadratic equation.

−𝑏 ± √𝑏 2 −4𝑎𝑐
𝑥= 2𝑎
where 𝑏2 − 4𝑎𝑐 is called the discriminator which determines the type of the roots.
P19-root2.f:
C USE OF ARITHMETIC IF STATEMENT
C FIND ROOTS OF A QUADRATIC EQUATION

REAL A,B,C,DISC,ROOT1,ROOT2,RP,IP
WRITE(*,*) 'Input coefficients a,b,c'
READ(*,*) A,B,C
DISC=B*B-4.*A*C

A2=2*A
IF (DISC) 10,20,30
20 ROOT=-B/A2
WRITE(*,*) 'Roots are equal: Root',ROOT
STOP

30 DISC=SQRT(DISC)
ROOT1=(-B+DISC)/A2
ROOT2=(-B-DISC)/A2
WRITE(*,*) 'Roots are real: Root1',ROOT1,' Root2',ROOT2

STOP
10 DISC=SQRT(ABS(DISC))
RP=-B/A2
IP=DISC/A2

WRITE(*,*) 'Roots are complex: Real part',RP,' Imaginary part',IP


STOP
END
OUTPUT-1:

Input coefficients a,b,c


1 0 -4
Roots are real: Root1 2. Root2 -2.
OUTPUT-2:
Input coefficients a,b,c

1 1 -4
Roots are real: Root1 1.56155276 Root2 -2.56155276
OUTPUT-3: 104
Input coefficients a,b,c

104
Roots are complex: Real part 0. Imaginary part 2.
OUTPUT-4:
Input coefficients a,b,c

124
Roots are complex: Real part -1. Imaginary part 1.73205078

S=1+X+X2+X3+X4+.....+XN sum upto n terms


P21-series-sum1.f:
! PROGRAM TO FIND THE SUM OF A SERIES USING ARITHMETIC IF STATEMENT
WRITE(*,*)'PROGRAM TO FIND THE SUM OF A SERIES USING ARITHMETIC IF STATEMENT'
WRITE(*,*)

WRITE(*,*)'THE SERIES IS S=1+X+X**2+X**3+X**4+.....+X**N'


WRITE(*,*)
WRITE(*,*)'ENTER THE VALUES OF X AND NO OF TERMS'
READ(*,*)X,N

SUM=1
I=0
N=N-1
10 I=I+1
SUM=SUM+X**I 1+x+x2+
IF(I-N)10,20,20

20 WRITE(*,*)'THE SERIES SUM IS=',SUM


STOP
END
OUTPUT-1:

PROGRAM TO FIND THE SUM OF A SERIES USING ARITHMATIC IF STATEMENT

THE SERIES IS S=1+X+X**2+X**3+X**4+.....+X**N

ENTER THE VALUES OF X AND N

2,3

THE SERIES SUM IS= 7.

OUTPUT-2:
PROGRAM TO FIND THE SUM OF A SERIES USING ARITHMATIC IF STATEMENT

THE SERIES IS S=1+X+X**2+X**3+X**4+.....+X**N

ENTER THE VALUES OF X AND N

THE SERIES SUM IS= 31.

OUTPUT-3:
PROGRAM TO FIND THE SUM OF A SERIES USING ARITHMATIC IF STATEMENT

THE SERIES IS S=1+X+X**2+X**3+X**4+.....+X**N

ENTER THE VALUES OF X AND N

-1.5

4
THE SERIES SUM IS= -1.625 Modify to get sum upto X^N terms

Note that to complete the arithmetic if structure we have written


statement number 20 twice although I-N will never be positive in this
example.

2. Logical IF statement:

Logical IF statement checks any given logical condition and


transfer the control accordingly.

IF (LOGICAL CONDITION) STATEMENT1

STATEMENT2

STATEMENT1 is any executable statement.


If the LOGICAL CONDITION is true the statement1 is executed
and then goes to the next statement2.
If the condition is false, the control goes to the statement2
without executing the statement1.
Relational or Logical operator Symbol used in Alternative symbol (only for
FORTRAN FORTRAN 90)

Less than .LT. <

Less than or equal to .LE. <=

Greater than .GT. >

Greater than or equal to .GE. >=

Equal to .EQ. ==

Not equal to .NE. /=


AND .AND. Explanation:
a.and.b will be true only
when both a and b are true

OR .OR. a.or.b will be true only


when any one of a and b is
true

…………………………………………………………………………………………………………………………..
P22-function2.f

C PROGRAM TO EVALUATE A FUNCTION FOR THREE DIFFERENT


CONDITIONS
C USE OF LOGICAL IF STATEMENT
WRITE(*,*)'*** THE FUNCTION IS***'
WRITE(*,*)'F=X*X+SIN(2X) IF X<3'
WRITE(*,*)'F=X*X-SIN(2X) IF X=3'
WRITE(*,*)'F=X**3-COS(3X) IF X>3'
WRITE(*,*)''
WRITE(*,*)'ENTER THE VALUE OF X'
READ(*,*)X
IF(X.LT.3) F=X*X+SIN(2*X) !executed only when x<3
IF(X.EQ.3) F=X*X-SIN(2*X) !executed only when x=3
IF(X.GT.3) F=X**3-COS(3*X) !executed only when x>3
WRITE(*,*)'FOR',X, ' THE VALUE OF THE FUNCTION IS=',F
STOP only once
END
OUTPUT-1:
ENTER THE VALUE OF X

THE VALUE OF THE FUNCTION IS= 3.24319744

OUTPUT-2:
ENTER THE VALUE OF X

3
THE VALUE OF THE FUNCTION IS= 9.27941513

OUTPUT-3:
ENTER THE VALUE OF X

THE VALUE OF THE FUNCTION IS= 125.759689

3. Unconditional GOTO statement:

This statement is used to transfer the control to any other


statement unconditionally.

GO TO N

N is the statement number to which the control will be


transferred.
The statement number N may be before or after the GO TO
statement.
The blank between GO and TO is optional.

P23-sum.f:

c program to calculate sum of first n integers


write(*,*) 'Input n'
read(*,*) n
is=0
i=1
10 is=is+i
if (i.eq.n) goto 20
i=i+1
goto 10
20 write(*,*)'calculated value',is
write(*,*)'formula value',n*(n+1)/2
end

OUTPUT-1:
C:\G77\work>p23-sum
Input n
6
calculated value 21
formula value 21
OUTPUT-2:
C:\G77\work>p23-sum
Input n
50
calculated value 1275
formula value 1275

Modify it to sum only the odd/even integer

P24-valid1.f:
C DATA VALIDATION USING LOGICAL IF STATEMENT

C READ VELOCITY, REJECT IT IF -VE OR ZERO WITH A MESSAGE AND STOP

REAL VEL

WRITE(*,*) 'Input velocity'

READ(*,*) VEL

WRITE(*,*) 'Velocity',VEL

IF (VEL.LE.0) WRITE(*,*) 'Negative or zero velocity not allowed, Program is

stopped!'

STOP

END

OUTPUT:
C:\G77\work>p24-valid1
Input velocity
-12
Velocity -12.
Negative or zero velocity not allowed, Program is stopped!
P25-valid2.f
C DATA VALIDATION USING ARITHMETIC IF STATEMENT
C USE OF UNCONDITIONAL GOTO STATEMENT
C CALCULATION OF DISTANCE TRAVELLED IN TIME T
C READ VELOCITY, REJECT IT IF -VE OR ZERO WITH A MESSAGE AND STOP
REAL VEL,TIME,DIST
10 WRITE(*,*) 'Input velocity'
READ(*,*) VEL
IF (VEL) 20,20,30
20 WRITE(*,*) 'Negative or zero velocity not allowed, sorry!'
goto 10
30 WRITE(*,*) 'Input time'
READ(*,*) Time
DIST=VEL*Time
WRITE(*,*) 'Distance travelled',DIST
STOP
END
OUTPUT:

C:\G77\work> p25-valid2
Input velocity
-10
Negative or zero velocity not allowed, sorry!
Input velocity
0
Negative or zero velocity not allowed, sorry!
Input velocity
15
Input time
15
Distance travelled 225.

Write a program to read names, roll numbers and genders of 5


students. You have to read gender as 0 for male and 1 for female. If the
user input any other number by mistake, there should be provision for
supplying the correct value with appropriate message to the user.
Finally you have to print all data. Use only those facilities of fortran
which have been taught so far.

write a program to find the promotional status of a student. A student fails if he


gets less than 40% marks.

P26-promotion.f:

C FIND PROMOTIONAL STATUS OF A STUDENT USING LOGICAL IF STATEMENT


C DEFAULT NAMING CONVENTION OF VARIABLES IS USED
WRITE(*,*)'ENTER FULL MARKS'
READ(*,*) MF
WRITE(*,*)'ENTER MARKS OBTAINED OUT OF', MF
READ(*,*) MO
PCNTM=REAL(MO)/REAL(MF)*100
IF(PCNTM.LT.40) WRITE(*,*) 'OBTAINED MARKS',PCNTM,' STATUS FAIL'
IF(PCNTM.GE.40) WRITE(*,*) 'OBTAINED MARKS',PCNTM,' STATUS PASS'
STOP
END
OUTPUT-1:

C:\G77\work>p26-promotion

ENTER FULL MARKS

100

ENTER MARKS OBTAINED OUT OF 100

63

OBTAINED MARKS 63. % STATUS PASS

OUTPUT-2:

C:\G77\work>p26-promotion

ENTER FULL MARKS

50

ENTER MARKS OBTAINED OUT OF 50

18

OBTAINED MARKS 36. % STATUS FAIL

we now consider that pass/fail status of a student will be decided on the basis of
marks obtained in four subjects. Also note that Unconditional GOTO statement
has been used in this program along with logical if statement.

P27-promotion2.f
C FIND PASS/FAIL STATUS (LESS THAN 40% IS FAIL)
C USE OF UNCONDITIONAL GOTO STATEMENT
C DEFAULT NAMING CONVENTION OF VARIABLES IS USED
WRITE(*,*)'ENTER FULL MARKS AND OBTAINED MARKS FOR FOUR
SUBJECTS'
I=1
SMF=0
SMO=0
50 WRITE(*,*) 'INPUT MARKS OF ONE SUBJECT'
READ(*,*) MF,MO
SMF=SMF+MF
SMO=SMO+MO
I=I+1
IF (I.LE.4) GOTO 50
PCNTM=SMO/SMF*100
IF(PCNTM.LT.40) GOTO 100
WRITE(*,*) 'OBTAINED MARKS',PCNTM,' percent STATUS PASS'
GOTO 200
100 WRITE(*,*) 'OBTAINED MARKS',PCNTM,' percent STATUS FAIL'
STOP
200 END
OUTPUT:
C:\G77\work>p27-promotion2
ENTER FULL MARKS AND OBTAINED MARKS FOR FOUR SUBJECTS
INPUT MARKS OF ONE SUBJECT
100 56
INPUT MARKS OF ONE SUBJECT
50 20
INPUT MARKS OF ONE SUBJECT
150 70
INPUT MARKS OF ONE SUBJECT
100 80
OBTAINED MARKS 56.5 percent STATUS PASS

We now rewrite the program P21 to evaluate a series sum using logical if
statement instead of arithmetic if statement.

P28-series-sum2.f:
C PROGRAM TO FIND THE SUM OF A SERIES USING LOGICAL IF STATEMENT

PRINT*,'PROGRAM TO FIND THE SUM OF A SERIES USING LOGICAL IF


STATEMENT'

PRINT*,''

PRINT*,'THE SERIES IS S=1+X+X**2+X**3+X**4+.....+X**N'

PRINT*,''

PRINT*,'ENTER THE VALUES OF X AND N'

READ*,X,N ! write*,n is not allowed

SUM=1

I=0

10 I=I+1

IF(I.EQ.N) GOTO 20

SUM=SUM+X**I

GOTO 10

20 PRINT*,'THE SERIES SUM IS=',SUM

STOP
END

OUTPUT:

PROGRAM TO FIND THE SUM OF A SERIES USING LOGICAL IF STATEMENT

THE SERIES IS S=1+X+X**2+X**3+X**4+.....+X**N

ENTER THE VALUES OF X AND N

-1.5 4

THE SERIES SUM IS= -1.625


● P29-fibonacci.f:
C Print Fibonacci numbers upto 20000

C find ratio of the higher to lower consecutive F. nos.

n0=0

n1=1

c write(*,*)n0

c write(*,*)n1

write(*,*)'F.No Ratio'

5 n=n0+n1

if (n.gt.20000) stop
write(*,*)n,' ',real(n)/real(n1)

n0=n1

n1=n

goto 5

end

OUTPUT:

C:\G77\work>p29-fibonacci

F.No Ratio

1 1.

2 2.

3 1.5

5 1.66666663
8 1.60000002

13 1.625

21 1.61538458

34 1.61904764

55 1.61764705

89 1.61818182
144 1.6179775

233 1.61805558

377 1.61802578

610 1.6180371

987 1.61803281

1597 1.61803448

2584 1.61803377

4181 1.61803401

6765 1.61803401

10946 1.61803401

17711 1.61803401
Note that for higher numbers, the ratio approaches a constant value which is
known as golden mean. This is actually one solution of the quadratic equation
x​2​-x-1=0. [Run program P19-root2 to verify].

4.​ Computed GO TO statement:


The ​Computed GO TO ​statement causes transfer of control depending upon value of an ​integer
variable.
…………………………………………………………………………………………………
………………………..
The general format of the statement is

Where I is the integer variable, N​1​, N​2​, ……….N​K ​are the statement numbers.
If I=1, the control goes to statement no. N​1
=2, the control goes to statement no. N​2
…………………………………………
..………………………………………
=k, the control goes to statement no. N​k
If I<1 or I>k then computed got statement is ignored and the control goes to the next line.

…………………………………………………………………………………………………
………………………..
Next program is to demonstrate the use of ​Computed GOTO statement by designing a
calculator to perform four simple mathematical operations addition, subtraction, multiplication
and division.

P30-calculator.f:
! program to design a calculator for simple arithmetic operations
! use of computed goto statement
5 write(*,*) 'Input two numbers A,B'
read(*,*) a,b
8 Write(*,*) '1. Addition 2. Subtraction'
Write(*,*) '3. Product 4. Division'
write(*,*) '5. Exit'
write(*,*) 'Choose any option number'
read(*,*) key
goto (10,20,30,40,150) key
10 write(*,*) 'Sum= ',A+B; goto 45
20 write(*,*) 'Difference= ',A-B; goto 45
30 write(*,*) 'Product= ',A*B; goto 45
40 write(*,*) 'Division= ',A/B; goto 45
45 write(*,*) 'To use other options enter 1, otherwise 0'
read(*,*) nk1
if (nk1.eq.1) goto 8
50 write(*,*) 'To work with new numbers enter 1, otherwise 0'
read(*,*) nk2
if (nk2.eq.1) goto 5
150 write(*,*) 'Thanks for using my calculator!'
end

OUTPUT:
Input two numbers A,B
56,63
1. Addition 2. Subtraction
3. Product 4. Division
5. Exit
Choose any option number
1
Sum= 119.
To use other options enter 1, otherwise 0
1
1. Addition 2. Subtraction
3. Product 4. Division
5. Exit
Choose any option number
2
Difference= -7.
To use other options enter 1, otherwise 0
1
1. Addition 2. Subtraction
3. Product 4. Division
5. Exit
Choose any option number
4
Division= 0.888888896
To use other options enter 1, otherwise 0
1
1. Addition 2. Subtraction
3. Product 4. Division
5. Exit
Choose any option number
3
Product= 3528.
To use other options enter 1, otherwise 0
0
To work with new numbers enter 1, otherwise 0
1
Input two numbers A,B
23 45
1. Addition 2. Subtraction
3. Product 4. Division
5. Exit
Choose any option number
3
Product= 1035.
To use other options enter 1, otherwise 0
1
1. Addition 2. Subtraction
3. Product 4. Division
5. Exit
Choose any option number
5
Thanks for using my calculator!
Modify the program to include additional tasks – to find a^b, and cube and cube
root of any number. Program should first display the options available for
calculations. Depending upon the option it should ask for input(s) and print the
result. Then further options as done in this program.
We now discuss another control statement which give more flexibility in a program.

5. ​IF-THEN-ENDIF statement:
By the logical if statement we can execute only one statement if the logical condition is true.

IF(X.LT.3) F=X*X+SIN(2*X)
But in many situations we need to execute more than one statement when the condition is
true. In that case we use if-then-endif statement.
…………………………………………………………………………………………………
………………………..
The general form of this statement is

The space between END and IF is optional.


If the condition is true, program statements between the ​IF-THEN​ and ​ENDIF ​will be executed,
otherwise control will be transferred to the line after ENDIF statement.

…………………………………………………………………………………………………
………………………..

Now to demonstrate the use of IF-THEN-ENDIF statement consider the


following programs to evaluate cosine, sine and exponential series.
These series are:

cos(x) = 1 – x​2​/2! + x​4​/4! – x​6​/6! + …………


sin(x) = x – x​3​/3! + x​5​/5! – x​7​/7! + …………
exp(x) = 1 + x + x​2​/2! + x​3​/3! + x​4​/4! + …………
In these programs we calculate the value of the trigonometric function
for a particular value of x by evaluating the series sum and by using the
library function to compare the two values.
● P31-cosine-series.f:
C Evaluate cos(x) series
write(*,*) 'Input x'
read (*,*) x
sum=1 cos(x) = 1 – x​2​/2! + x​4​/4! – x​6​/6! + …………
t=1
i=1
nct=1
10 t=-t*x*x/(i*(i+1)) -x^2/2! X^4/4!
if(abs(t).gt.​0.00000001​) then
sum=sum+t 1-x^2/2!+ X^4/4!
i=i+2 3 5
nct=nct+1 2 3
goto 10
endif
20 write(*,*) 'x, series sum, no of terms, cos(x)'
write(*,*) x,sum,nct,cos(x)
end
OUTPUT-1:
C:\G77\work2>p31-cosine-series
Input x
.25
x, series sum, no of terms, cos(x)
0.25 0.968912423 4 0.968912423
OUTPUT-2:
C:\G77\work2>p31-cosine-series
Input x
.2
x, series sum, no of terms, cos(x)
0.200000003 0.980066597 4 0.980066597
OUTPUT-3
C:\G77\work2>p31-cosine-series
Input x
.5
x, series sum, no of terms, cos(x)
0.5 0.87758261 5 0.87758255

● P32-sine-series.f:
c sine series evaluation
write(*,*) 'input x'
read(*,*) x
sum=x
t=x
i=1
nct=1
10 t=-t*x**2/((i+1)*(i+2))
if (abs(t).gt.​0.000001​) then
sum=sum+t
i=i+2
nct=nct+1
goto 10
endif
write(*,*) 'x',x,' sum',sum,' No of terms',nct,' sinx',sin(x)
end
OUTPUT:
C:\G77\work>p32-sine-series
input x
.5
x 0.5 sum 0.47942552 No of terms 4 sinx 0.47942555

● P33-exp-series.f:
c evaluate exponential series
write(*,*) 'Input x'
read(*,*) x
SUM=1
I=1
T=1
nct=1
25 T=T*X/I
IF (T.LT.​1.0E-9​) GOTO 40
SUM=SUM+T
I=I+1
nct=nct+1
GOTO 25
40 WRITE(*,*) 'X',x,' SUM',sum,' no of terms',nct,' EXP(X)',exp(x)
END
OUTPUT:
C:\G77\work>p33-exp-series
Input x
.4
X 0.400000006 SUM 1.49182475 no of terms 9 EXP(X) 1.49182475

Note that in the last example exp(x) series is evaluated without using
IF-THEN-ENDIF statement, rather we use logical if statement to show
that a particular problem may be solved using different facilities of
fortran. Unlike in the two previous examples here we continued the
repetitive work when the calculated term is greater than the
pre-assigned small value 1x10​-9​.
Modify the above program to find value of exp(x) taking 3, 5, 7 and 9 terms.
Modify the above program so that the program also prints each term value.
In the next example, we check whether an integer is multiple of 2, 3 or
7. Basically we have used MOD function to achieve the task. In the
output we have shown examples of all possibilities.
● P34-multiple1.f:
C USE Of IF-THEN-ENDIF STRUCTURE
C PROGRAM TO CHECK WHETHER AN INTEGER IS
C MULTIPLE OF 2, 3 OR 7
WRITE(*,*)'ENTER THE NUMBER'
READ(*,*) N
IF (MOD(N,2).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 2'
A=0 !this is used to check if the number is not multiple of 2,3,7

ENDIF
IF (MOD(N,3).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 3'
A=0
ENDIF
IF (MOD(N,7).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 7'
A=0
ENDIF
IF (A.NE.0) WRITE(*,*) N,' IS NOT MULTIPLE OF 2,3 AND 7'
STOP
END

OUTPUT-1:
C:\G77\work>p34-multiple1
ENTER THE NUMBER
4
4 IS MULTIPLE OF 2
OUTPUT-2:
C:\G77\work>p34-multiple1
ENTER THE NUMBER
27
27 IS MULTIPLE OF 3
OUTPUT-3:
C:\G77\work>p34-multiple1
ENTER THE NUMBER
12
12 IS MULTIPLE OF 2
12 IS MULTIPLE OF 3
OUTPUT-4:
C:\G77\work>p34-multiple1
ENTER THE NUMBER
14
14 IS MULTIPLE OF 2
14 IS MULTIPLE OF 7
OUTPUT-5:
C:\G77\work>p34-multiple1
ENTER THE NUMBER
42
42 IS MULTIPLE OF 2
42 IS MULTIPLE OF 3
42 IS MULTIPLE OF 7
Modify the program to find if a given number is multiple of 5, 7 and 9
Modify the program to find if a given number is multiple of three
integers supplied at the time of running.

Let us now discuss more flexible control statement.


6. IF-THEN-ELSE-ENDIF statement:
When it is required to execute more than one statement when the
logical condition is true and also when the condition is false we use
if-then-else-endif statement.
If the condition is true then the statement(s) between THEN and ELSE
will be executed, but if the condition is not true then the statements
between ELSE and ENDIF will be executed ignoring the statements
between THEN and ELSE.
We want to write a program to find the greatest common divisor or
highest common factor (HCF) of two integers, say I and J, using
IF-THEN-ELSE-ENDIF structure. We use the following logic: I is divided by
J. If the remainder k is zero, J is the HCF. Otherwise I is replaced by J and
J is replaced by the remainder k and the process is continued.
42 12 42 12 6
● P35-hcf.f:
C TO FIND HCF OF TWO INTEGERS
c USE OF MOD FUNCTION
WRITE(*,*) 'Input two integers'
READ(*,*) I,J
iold=i
jold=j
c MOD RETURNS REMAINDER OF X1/X2 WHEN X1>X2, RETURNS X1 IF X1<X2

5 K=MOD(I,J)
IF (K.EQ.0) GOTO 10
I=J
J=K
GOTO 5
10 WRITE(*,*) 'HCF of',iold,' and',jold,' is',J
END
OUTPUT-1:
Input two integers
12 3
HCF OF 12 AND 3 is 3
OUTPUT-2:
Input two integers
9 63
HCF OF 9 AND 63 is 9
Note that in this case, in the first loop, the values of I and J get
interchanged since k=9 in this loop, then in the next loop we get the
gcd.
Next we write a program to find whether integer number I is multiple of
integer number J using IF-THEN-ELSE-ENDIF statement.

● P36-multiple2.f:
C TO CHECK IF INTEGER I is MULTIPLE OF INTEGER J
C USE OF IF THEN ELSE ENDIF STATEMENT
C USE OF MOD FUNCTION
WRITE(*,*) 'Input the bigger integer number I'
READ(*,*) I
WRITE(*,*) 'Input smaller integer number J'
READ(*,*) J 24 18
IF (MOD(I,J).EQ.0) THEN
WRITE(*,*) 'Number ',I, ' is multiple of',J
ELSE
WRITE(*,*) 'Number ',I, ' is not a multiple of',J
ENDIF
END
OUTPUT-1:
Input the bigger integer number I
28
Input smaller integer number J
7
Number 28 is multiple of 7
OUTPUT-2:
Input the bigger integer number I
23
Input smaller integer number J
3
Number 23 is not a multiple of 3
Nested IF-THEN-ELSE-ENDIF:
In certain cases we may have to use one or more
IF-THEN-ELSE-ENDIF structures within another
IF-THEN-ELSE-ENDIF structure. This is called nested usage of
IF-THEN-ELSE-ENDIF.
Its general format is

NOTE: If there are N number of IF-THEN-ELSE-ENDIF blocks


then we require N number ENDIF statements.
As an use of this nested structure we have re-written the
program P34 to check whether an integer is multiple of 2, 3 or
7. Note that we have typed in the program in such a way that
each IF-THEN-ELSE-ENDIF structure is clearly visible. In this
program all possibilities are checked explicitly.
● P37-multiple3.f:
C USE Of NESTED IF-THEN-ELSE-ENDIF STRUCT
C PROGRAM TO CHECK WHETHER AN INTEGER IS
C MULTIPLE OF 2, 3 OR 7
WRITE(*,*)'ENTER THE NUMBER'
READ(*,*) N 23
IF (MOD(N,2).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 2'
ELSE
IF (MOD(N,3).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 3'
ELSE
IF (MOD(N,7).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 7'
ELSE
WRITE(*,*) N,' IS NOT MULTIPLE OF 2,3 AND 7'
STOP
ENDIF
ENDIF
ENDIF
C one structure complete
IF (MOD(N,6).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 2 AND 3'
ELSE
IF (MOD(N,14).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 2 AND 7'
ELSE
IF (MOD(N,21).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 3 AND 7'
ENDIF
ENDIF
ENDIF
C another block complete
IF (MOD(N,42).EQ.0) THEN
WRITE(*,*) N,' IS MULTIPLE OF 2, 3 AND 7'
ELSE
WRITE(*,*) N,' IS NOT MULTIPLE OF 2,3 AND 7'
ENDIF
END

OUTPUT-1:
ENTER THE NUMBER
29
29 IS NOT MULTIPLE OF 2,3 AND 7
OUTPUT-2:
ENTER THE NUMBER
42
42 IS MULTIPLE OF 2
42 IS MULTIPLE OF 2 AND 3
42 IS MULTIPLE OF 2, 3 AND 7
OUTPUT-3:
ENTER THE NUMBER
69
69 IS MULTIPLE OF 3
69 IS NOT MULTIPLE OF 2,3 AND 7
OUTPUT-4:
ENTER THE NUMBER
4
4 IS MULTIPLE OF 2
4 IS NOT MULTIPLE OF 2,3 AND 7
Suppose we want to check whether three given lengths can
form a triangle or not. We have used nested if-then-else-endif
structure. In addition, short form of read and print statements
are used as explained before.
● P38a-triangle2.f:
C Program to check if given 3 sides form a triangle
C use of nested if-then-else-endif structure
Integer a,b,c

print*,'Input a,b,c'

read*,a,b,c

if (a+b.gt.c) then

if (b+c.gt.a) then

if (c+a.gt.b) then

print*,a,b,c,' form triangle'

else

print*,a,b,c,' donot form triangle'

endif

stop

endif

print*,a,b,c,' donot form triangle'

stop

endif

print*,a,b,c,' donot form triangle'

end

OUTPUT-1:
Input a,b,c
639
6 3 9 donot form triangle
OUTPUT-2:
Input a,b,c
468
4 6 8 form triangle

Alternatively we could have used the following program using


special logical if statement. Three relational expressions
(a+b.gt.c), (b+c.gt.a) and (c+a.gt.b) have been connected by
logical operator .AND.. The condition is true only when all the
relational expressions are true.
● P38b-triangle3.f:
C Program to check if given 3 sides form a triangle
Integer a,b,c
print*,'Input a,b,c'
read*,a,b,c
if ((a+b.gt.c).and.(b+c.gt.a).and.(c+a.gt.b)) then
print*,a,b,c,' form triangle'
else
print*,a,b,c,' donot form triangle'
endif
stop
end

OUTPUT-1:
C:\G77\work2>p38b-triangle3
Input a,b,c
639
6 3 9 donot form triangle
OUTPUT-2:
C:\G77\work2>p38b-triangle3
Input a,b,c
468
4 6 8 form triangle
We now discuss a special kind of control statement which is
used to temporarily halt execution of the program.
8. Pause function
Suppose we are running a program and it has given several
outputs. You want read those output values and then want to
decide whether you want to continue or not. In such situations
it is required to halt the program after running a few steps. This
can be done using PAUSE statement. While running the
program appropriate message will be displayed what you have
to do to continue or to abort the program.
General form of this statement is

Use of pause function is explained in the following program.

● P38c-pause.f:
C TO DEMONSTRATE THE USE OF PAUSE FUNCTION
WRITE(*,*)'ENTER VALUES OF X AND Y'
READ(*,*) X,Y
WRITE(*,*)'X,Y ',X,Y
PAUSE
WRITE(*,*)'ENTER VALUES OF A AND B'
READ(*,*) A,B
WRITE(*,*)'A,B ',A,B
STOP
END
OUTPUT-1:
C:\G77\work>p38c-pause
ENTER VALUES OF X AND Y
23
X,Y 2. 3.
PAUSE statement executed
To resume execution, type go. Other input will terminate the job.
go
Execution resumes after PAUSE.
ENTER VALUES OF A AND B
32
A,B 3. 2.
OUTPUT-2:
C:\G77\work>p38c-pause
ENTER VALUES OF X AND Y
12 45
X,Y 12. 45.
PAUSE statement executed
To resume execution, type go. Other input will terminate the job.
23
STOP
PROGRAMS USING LOOPS:
In many problems it is required to perform a certain job repeatedly. For this purpose we need
to repeat a set of statements a specified number of times. To perform this kind of job we use
DO statement, more frequently used term is DO loops.

DO LOOPS:
The general form of the DO loop is

DO NO I=N1, N2, N3 DO I=N1, N2, N3 DO NO I=N1, N2, N3


Or Or
……………………. ……………………… ……………………………

……………………. ……………………… …………………………..

NO CONTINUE END DO NO Executable Statement

where,
………………………… denote Executable Statements
NO is the statement number up to which the DO loop is CONTINUED.
I is the loop control variable (also called the running variable of DO loop).
N1=initial value of I
N2=final value of I
N3=increment value of I. If the increment is 1 then it can be omitted.
The control variable I may be an integer or real, accordingly the parameters N1, N2, N3 may be
integer or real numbers (or variables, even may be expressions). Space between END and DO is
optional.
DO loop works in the following way.
a. At the beginning of the loop assign I=N1
b. All the statements between the DO statement and the CONTINUE statement Or the
ENDDO statement (2nd format) Or up to the statement number N0 (3rd format) are
executed.
c. Increase I by N3 i.e. I=I+N3
d. If I>N2 then go to the statement just after the do loop structure, otherwise go to step b.
Note that at the end of the do loop I is N2+N3 not N2. One also has to remember that it is
allowed to go out of the do loop from any location of the loop structure if required (when
certain condition is satisfied), but entry in the loop is permitted only at the beginning of the
loop structure.
Now we will write a program to find sum of a series which is S=1+2+3+4+......+100 i.e. sum first
100 integer numbers to explain the features. We explained the technique of summing a series
before.

P39-series-sum3.f:

C TO FIND SERIES SUM S=1+2+3+4+......+100


c USE OF DO LOOP
INTEGER SUM
WRITE(*,*)'PROGRAM TO FIND THE SERIES SUM GIVEN BY S=1+2+3+4+......+100'
SUM=0
DO 10 I=1,100 ! loop begins
SUM=SUM+I
10 CONTINUE ! loop ends
WRITE(*,*)'THE SUM IS =',SUM
STOP
END
OUTPUT:
C:\G77\work>p39-series-sum3

PROGRAM TO FIND THE SERIES SUM GIVEN BY S=1+2+3+4+......+100

THE SUM IS = 5050

In this case SUM=SUM+I is the only statement within the loop structure. Default increment of
the control variable I is 1. At the beginning of the loop, I=1. Since I<100, the looping is
continued. So, the value of SUM is SUM+I=0+1=1. The continue statement sends the control
back to the beginning of the loop. I becomes 1+1=2. Since still I<100, the looping is continued.
But now SUM=SUM+I=1+2=3. So effectively the first and the second integer is summed up. In
this manner the loop is continued till I=100 and the number 100 is added to the last SUM.
When I becomes 101 at the beginning of the next loop, the condition of end of the loop is
satisfied, the control is transferred to the statement immediately below the loop structure, i.e.
to the write statement whence the value of the sum is written.
Note that in the above program DO loop could also be written in the following ways:-
(i) DO I=1,100
SUM=SUM+I
END DO [ second format]

(ii) DO 10 I=1,100
10 SUM=SUM+I [ third format]

The above program may be modified to find sum of first N integers – Read N and write DO
I=1,N. If we want to get sum of all even integers up to N, we have to modify the DO statement
as DO I=2,N,2. For getting sum of odd integers, write DO I=1,N,2. To find sum of all integers
which are multiple of 5, write DO I=5,N,5.
Our next program is to find factorial of any number using Do loop. Since value of 13! onwards
cannot be stored in integer mode we have calculated factorial in real mode. A computer whose
CPU is of 64 bits, can store up to 2^64 – 1 as integer number. One can also use Stirling’s
approximation for factorials: n!=e-nnn Ö(2pn)
Modify it to find sum of first n integers
Modify it to find sum of first n odd integers
Modify it to find sum of first n even integers
Modify it to find sum of first n integers which are multiples of 5
Modify it to find sum of first n integers which are multiples of m
P40-factorial.f:
! PROGARM TO FIND THE FACTORIAL OF A NUMBER
WRITE(*,*)'ENTER THE NUMBER'
READ(*,*)N 10
FACT=1
DO I=1,N !loop begins
FACT=FACT*I
END DO !loop ends
WRITE(*,*)'FACTORIAL OF ',N,’ IS’,FACT
STOP
END
Note that in this case also the only executable statement within the do loop is FACT=FACT*I.
The loop continues N times, from I=1 to I=N, the increment value being 1. Since we need to find
the product 1.2.3.4……..N, we have set the initializer of the product to 1 (FACT=1) before the
loop begins (instead of SUM=0 in the previous example). The program works exactly in the
same manner as explained in the previous example.
OUTPUT-1:
ENTER THE NUMBER

FACTORIAL OF 6 IS 720.

OUTPUT-2:
ENTER THE NUMBER

12

FACTORIAL OF 12 IS 479001600.

OUTPUT-3:
ENTER THE NUMBER

13

FACTORIAL OF 13 IS 6.2270208E+009
Since value of 13! is beyond the integer number handling capacity of a 32 bit computer the
result is given in real form – which in integer form is 6227020800 and exact.

Modify it to find product of the first n odd integers


Modify it to find product of the first n even integers
Modify it to find product of the first n integers which are multiples of m

In the next example we find all factors of an integer. Note that a slight change in the program
P36 will give the desired result.

P41-factor.f:
C FIND ALL THE FACTORS OF AN INTEGER
write(*,*)'Input the no'
READ(*,*) N
WRITE(*,*) 'FACTORS OF ',N,' ARE:'
DO 10 I=1,N
K=MOD(N,I)
IF (K.EQ.0) WRITE(*,*) I
10 CONTINUE
STOP
END
OUTPUT-1:
Input the no

12

FACTORS OF 12 ARE:

4
6

12

OUTPUT-2:
Input the no

121

FACTORS OF 121 ARE:

11

121

We should be very careful while using do loops. Never a situation should be created when
unending loop is generated. This is explained in the following program.

P42-infinitedo.f
C unending loop
5 do i=1,1000
end do
goto 5
end
OUTPUT:
Once we execute this program it continues to run without any end. We have to terminate the program by pressing
ctrl+c keys together.

In this program the I loop is run for 1000 times. But after ending this do loop the control goes to
next statement, goto 5, which directs the control to the beginning of the I loop. So in effect the
I loop is run again and again and the loop never ends. So the program runs for infinite time.
Nested DO loops:
When one DO loop is constructed within another DO loop, it is called a nested DO loop. Inner
loop is evaluated first, then the outer loop.
Let’s explain with the help of following program:
Write a program to get 1 once, 2 twice, 3 thrice, 4 four times and 5 five times.

P43-print1.f:
!PROGRAM TO PRINT THE FOLLOWING OUT PUT
!1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
DO 10 I=1, 5 123
DO 20 J=1,I 1
WRITE(*,*)I
20 CONTINUE
10 CONTINUE
STOP
END
Note that the I loop (outer loop) will run 5 times. Within this, the J loop is generated (inner
loop), which will run for I times. Thus when I=1, J will run for 1 time, but when I=2, J will run for
2 times etc. So we get the desired output.
OUTPUT:
1

4
4

To apply the DO loop facility in various other problems we need to discuss the general form of
READ and WRITE statement and the FORMAT statement. Moreover, there is another important
form of DO loop called implied do loop which can be discussed only when we are familiar with
DIMENSIONAL variables, so will be discussed later.

PROGRAMS USING FORMAT STATEMENTS:

To read and write data in a specific way we can use general form of the read and write
statements which are discussed below.

…………………………………………………………………………………………………………………………..
READ STATEMENT:
The general format of the read statement is

READ(N1,N2) V1,V2,V3,…………

where,

N1 is the hardware number of the output device.

N2 is the line number of the FORMAT statement, discussed below.

V1, V2, V3,….… are the names of variables separated by comma.

N1= * denotes default input device which is the KEYBOARD. In most compilers N1=5 also points
to keyboard. Input device may also be a data file use of which will be discussed later.

N2= * means free format.

Data has to be entered one after another or type the data separated by space or comma and
enter.
WRITE STATEMENT:
The general format of a WRITE statement is

WRITE(N1,N2) V1,V2,V3,…………

where,

N1 is the hardware number of the output device.

N2 is the line number of the FORMAT statement, discussed next.

V1, V2, V3,….… are the names of variables separated by comma.

N1= * denotes default output device which is the MONITOR or computer screen. In most
compilers N1=6 also points to monitor. Output device may also be a data file use of which will
be discussed later.

N2= * means free format.

…………………………………………………………………………………………………………………………..
If something is written within single quotes, that message is displayed as such as discussed
before. However if there is an apostrophe symbol in the message, then the message has to be
placed within double quote. For example:
write(*,*) " adam's cat " is valid but write(*,*)'adam',''s cat' is not valid. This is used in Program
50.

FORMAT Specification:
The specification of the type of data (integer, real or character) and also its width is called
FORMAT specification.
Example: consider the constant -72.65375
The total width of this constant including sign and the decimal point is 9. There are 5 decimal
digits in the right side of the decimal point. That is
Total width=9
Decimal width=5
We say that this real constant has width 9.5
FORMAT Statements:
…………………………………………………………………………………………………………………………..
The general form of a FORMAT statement is

N FORMAT(S1, S2, ……Sr)

Where N is a statement number and S1, S2, ……Sr are the format specifications.

…………………………………………………………………………………………………………………………..
Carriage control:
In any output using FORMAT statement the first character of the output is lost, if the output
device is a printer. That is considered as the carriage control. So, the first character of the
output must be made a blank space so that the loss does not affect the output. However, this is
not required if the output is sent to computer monitor.

Different types of FORMAT statements:


1. I FORMAT
2. F FORMAT
3. E FORMAT
4. X FORMAT
5. / (slash) FORMAT
6. Quote FORMAT
7. A FORMAT
8. T FORMAT

1. I FORMAT:
…………………………………………………………………………………………………………………………..
General form of this statement is:
FORMAT (Iw)

The symbol Iw is used to denote the format of an integer quantity, w being its width.

…………………………………………………………………………………………………………………………..
Example: Let us consider an integer number -145
The number has width 4 (including sign). This data can be described by the FORMAT statement.

FORMAT (I4)

For three numbers such as 143, -363, and 648 we have to write FORMAT (I4, I4, I4).
This can also be written as FORMAT (3I4).
If a format statement is written as FORMAT (I7) then it can be used for an integer number
having maximum seven digits including sign.
To be on the safe side it is wise to specify width slightly higher than the maximum expected
width. If the actual data is of less width than specified in the format statement, then data will
be written in right adjusted way. This is also true for all subsequent formats.
2. F FORMAT:
…………………………………………………………………………………………………………………………..
Symbol Fw.d is used to specify the format of real numbers. Its general form is:
FORMAT (Fw.d)

Here w is total width of the data and d is number of digits after decimal points.

…………………………………………………………………………………………………………………………..
Consider the number -142.653
This has
Total width=8 (including sign and decimal point)
Decimal width=3
FORMAT (F8.3)
This is represented by the format statement
In case of a positive number, the “+” sign of the number is not counted for determining the
width of data.
Similarly, FORMAT (F10.3) will be used to read/display/print data of
maximum total width=10
and decimal width=3
But if for a real number say 1245.889 we specify the format statement as FORMAT (F7.2) then
the displayed number will be 1245.89 (rounded off to 2 decimal places).
1. E FORMAT:
This format is used to display the real data expressed in the exponent form.

…………………………………………………………………………………………………
………………………..
Its general form is:

Here w is total width of the data and d is number of digits after decimal points.

…………………………………………………………………………………………………
………………………..
Consider the constant -12.567512x10​-14
In exponential notation it is written as -12.567512E-14
Here the total width is 14
The decimal width of mantissa is 6
So, this number is represented by the FORMAT statement
Consider two numbers 3.52x10​12 and -1.578x10​-13​. These two numbers can be represented by
the FORMAT statement ​FORMAT (E7.2) and FORMAT (E10.3)

2. X FORMAT:
The symbol X is used to skip some columns in a data reading/writing.

…………………………………………………………………………………………………
………………………..
Its general form is

where N is the number of columns to be skipped.

…………………………………………………………………………………………………
………………………..
In case of output format this causes N blank spaces in the output.
Example: To print 123 if we write format statement as ​Format(5x,I4) - First five columns will
be skipped, 123 will be written in columns 7-9 (right adjusted).
5. / (slash) FORMAT:
The symbol slash (/) in format statement is used to move to the next line.

…………………………………………………………………………………………………
………………………..
Its general form is

…………………………………………………………………………………………………
………………………..
If we use four slashes then four lines will be skipped, i.e. four blank lines will be printed.
6. QUOTE FORMAT:

…………………………………………………………………………………………………
………………………..
Whatever is placed within quotes is printed as it is. For example, if we want to print the
message - You are welcome - then the corresponding format statement will be

…………………………………………………………………………………………………
………………………..
7. A FORMAT:
The A format is used for character data.

…………………………………………………………………………………………………
………………………..
The general form is

where w is the width. In this format w is optional. If w is not specified then the size of the
variable declared in the CHARACTER statement is considered as width.
…………………………………………………………………………………………………
………………………..
Suppose a variable N is declared as follows:
CHARACTER N*6
N=’ RAMESH ‘
Now if we use the format statement
FORMAT (1X, A)
Then the out will be RAMESH
Here the width is considered from the CHARACTER statement.
However, if we use the format statement ​FORMAT (1X, A4) ​then the output will be ​RAME.
8. T FORMAT:
This is used to print from a particular column.

…………………………………………………………………………………………………
………………………..
The general form is:

where n specifies the column from which the output must start.

…………………………………………………………………………………………………
………………………..
For example consider the format statement

The value of the first variable will be printed according to ​I5 format, after skipping 1 column.
Then the value of the second variable will ​start printing from column 10 (if the data width is 10,
for data with less width it will printed right adjusted manner). It must be noted that ​T10 does
not leave ten blank spaces​.
To see the necessity of general form of READ - WRITE statements and the FORMAT statement,
let us consider the following program where we want to find sine, cosine and tangent values at
four different angles. In program P14 we found the same values but at fixed angles 0, 30, 45
and 60 degrees. But in this program we can get the result for any values of the angles. Look into
the program and its output.

● P44-trig2.f:
C PROGRAM TO FIND TRIGINOMETRIC FUNCTION VALUES at 4 points
INTEGER X1,X2,X3,X4
REAL X1R,X2R,X3R,X4R
WRITE(*,*) 'INPUT 4 THETA VALUES'
READ(*,*) X1,X2,X3,X4
PI=ATAN(1.0)*4.
X1R=X1*PI/180.
X2R=X2*PI/180.
X3R=X3*PI/180.
X4R=X4*PI/180.
WRITE(*,*) 'THETA SINTH COSTH TANTH'
WRITE(*,*) X1,SIN(X1R),COS(X1R),TAN(X1R)
WRITE(*,*) X2,SIN(X2R),COS(X2R),TAN(X2R)
WRITE(*,*) X3,SIN(X3R),COS(X3R),TAN(X3R)
WRITE(*,*) X4,SIN(X4R),COS(X4R),TAN(X4R)
STOP
END
OUTPUT:
​INPUT 4 THETA VALUES
30 35 40 45

THETA SINTH COSTH TANTH

30 0.5 0.866025388 0.577350259

35 0.57357645 0.819152057 0.700207531

40 0.642787635 0.766044438 0.839099705


45 0.707106769 0.707106769 1.

In the output we get the values correctly but the output is not in desired tabulated form.
Let’s now modify this program using general form of READ-WRITE statement and Format
statement and get the output in the desired form. Use of other format specifications will be
discussed next.

● P45-trig3.f
C PROGRAM TO FIND TRIGINOMETRIC FUNCTION VALUES
C USE OF FORMATTED READ AND WRITE STATEMENT
INTEGER X1,X2,X3,X4
REAL X1R,X2R,X3R,X4R
WRITE(*,*) 'INPUT 4 THETA VALUES'
READ(5,11) X1,X2,X3,X4
11 FORMAT(4I3)
PI=ATAN(1.0)*4.
X1R=X1*PI/180.
X2R=X2*PI/180.
X3R=X3*PI/180.
X4R=X4*PI/180.
WRITE(6,*) 'THETA SINTH COSTH TANTH'
WRITE(6,12) X1,SIN(X1R),COS(X1R),TAN(X1R)
12 FORMAT(I6,3F10.5)
WRITE(6,12) X2,SIN(X2R),COS(X2R),TAN(X2R)
WRITE(*,12) X3,SIN(X3R),COS(X3R),TAN(X3R)
WRITE(6,12) X4,SIN(X4R),COS(X4R),TAN(X4R)
STOP
END
OUTPUT:
C:\G77\work>p45-trig3

INPUT 4 THETA VALUES


30 35 40 45

THETA SINTH COSTH TANTH

30 0.50000 0.86603 0.57735

35 0.57358 0.81915 0.70021

40 0.64279 0.76604 0.83910

45 0.70711 0.70711 1.00000

Output appears nicely formatted.


Since theta values are now read as formatted data (I3), these are to be entered as follows:
b30b35b40b45 [b stands for blank space]
Three columns are used for each data. Of course, we could have read the data in free format as
before. In the output WRITE statement FORMAT specification is used (F10.5). Since 3 variable
values are to written we have used 3F10.5, meaning each data will be written in F10.5 format.
Format specification F10.5 means that total data width is 10 including sign and five decimal
data points will be written in the output. In one of the WRITE statement we have used * instead
of number 6 to show that they have same effect. Similarly, in the read statement we could have
used * instead of device number 5. Note that format statement can be placed anywhere in the
program.
Write a program to generate a table of the square root, cube root, fourth root and fifth root of
numbers 0 to 10 in step of 0.5. Results should printed upto 5​th​ decimal place.
In the next example we find the angle between two vectors and the results are printed using
format statement. We know that if (x1,y1,z1) and (x2,y2,z2) are the components of two vectors,
then angle (θ) between them is given by

x1.x2+y1.y2+z1.z2
θ = cos−1
√x12 +y12 +z12 .√x22 +y22 +z22

● P46-angvec.f
C ANGLE BETWEEN TWO VECTORS
WRITE(*,*)'Input components of first vector'
READ(*,*) X1,Y1,Z1
WRITE(*,*)'Input components of second vector'
READ(*,*) X2,Y2,Z2
A=X1*X2+Y1*Y2+Z1*Z2
B=SQRT(X1**2+Y1**2+Z1**2)
C=SQRT(X2**2+Y2**2+Z2**2)
TH=ACOS(A/(B*C)) !remember acos means cos​-1
WRITE(*,*)'Components of first vector'
write(*,9) x1,y1,z1
WRITE(*,*)'Components of second vector'
write(*,9) x2,y2,z2
write(*,*)
write(*,*)'Angle Radian Degree'
WRITE(*,10) TH, TH*180/3.14159
9 FORMAT(3F7.2)
10 FORMAT(/5x,F9.2,2x,F9.2)
END
OUTPUT-1:
Input components of first vector

123

Input components of second vector

456

Components of first vector

1.00 2.00 3.00

Components of second vector

4.00 5.00 6.00

Angle Radian Degree

0.23 12.93
OUTPUT-2:
​Input components of first vector
12.35 3.45 -7.89

Input components of second vector

-1.34 15.56 -4.80

Components of first vector

12.35 3.45 -7.89

Components of second vector

-1.34 15.56 -4.80

Angle Radian Degree

1.26 72.25

In this program components of the vectors are read in free format but in the output,
components of the vectors are written in Format(3F7.2), which means all three variables are
printed in F7.2 format. But before that a header is printed in free format. Similarly, a header
regarding angle is printed in free format. Next, value of the angle is printed in
FORMAT(/5x,F9.2,2x,F9.2). The first / will produce a blank line, in the next line 5 columns will be
skipped by 5X, then angle in radian will be printed using F9.2 format, then 2 columns will be
skipped and finally angle in degree will be printed using again F9.2 format. Note that if the
angle data width is less than 9, then it will be printed right adjusted manner.
Write a program to find the distance between two points in 3D. All data should be printed upto
2​nd​ decimal place.
Another program explaining all the remaining format statements is shown below.
● P47-format.f
C Program to explain F, E, /, X, qoute and T format
write(*,*) 'Format test program'
a=1234.56789
write(*,*)
write(*,*)'a unformatted ',a
write(*,*) 'formatted a'
write(*,12) a,a,a,a
12 format(' a in f10.5 ',f10.5/,' a in f10.3',f10.3/,
1 ' a in f8.1 ',f8.1/,' a in e10.2',e10.2) ! 1 in 6​th​ column for continuation of the prev. line
c=3e10 done upto this
t=7.82e5
s=c*t
write(*,*)
write(*,*) 'c,t,s unformatted',c,t,s
write(*,15) c,t,s
15 format(5x,'formatted c, t and s',/,'c e15.5',e15.5/,'t e15.5'
1 ,e15.5/,'s e15.4',e15.4)
write(*,16)a,a,a
16 format(f10.5,T15,f10.5,T30,f10.5)
stop
end
OUTPUT:
Format test program

a unformatted 1234.56787

formatted a

a in f10.5 1234.56787

a in f10.3 1234.568

a in f8.1 1234.6

a in e10.2 0.12E+04

c,t,s unformatted 3.0000001E+010 782000. 2.34600004E+016

formatted c, t and s

c e15.5 0.30000E+11

t e15.5 0.78200E+06
s e15.4 0.2346E+17

1234.56787 1234.56787 1234.56787

Note that when a=1234.56787 is printed in f10.5 it is 1234.56787. When it is printed in f10.3
and f8.1 the values are 1234.568 and 1234.6, in each case the digit at the last decimal place is
rounded off. But when it is printed in e10.2 format the normalized output is 0.12e+04 which is
effectively 1200, much different from the actual value 1234.56787. So one has to be very
careful while using a format statement to print a variable whose value is given or calculated in a
different format type. But since the values of the variables c and s are large and are in
exponential form, no significant figure is lost when printed in e format. Even when t is printed
in e15.5, no loss of significant figures since actual t was also having 6 significant figures.
Because of the first / in the format statement 15, after printing the header ‘formatted c,t and s’
skipping first five columns, the variable c is printed in the next line. Same thing happens while
printing values of t and s. Format statement 16 causes printing of second a value from column
15 because of t15 format, and of third a value from column 30 because of t30 format.
Another program explaining all the remaining format statements is shown below.
● P47-format.f
C Program to explain F, E, /, X, qoute and T format
write(*,*) 'Format test program'
a=1234.56789
write(*,*)
write(*,*)'a unformatted ',a
write(*,*) 'formatted a'
write(*,12) a,a,a,a
12 format(' a in f10.5 ',f10.5/,' a in f10.3',f10.3/,
1 ' a in f8.1 ',f8.1/,' a in e10.2',e10.2) ! 1 in 6​th​ column for continuation of the prev. line
c=3e10 3x10^10
t=7.82e5
s=c*t
write(*,*)
write(*,*) 'c,t,s unformatted',c,t,s
write(*,15) c,t,s
15 format(5x,'formatted c, t and s',/,'c e15.5',e15.5/,'t e15.5'
1 ,e15.5/,'s e15.4',e15.4)

write(*,16)a,a,a
16 format(f10.5,T15,f10.5,T30,f10.5)
stop
end
OUTPUT:
Format test program

a unformatted 1234.56787

formatted a
a in f10.5 1234.56787

a in f10.3 1234.568

a in f8.1 1234.6

a in e10.2 0.12E+04

c,t,s unformatted 3.0000001E+010 782000. 2.34600004E+016

formatted c, t and s

c e15.5 0.30000E+11

t e15.5 0.78200E+06

s e15.4 0.2346E+17

1234.56787 1234.56787 1234.56787

Note that when a=1234.56787 is printed in f10.5 it is 1234.56787. When it is printed in f10.3
and f8.1 the values are 1234.568 and 1234.6, in each case the digit at the last decimal place is
rounded off. But when it is printed in e10.2 format the normalized output is 0.12e+04 which is
effectively 1200, much different from the actual value 1234.56787. So one has to be very
careful while using a format statement to print a variable whose value is given or calculated in a
different format type. But since the values of the variables c and s are large and are in
exponential form, no significant figure is lost when printed in e format. Even when t is printed
in e15.5, no loss of significant figures since actual t was also having 6 significant figures.
Because of the first / in the format statement 15, after printing the header ‘formatted c,t and s’
skipping first five columns, the variable c is printed in the next line. Same thing happens while
printing values of t and s. Format statement 16 causes printing of second a value from column
15 because of t15 format, and of third a value from column 30 because of t30 format.

The following program explains use of character format.


● P48-format2.f
C program to show use of character format A
character name1*20
character *25 name2,name3
write(*,*) 'what is your name ?'
read(*,11) name1
write(*,*) 'Name of your mother?'
read(*,12) name2
write(*,*) 'Name of your father?'
read(*,12) name3
write(*,*)
write(*,*) 'Name of candidate'
write(*,11)name1
write(*,*) 'Name of parents'
Write(*,12) name2,name3
11 format(A20)
12 format(2A25)
stop
end
OUTPUT:

C:\G77\work>p48-format2

what is your name ?

Sarat Chatterjee

Name of your mother?

Mahua Chatterjee

Name of your father?

Manab Chatterjee

Name of candidate

Sarat Chatterjee

Name of parents

Mahua Chatterjee Manab Chatterjee


Note that the character variable name1 is declared to be of maximum length 20 while Name2
and Name3 are of lengths 25. Name1 has been printed with A20 while the other two variables
are printed with format A25.

PROGRAMMES USING ARRAYS:

We have seen how to use variable name to store a single data. But often situation arises when
storing more than one data in a single variable is advantageous. In such situations we use
dimensional or subscripted variables or arrays. To explain the necessity and usefulness of arrays
let us consider the problem of finding the highest and lowest marks scored by a group of 10
students. We can write the following program.

● P49-highlow.f:
C FIND THE LOWEST AND HIGHEST MARKS OF​ ​10 STUDENTS
INTEGER BIG, SMALL
WRITE(*,*)'ENTER THE MARKS ONE BY ONE'
READ(*,*) M
BIG=M ! We initially assume that first data is maximum and minimum score
SMALL=M
DO I=2,10
READ(*,*) M
IF (BIG.LT.M) BIG=M ! If 2nd number is greater than 1st, It is stored as BIG
IF (SMALL.GT.M) SMALL=M ! Otherwise 1st number remains as big.
END DO ! this is repeated for remaining numbers
WRITE(*,*)'THE HIGHEST SCORE IS',BIG
WRITE(*,*)'THE LOWEST SCORE IS',SMALL
STOP
END
OUTPUT:
ENTER THE NUMBERS ONE BY ONE

10

35

31

43

90

THE HIGHEST SCORE IS 90

THE LOWEST SCORE IS 1

In the above program only the last score is available from the variable M. But if we want to
print all the scores first, then the highest and the lowest scores – we have to read the numbers
twice, first time to print the numbers and then again to compare the numbers to find the
highest and lowest scores. Alternatively we could have stored the scores in 10 separate
variable names. Obviously, if number of students is large, the above method of storing single
data in a single variable name is not a convenient method. One can, however, store many data
in a single variable easily by declaring the variable as an array or dimensional variable.
An array is considered as a set of similar type data items that can be referred to by a common
name with some index number or subscript in brackets after the array name signifying the
individual members.
General form is:

It starts with the key word dimension followed by name of the variable. m and n are dimensions
of the variable of total size=mxn. Number of dimensions depends on the variable type.
For example marks obtained by 10 students can be stored in a one dimensional array as
follows:

Marks of individual students are referred to as M(1), M(2), ……. M(10). M is called a one
dimensional variable of size 10. This method not only provides easy way of storing large
number of similar data but various operations can be performed on those data very easily. One
has to keep in mind that there is no problem if less number of data is stored in M, say 8, but it
can store maximum 10 data element.

But if we declare an array as

Then this signifies that M is a one dimensional array with the subscript varying from 0 to 10.
A two dimensional array can be declared as​:

Here both subscripts vary from 1 to 10, so one can store 10x10=100 data in it. First subscript
refers to row number of the array (row) and second refers to the column number. Thus A(7,3)
refers to seventh row and third column element of the array, i.e. 21​st data element and
A(10,10) refers to 100​th data element. A is called a two dimensional variable (or array) of size
100.
Similarly, a three dimensional array can be declared as:

Here the array A can store 12x15x8=1440 data elements.


Since dimension statement is used to declare dimension type of a variable, it has to be placed
before any executable statement in a program like other declaration statements. If a variable is
real as well as dimensional variable one may use following declaration statements:
Real A
Dimension A(15)
Or simply, Real A(15)
Both will have the same effect.
Ways to declare ARRAYs of different types:

Statement Meaning
INTEGER A (100, 100) A is declared as a two dimensional integer variable with both
the subscripts varying from 1 to 100.
REAL B (50, 100) A is declared as a two dimensional real variable where the
first subscript varies from 1 to 50 whereas the second
subscript varies from 1 to 100.

CHARACTER*20 D(15), D is declared as a one dimensional character variable with


Name(25) the subscript varying from 1 to 15.
Name is declared as a one dimensional character variable
with the subscript varying from 1 to 25.
In both cases, ​maximum width ​of character data is ​20​.

Let’s now see how we can find the maximum and the minimum score of the 10 students using
do loops on dimensional variable, at the same time we can print all the scores without reading
the data twice. Moreover, ​we also find the position of maximum and minimum score​.
● P50-highlow2.f:
C USE OF ARRAY
C FIND THE LOWEST AND HIGHEST SCORE OF 10 GIVEN SCORES
DIMENSION M(10)
INTEGER BIG, SMALL, PB, PS
WRITE(*,*)'ENTER THE NUMBERS ONE BY ONE'
DO I=1,10
READ(*,*) M(I) M(1) M(2) M(10)
ENDDO
write(*,*)'Scored numbers'
write(*,*) (M(I),I=1,10)
BIG=M(1) ! We initially assume that first data is maximum and minimum score
PB=1
SMALL=M(1)
PS=1
DO I=2,10
IF (BIG.LT.M(I)) THEN ! If M(4) is greater than M(1), in BIG value of M(4) is saved
BIG=M(I) ! Its position PB is changed to 4
PB=I
ENDIF
IF (SMALL.GT.M(I)) THEN ! If M(6) is less than M(1), in SMALL value of M(6) is saved
SMALL=M(I) ! Its position PB is changed to 6
PS=I
ENDIF
END DO
WRITE(*,*)'THE HIGHEST SCORE IS',BIG," IT'S POSITION ",PB
WRITE(*,*)'THE LOWEST SCORE IS',SMALL," IT'S POSITION ",PS
STOP
END
OUTPUT:
C:\G77\work>p50-highlow2

ENTER THE NUMBERS ONE BY ONE

12

31

42

35

67

89

92
30

66

61

Scored numbers

12 31 42 35 67 89 92 30 66 61

THE HIGHEST SCORE IS 92 IT'S POSITION 7

THE LOWEST SCORE IS 12 IT'S POSITION 1

Implied DO loops:
You may have noticed that in the above program we have used another form of DO loop in the
statement WRITE(*,*) (M(I),I=1,10). This is called implied do loop. This kind of loop structure
was not discussed before since we were not familiar with dimensional variables. We could have
written normal Do loop for this as follows:
DO 99 I=1,10
99 WRITE(*,*) M(I)
In that case the scored numbers would have been printed one in a line. But with implied do
loop all the data can be printed one after another in the same line.
General forms of implied do loops for a two dimensional array such as A(m,n) for reading and
writing data are as follows:

The row loop (m) is written as outer loop whereas the column loop is written as inner loop. In
this case for one value of outer loop variable I, inner loop variable J will vary from 1 to n. Outer
loop will vary from 1 to m.

Also note that since normal do loop is used to read the data ( line 6-7), we had to supply data
one in a line. If we supply more than one data in one line, only the first data is read. Until we
enter all the data, control does not move to the next line. It will be clear from the following
output:
OUTPUT:
C:\G77\work2>p50-highlow2

ENTER THE NUMBERS ONE BY ONE

1234

5678

9 10

Scored numbers

1597654321

THE HIGHEST SCORE IS 9.

THE LOWEST SCORE IS 1.

If instead we had used following implied do loop


READ(*,*) (M(I),I=1,10)
we could have supplied all ten data in one line separated by comma or space. However, In this
case data can also be supplied one in a line.
For a two dimensional array such as A(50,50) one can use following ​implied do loops for
reading and writing data as follows:
In this case for one value of outer loop variable I, say I=5, inner loop variable J will vary from 1
to 50.
Similarly implied Do Loop can be written for three dimensional variables.
Implied Do loop can also be used in data statement as follows:
data (x(i),i=1,8)/1 2 3 4 5 6 7 8/
data (y(i),i=1,8)/2 4 5 8 12 15 17 20/
In a previous program we printed 1 once, 2 twice, 3 thrice…. in separate lines. But suppose we
want to write them in separate lines in the form of a tree as shown below.
​ ​ ​ ​1
​ ​ ​2 2
​3 3 3
​ ​ ​ ​4 4 4 4
In the next program we do this task using implied do loop.

• P51-print2.f
!PROGRAM TO PRINT THE FOLLOWING OUTPUT
!1223333444455555
​INTEGER A(5)
​DO I=1,5 ​
​Do j=1,i
​A(j)=I ​ ​! Numbers are stored in one dimensional variable A
​enddo
​WRITE(*,*) (A(J),J=1,I)
​ENDDO
​STOP
​END

OUTPUT:
1
22
333
4444
55555
Suppose there are 10 numbers between 1 and 20. We want to find out the count of each number.
In other words we want to generate the frequency of occurrence of each number. This can be
done by the following program. We initialize all number counts or frequency to zero. After
reading a number, we increase the frequency of that number by 1.
• P52-freq1.f

C ​Frequency table of integer data


​dimension nf(100)
​write(*,*) 'Input no data points'
​Read(*,*) nd 10
​write(*,*) 'Input minimum and maximum values of the data'
​read(*,*) mind,maxd 1 20
do i=mind,maxd 1,20
nf(i)=0 ​ ​ ​!initialize all number counts or frequency to zero
enddo
do i=1,nd 10
​write(*,*) 'input data',I 3 7 9 11 3
read(*,*) nv
nf(nv)=nf(nv)+1 ​ ​ ​! increase frequency of the number by 1
enddo
write(*,*)'No Count of no'
do i=mind,maxd 1,20
write(*,*) i,' ', nf(i)
enddo
end
OUTPUT:
Input no data points
10
Input minimum and maximum values of the data
1 20

input data 1
3

input data 2
7

input data 3
9

input data 4
11

input data 5
3

input data 6
7

input data 7
13

input data 8
19

input data 9
13

input data 10
13
No Count of no
1 ​0
2 ​0
3 ​2
4 ​0
5 ​0
6 ​0
7 ​2
8 ​0
9 ​1
10 ​ 0

11 ​1
12 ​ 0

13 ​3
14 ​0
15 ​0
16 ​0
17 ​0
18 ​0
19 ​1
20 ​0
In the above program we have printed frequency of each numbers between 1 and 20, even if the
count of a particular number is zero. But we may be interested to get only the non-zero frequency
count. By making only one change in the above program we can achieve this task. Look at the
output write statement portion.
• P53a-freq2.f

C ​Frequency table of integer data


integer nf(100)
​write(*,*) 'Input no data points'
Read(*,*) nd
​write(*,*) 'Input minimum and maximum values of the data'
​read(*,*) mind,maxd
do i=mind,maxd
nf(i)=0
enddo
do i=1,nd
write(*,*) 'input data',i
read(*,*) nv
nf(nv)=nf(nv)+1
enddo
write(*,*)'No Count of no'
do i=mind,maxd
if (nf(i).ne.0) write(*,*) i,' ', nf(i) do i=mind,maxd
enddo write(*,*) i,' ', nf(i)
end enddo
OUTPUT:
Input no data points
5
Input minimum and maximum values of the data
1 10

input data 1
5

input data 2
3

input data 3
5

input data 4
7

input data 5
9
No Count of no
3 1
5 2
7 1
9 1
While writing the above program we assumed that the maximum and minimum of the data were
known and entered these two data for calculation purpose. If we have large number of data, then
finding the maximum and minimum data values manually may not be easy. So we want to
modify the program so that the program also finds the maximum and minimum data values.
Modified program is shown below.
• P53b-freq3.f:

C ​Frequency table of integer data


integer nv(100),nf(100)
​write(*,*) 'Input no data points'
Read(*,*) nd
C ​write(*,*) 'Input minimum and maximum values of the data'
C ​read(*,*) mind,maxd
WRITE(*,*)'ENTER THE NUMBERS ONE BY ONE'
do i=1,nd
​read(*,*) nv(i)
​enddo
​write(*,*)'Data values'
​write(*,*) (nv(i),i=1,nd)
​mind=nv(1)
​maxd=nv(1)
​DO I=2,nd
​ IF (maxd.LT.nv(I)) maxd=nv(I)
​ IF (mind.GT.nv(I)) mind=nv(I)
​ END DO
​write(*,*) 'Maximum data value',maxd
​write(*,*) 'Maximum data value',mind
do i=mind,maxd
nf(i)=0
enddo
​do i=1,nd
nf(nv(i))=nf(nv(i))+1 nf(nv)=nf(nv)+1
enddo
write(*,*)'No Count of No'
do i=mind,maxd
if (nf(i).ne.0) write(*,*) i,' ', nf(i)
enddo
end
OUTPUT:
C:\G77\work>p53b-freq3
Input no data points
10
ENTER THE NUMBERS ONE BY ONE
23
32
37
29
13
32
23
37
32
32
Data values
23 32 37 29 13 32 23 37 32 32
Maximum data value 37
Minimum data value 13
No Count of No
13 1
23 2
29 1
32 4
37 2
Modify the program to accommodate the situation when we don’t know
beforehand the number of data to be handled.

Suppose we want to find sum of three integers (triplets), for a certain number of such triplets. For
this we may write the following program. Here the inner loop in j is for summing the integers,
while the outer loop in i is for number of such operations.
• P54-triplet.f

C ​To find sum of three integers specified times


​write(*,*)'input how many times you want to sum'
read*,n
do 10 i=1,n
mt=0
write(*,*)'input integers one after another'
do 20 j=1,3
read*,m
20 mt=mt+m
print*,'sum ',i,' sum value ',mt
10 continue
end
OUTPUT:
C:\G77\work>p54-triplet

input how many times you want to sum


2

input integers one after another


3
6
9

sum 1 sum value 18

input integers one after another


12
14
18

sum 2 sum value 44

2
Next we write a program for to find the integers, upto 100, which form Pythagorian triplet (a +
2 2
b = c ) and find sum of the integers forming the triplets.
• P55-pytha.f

C ​find Pythagorian triplets a^2 + b^2 = c^2


C ​using integers upto 100 and find sum of the triplet forming integers
​write(*,*) 'Pythagorian triplets sum'
​do 10 i=1,100
​do 10 j=i+1,100
​do 10 k=i+2,100
​if ((i**2 + j**2).eq.k**2) then
​sum=i+j+k
​write(*,*) i, j, k,' ', sum
​endif
10 continue
end
OUTPUT:
C:\G77\work>p55-pytha
Pythagorean triplets sum

345 12.

5 12 13 30.

6 8 10 24.

7 24 25 56.

8 15 17 40.

9 12 15 36.

9 40 41 90.

10 24 26 60.

11 60 61 132.

12 16 20 48.

12 35 37 84.

13 84 85 182.

14 48 50 112.

15 20 25 60.

15 36 39 90.

16 30 34 80.

16 63 65 144.

18 24 30 72.

18 80 82 180.

20 21 29 70.

20 48 52 120.

21 28 35 84.

21 72 75 168.

24 32 40 96.

24 45 51 120.

24 70 74 168.

25 60 65 150.

27 36 45 108.

28 45 53 126.

28 96 100 224.

30 40 50 120.

30 72 78 180.

32 60 68 160.
33 44 55 132.

33 56 65 154.

35 84 91 210.

36 48 60 144.

36 77 85 198.

39 52 65 156.

39 80 89 208.

40 42 58 140.

40 75 85 200.

42 56 70 168.

45 60 75 180.

48 55 73 176.

48 64 80 192.

51 68 85 204.

54 72 90 216.

57 76 95 228.

60 63 87 210.

60 80 100 240.

65 72 97 234.
Modify P55 to change the output to a nice table using format statement
As a use of implied and nested Do Loops we consider next the problem of finding the prime
numbers between 1 and 1000. Prime numbers are those numbers which are divisible by
themselves and 1. Logic will be to check whether the remainder is zero when it (say N) is
divided by all numbers from 2 up to the number N-1. If the answer is yes, the number is not
prime, otherwise it is prime. In fact, it will be sufficient if we divide the number up to the
number (nc) – square root of N plus 1, because continuation after that will be repetition of
previous checks.
• P56-prime1.f:
C ​To find Prime nos upto 100 17 2,3,4,5,6,7,…..16 2,3,4,5 3,2 2,5
​Integer c
write(*,*) 'Prime nos upto 100'
​c=0 ​ ​ ​! Initializer to count no of prime numbers
​do 10 i=2,100 ​ ​!to check all numbers between 2 and 100
​nc=sqrt(real(i))+1
​do 20 j=2,nc ​ ​!each number is divided by all numbers upto nc
​if (i.eq.2) goto 7 ​!two is taken as prime
​if (mod(i,j).eq.0) goto 10 !condition true means the number is not prime, chk next
20 ​continue
7 ​c=c+1
​write(*,*) i
10 continue
​write(*,*) 'total count', c
end
OUTPUT:
C:\G77\work>p56-prime1
Prime nos upto 100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

total count 25
So there are 25 prime numbers till 100. The prime numbers are written one in a line, so we need
25 lines. Can’t we write several prime numbers in one line so that we need less space?
This is precisely what we have done in the next program. In this case we have found prime
numbers till 1000. Instead of printing them immediately, we have stored them in an array
variable. Then we printed 12 of them in one line using a format statement.
• P57-prime2.f:
C ​ FIND PRIME NUMBERS BETWEEN 1 TO 1000
C ​USE OF NESTED AND IMPLIED DO LOOPS
​ INTEGER PRIME(1000),PC
​PC=0
​DO 10 I=2,1000
​NC=SQRT(REAL(I))+1
​ DO J=2,NC
​if (i.eq.2) goto 7
C ​IR=I-I/J*J ​ ​!Alternative of mod(I,j)
​IR=MOD(I,J)
​ IF (IR.EQ.0.0) GOTO 10
​ ENDDO
7 ​PC=PC+1
​PRIME(PC)=I
10 ​CONTINUE
​WRITE(*,*) 'COUNT OF PRIME NUMBERS BETWEEN 1 AND 1000:',PC
​WRITE(6,12) (PRIME(I),I=1,PC)
12 ​FORMAT(12I5)
​STOP
​END
OUTPUT:
COUNT OF PRIME NUMBERS BETWEEN 1 AND 1000: 168
2 3 5 7 11 13 17 19 23 29 31 37
41 43 47 53 59 61 67 71 73 79 83 89
97 101 103 107 109 113 127 131 137 139 149 151
157 163 167 173 179 181 191 193 197 199 211 223
227 229 233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349 353 359
367 373 379 383 389 397 401 409 419 421 431 433
439 443 449 457 461 463 467 479 487 491 499 503
509 521 523 541 547 557 563 569 571 577 587 593
599 601 607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733 739 743
751 757 761 769 773 787 797 809 811 821 823 827
829 839 853 857 859 863 877 881 883 887 907 911
919 929 937 941 947 953 967 971 977 983 991 997
Suppose we want to find sum of factorials of all integers till n, value of which should be read
while running the program. But if N goes beyond 12, the value of sum cannot be stored in
integer mode. Program will be as follows:
● P58-series-sum4:
C Find 1! + 2! + 3! +.......+ n! '
40 WRITE(*,*)'INPUT THE VALUE OF N, max value 12'
READ(*,*)N
IF(N.GT.12) GOTO 40
IS=0

DO 10 I=1,N
LP=1
DO 20 K=1,I
LP=LP*K
20 CONTINUE
IS=IS+LP
10 CONTINUE
WRITE(*,*)'THE VALUE OF SUMMATION=',IS
END
OUTPUT-1:
INPUT THE VALUE OF N

THE VALUE OF SUMMATION= 153

OUTPUT-2:
INPUT THE VALUE OF N

10

THE VALUE OF SUMMATION= 4037913

1 100 20.26s 18.09s 18.0s sakib ali CPU GHz 10​9​s


Now we consider a completely different type of problem. Modern computers have CPU which
has speed in GHz order i.e. 10​9 Hz/sec. How fast is this speed? It should be able to count 10​9
numbers roughly in one second if the speed is really so fast. Compare how much time you need
to count upto only 10​3​! How can we check the speed? How can we ask the computer to count
numbers? This can be done as follows: we generate a loop and no task is placed within the
loop. Then the computer will basically count the number up to the loop. How to measure the
time the computer is really taking. This can be done by using ​secnds(0.0) ​function which
provides clock time in seconds.

Difference of clock time at the beginning and end of the counting will give us the elapsed time
for counting. The program is shown below:

● P59-count1.f:
C program to count numbers and time of counting
write(*,*)'Counting 10 billion ....'
t=secnds(0.0) !secnds(0.0) outputs clock time in seconds
do i=1,1000000 !since my computer cannot store 10^9 in integer mode
do j=1,10000
enddo
enddo
t=secnds(0.0) -t
write(*,*) 'Time to count 10 billion',t,' seconds'
end
Note that since even 64 bit CPU machine cannot hold 1000000000 as integer, we had to
generate two loops.
OUTPUT:
C:\G77\work>p59-count1

Counting 10 billion ....

Time to count 10 billion 22. seconds


So its taking just 22 seconds! It may be noted that the CPU is not only counting numbers upto
10​9​, it is also checking after each looping whether the loop end number has been reached or
not. Otherwise it would have taken lesser time! Note that your computer may take different
time!
There is another facility in fortran to find the time which is the built-in subroutine cpu_time(v1).

where v1 is any variable name.

It stores cpu clock time, in fractions of seconds, at the instant of calling the subroutine, in the
variable v1. Concept of subroutine is discussed later. We re-write the above program to find
time for head count of Indian population (130 billion).
● P60-count2.f
C time to head count Indian population 130 billion
real start, finish
write(*,*) 'Counting 130 billion .....'
call cpu_time(start)
do i=1,1000000
do j=1,130000
enddo
enddo
call cpu_time(finish)
write(*,12) finish-start
12 format(f10.3,'secs')
end
OUTPUT:
C:\G77\work>p60-count2

Counting 130 billion .....


302.219 secs

Note it has given time in fractions of a second. So it takes little more than 5 mins.

So far we were generating do loops only with integer variables. We can use real numbers also.
This is explained by the following program.
Suppose we want to calculate the Fourier sum of a function f(x) for x=0 to x=3.2 in step of 0.4.
f(x) is given by
m nπ
f (x) = ∑ (an sin sin nx ) ​where​ an = 2
n2 π
− cos cos nπ
n
n=1

How many terms to consider in the summation (value of m) will be decided at the time of
running the program.

● P63-fouriersum.f:
C example of fractional increment in do loop
C calculation of a Fourier series
dimension cf(50)
write(*,*)'Input no of Fourier coefficients to be taken'
read(*,*) m
write(*,*)'No of Fourier coefficients to be taken ',m
C calculate coefficients
do 10 n=1,m
10 cf(n)=2*sin(n*3.1416/2)/(n*n*3.1416)-cos(n*3.1416)/n
write(*,*)'x f(x)'
do 100 x=0,3.2,.4
fx=0
do 20 n=1,m
20 fx=fx+cf(n)*sin(n*x)
write(*,12) x,fx
100 continue
12 format(F4.2,4x,F8.3)
end
OUTPUT-1:
C:\G77\work>p63-fouriersum

Input no of Fourier coefficients to be taken

25

No of Fourier coefficients taken 25

x f(x)

0.00 0.000

0.40 0.386

0.80 0.822

1.20 1.183

1.60 1.570

2.00 1.595

2.40 1.517

2.80 1.648

3.20 -1.318

OUTPUT-2:
C:\G77\work>p63-fouriersum

Input no of Fourier coefficients to be taken

10

No of Fourier coefficients to be taken 10

x f(x)

0.00 0.000

0.40 0.440

0.80 0.761

1.20 1.195

1.60 1.614

2.00 1.497

2.40 1.551
2.80 1.824

3.20 -0.602

We know that computers ultimately work on binary numbers. How to manually get these
binary numbers from decimal numbers that procedure is known to us. We write a program to
convert a decimal integer into its binary equivalent. Remember that to get the binary
equivalent we have to divide the number by 2, note the remainder, continue the process till the
quotient is 1 which will be the last remainder. Then taking the remainders in reverse order will
give the binary number.
● P64a-decbin1.f:
C Program to find the binary equivalent of a decimal integer
dimension IR(20) !*** binary equivalent should not be of more than 25 digits***
WRITE(*,*)'Input number'
READ(*,*)N
m=n
J=1
5 IR(J)=MOD(N,2) !find the remainder when divided by 2
IQ=N/2 !find the quotient IQ
IF (IQ.EQ.1) GOTO 10 !when the quotient is 1, terminate the process
N=IQ !take quotient as the number N
J=J+1
GOTO 5
10 IR(J+1)=IQ
WRITE(*,*)'Decimal no.',M,' Equivalent binary no.',(IR(J),J=J+1,1,-1)
END
OUTPUT:
Input number

26

Decimal no. 26 Equivalent binary no. 1 1 0 1 0


In the above program we converted a decimal integer number to its equivalent binary number.
Now we want do the reverse work i.e. binary to decimal conversion. Suppose the binary
number is 10101. Its decimal equivalent is calculated in the following way:
1 0 1 0 1 1111101
Position number of the digits 4 3 2 1 0
Value 1x2​4​ + ​0x2​3​ + 1x2​2​ + ​0x2​1​ +1x2​0​ = 21
Number at the zeroth position is found by mod(10101,10)=1 decimal value= 1x2​0
To get the 1​st position number we first do integer division 10101/10 which gives 1010, the
mod(1010,10) gives the required number=0 decimal value=0x2​1
This process is continued till the integer division results in 1. Its decimal value=1x2​4​.
Sum of all the decimal values gives equivalent decimal number. This is implemented in the next
program.
● P64b-bindec.f:
C Program to find the decimal equivalent of a binary integer
dimension IR(20)
write(*,*)'Program valid for only integer binary number'
Write(*,*)
WRITE(*,*)'Input binary number'
READ(*,*)N
M=N
J=1
S1=0
5 IR(J)=MOD(N,10)
S1=S1+IR(J)*2**(J-1)
IQ=N/10
IF (IQ.EQ.1) GOTO 10
N=N/10
J=J+1
GOTO 5
10 S1=S1+IQ*2**J
40 WRITE(*,*)'Binary no.',M,' Equivalent decimal no.',S1
END
OUTPUT-1:
C:\G77\work>p64b-bindec

Program valid for only integer binary number

Input binary number

1111

Binary no. 1111 Equivalent decimal no. 15.

OUTPUT-2:
C:\G77\work>p64b-bindec

Program valid for only integer binary number

Input binary number

1010101

Binary no. 1010101 Equivalent decimal no. 85.


In the above program we converted a decimal integer number to its equivalent binary number.
Now we want do the reverse work i.e. binary to decimal conversion. Suppose the binary
number is 10101. Its decimal equivalent is calculated in the following way:

1 0 1 0 1 1111101
Position number of the digits 4 3 2 1 0
Value 1x2​4​ + ​0x2​3​ + 1x2​2​ + ​0x2​1​ +1x2​0​ = 21
Number at the zeroth position is found by mod(10101,10)=1 decimal value= 1x2​0
To get the 1​st position number we first do integer division 10101/10 which gives 1010, the
mod(1010,10) gives the required number=0 decimal value=0x2​1
This process is continued till the integer division results in 1. Its decimal value=1x2​4​.
Sum of all the decimal values gives equivalent decimal number. This is implemented in the next
program.
● P64b-bindec.f:
C Program to find the decimal equivalent of a binary integer
dimension IR(20)
write(*,*)'Program valid for only integer binary number'
Write(*,*)
WRITE(*,*)'Input binary number'
READ(*,*)N

M=N
J=1
S1=0
5 IR(J)=MOD(N,10)
S1=S1+IR(J)*2**(J-1)
IQ=N/10
IF (IQ.EQ.1) GOTO 10
N=N/10
J=J+1
GOTO 5
10 S1=S1+IQ*2**J
40 WRITE(*,*)'Binary no.',M,' Equivalent decimal no.',S1
END
OUTPUT-1:
C:\G77\work>p64b-bindec

Program valid for only integer binary number

Input binary number

1111

Binary no. 1111 Equivalent decimal no. 15.

OUTPUT-2:
C:\G77\work>p64b-bindec

Program valid for only integer binary number

Input binary number

1010101

Binary no. 1010101 Equivalent decimal no. 85.

Let us now see how to convert a fractional decimal number to its binary equivalent. In this case
the fractional number is to be multiplied by 2. Integral part of the result is to be taken as the
first binary digit of the equivalent number. This process is continued and integral parts are
considered as second, third… binary digits of the equivalent number till the fractional part
becomes zero. In most cases, exact binary equivalent is not obtained, then the process is
interrupted after a certain number of terms. Following program does the job.
● P65-decbin2.f:
C Program to find the binary equivalent of a decimal fraction
dimension IR(20)
WRITE(*,*) 'Input decimal fraction number' 1/3
read(*,*) f
FOLD=F ​.25 x 2 = 0.50 0
I=1 ​.50 x 2 = 1.00 1 .01

10 F2=2*F ​0 x 2​-1​ + 1 x 2​-2​ = .25


G=INT(F2) ! finds the integer part of F2
IR(I)=G
F=F2-G
IF ((F.EQ.0).OR.(I.ge.19)) GOTO 20
I=I+1
GOTO 10
20 WRITE(*,*) 'Decimal fraction number',FOLD
If (i.le.18) then
write(*,*) 'Equivalent binary number .',(IR(J),J=1,I)
else
write(*,*) 'Equivalent binary number (approx) .',(IR(J),J=1,I)
endif
END
OUTPUT-1:
Input decimal fraction number

.15625

Decimal fraction number 0.15625

Equivalent binary number . 0 0 1 0 1

OUTPUT-2:
​Input decimal fraction number
.2

Decimal fraction number 0.200000003

Equivalent binary number (approx) . 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1

Natural end is to write a program which can handle a number which has both integral and
fractional part. We combine the above two programs and make necessary obvious
modifications to get the final program for this task.
● P66-decbin3:
C Program to find the binary equivalent of a real number
dimension IR(20),IIR(20)
WRITE(*,*)'Input real number'
READ(*,*)F
FOLD=F
N=INT(F) !find the integer part
J=1
5 IIR(J)=MOD(N,2)
IQ=N/2
IF (IQ.EQ.1) GOTO 10
N=N/2
J=J+1
GOTO 5
10 IIR(J+1)=IQ
I=1
F=F-int(F) !find the fractional part
20 F2=2*F
G=INT(F2)
IR(I)=G
F=F2-G
IF (F.EQ.0) GOTO 40
I=I+1
GOTO 20
40 WRITE(*,*) 'Decimal fraction number',FOLD
write(*,*) 'Equivalent binary number ',(IIR(J),J=J+1,1,-1),' .',(IR(J),J=1,I)
end
OUTPUT-1:
Input real number

5.625

Decimal fraction number 5.625

Equivalent binary number 1 0 1 . 1 0 1

OUTPUT-2:
Input decimal number

Decimal fraction number 5.

Equivalent binary number 1 0 1 . 0

OUTPUT-3:
Input decimal number
14.2

Decimal fraction number 14.1999998

Equivalent binary number 1 1 1 0 . 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1

Note that in this case the program has terminated normally since the decimal fraction becomes
so small that it is effectively zero, and the program termination condition is satisfied.

Next we consider problems involving ​matrix algebra which is extensively used in all branches of
science, especially in physics and engineering. Suppose we want to read and write a matrix of
any size (maximum 10x10), this can be done by the following program. Since the element a​i,j has
two suffixes which varies over m (for i, row) and n (for j, column), we need two do loops – one
for i and other for j.
● P67-matread.f:

!PROGRAM TO READ AND WRITE A MATRIX


DIMENSION A(10,10)
WRITE(*,*)'ENTER THE NO.OF ROWS(M) & COLUMNS(N)'
READ(*,*)M,N 23
WRITE(*,*)'ENTER THE MATRIX(ROWISE)'
DO I=1,M 123 456
READ(*,*)(A(I,J),J=1,N) ! One has to input data row wise
END DO
WRITE(*,*)'THE MATRIX IS'
DO I=1,M
WRITE(*,*)(A(I,J),J=1,N)
END DO
STOP
END
OUTPUT:
ENTER THE NO.OF ROWS (M) & COLUMNS (N)

23

ENTER THE MATRIX (ROW WISE)

123

456

THE MATRIX IS

1. 2. 3.

4. 5. 6.

Note that if write


DO I=1,M
DO J=1,N
WRITE(*,*) (A(I,J)
END DO
END DO
Instead of
DO I=1,M
WRITE(*,*)(A(I,J),J=1,N)
END DO
then the matrix elements will be printed one in a line.

MATRIX ADDITION:
Suppose A and B two matrices of same order.

Let A= and B=

Let C= A + B

If we denote C=
Then c11= a11 + b11
c12= a12 + b12
and so on.

● P68-matadd.f:
! PROGRAM TO ADD TWO REAL MATRICES
DIMENSION A(10,10),B(10,10),S(10,10)
WRITE(*,*)'ENTER THE NO.OF ROWS & COLUMNS OF THE TWO MATRICES TO BE ADDED'
READ(*,*)N,M
write(*,*)
WRITE(*,*)'ENTER THE 1ST MATRIX ROW WISE'
! READING 1ST MATRIX
DO I=1,N
READ(*,*)(A(I,J),J=1,M)
END DO
write(*,*)
WRITE(*,*)'ENTER THE 2ND MATRIX ROW WISE'
! READING 2ND MATRIX
DO I=1,N
READ(*,*)(B(I,J),J=1,M)
END DO
! ADDITION
DO I=1,N
DO J=1,M
S(I,J)=A(I,J)+B(I,J)
END DO
END DO
! PRINTING INPUT MATRICES
write(*,*)
WRITE(*,*)'1ST INPUT MATRIX'
DO I=1,N
WRITE(*,*)(A(I,J),J=1,M)
END DO
write(*,*)
WRITE(*,*)'2ND INPUT MATRIX'
DO I=1,N
WRITE(*,*)(B(I,J),J=1,M)
END DO
! PRINTING OF SUMMED MATRIX
write(*,*)
WRITE(*,*)'ADDITION MATRIX'
DO I=1,N
WRITE(*,*)(S(I,J),J=1,M)
END DO
STOP
END

OUTPUT:

ENTER THE NO.OF ROWS & COLUMNS OF THE TWO MATRICES TO BE ADDED

33

ENTER THE 1ST MATRIX ROW WISE

123
456

789

ENTER THE 2ND MATRIX ROW WISE

987

654

321

1ST INPUT MATRIX

1. 2. 3.

4. 5. 6.

7. 8. 9.

2ND INPUT MATRIX

9. 8. 7.

6. 5. 4.

3. 2. 1.

ADDITION MATRIX

10. 10. 10.

10. 10. 10.

10. 10. 10.

TRANSPOSE MATRIX
Similarly one can write a program to get transpose (B) of a given matrix (A), by generating it
using the relation: b​ij​=a​ji​. However, if the matrix is not a square matrix, then while calculating
the elements of the transposed matrix, the row and column numbers have also to be
interchanged. The program is written below:

● P69-transmat.f:
C PROGRAM TO find a transposed matrix
INTEGER A(10,10), B(10,10)
WRITE(*,*)'ENTER THE NO.OF ROWS(M) & COLUMNS(N)'
READ(*,*)M,N
WRITE(*,*)'ENTER THE MATRIX(ROW WISE)'
DO I=1,M
READ(*,*)(A(I,J),J=1,N)
END DO
WRITE(*,*)'THE MATRIX IS'

DO I=1,M
WRITE(*,*)(A(I,J),J=1,N)
END DO
DO I=1,N
DO J=1,M !row and column numbers interchanged
B(I,J)=A(J,I)
END DO
ENDDO
WRITE(*,*)'THE TRANSPOSE MATRIX IS'
DO I=1,N
WRITE(*,*)(B(I,J),J=1,M) !rows and column nos have also been changed
END DO
STOP
END
OUTPUT-1:
C:\G77\work>p69-transmat

ENTER THE NO.OF ROWS(M) & COLUMNS(N)

33

ENTER THE MATRIX(ROW WISE)

123
456

789

THE MATRIX IS

123

456

789

THE TRANSPOSE MATRIX IS

147

258

369

​OUTPUT-2:

C:\G77\work>p69-transmat

ENTER THE NO.OF ROWS(M) & COLUMNS(N)

34

ENTER THE MATRIX(ROW WISE)

1234

5678

9 10 11 12

THE MATRIX IS

1234

5678

9 10 11 12

THE TRANSPOSE MATRIX IS

159

2 6 10

3 7 11

4 8 12

MATRIX MULTIPLICATION:
Suppose A and B are two matrices. If we want to multiply them, number of columns in A must
be equal to number of rows in B.
Suppose A is a “m × n”matrix and B is a “n × l” matrix. Then if we multiply them, the product
matrix say C will be a “m ×l” matrix.
For simplicity let us consider A and B as 2×2 matrix given by

A= and B=

Let C= A × B

If we denote C=

Then
c11= a11 × b11 + a12 × b21
c12= a11 × b12 + a12 × b22
c21= a21 × b11 + a22 × b21
c22= a21 × b21 + a22 × b22
To find c11 we have to multiply a11 by b11 and a12 by b21 and add them, similarly for other
elements.

For writing the program we have to use the following loops. First two loops for the subscript i
(row) and j (column) and the third loop for the product loop on k.
1
2

Let’s see how this works. We consider, M=2, N=2, l=2


For I=1, J=1​:
When K=1,C(1,1)= C(1,1) + A(1,1) ×B(1,1)= A(1,1) ×B(1,1) [since initially C(I,J)=0]
When k=2, C(1,1)=C(1,1)+A(1,2) ×B(2,1)
Hence we get C(1,1)=A(1,1) ×B(1,1)+A(1,2) ×B(2,1)
When k=3, C(1,1)=C(1,1)+A(1,3) ×B(3,1)
Hence finally we get C(1,1)=A(1,1) ×B(1,1)+A(1,2) ×B(2,1)+ A(1,3) ×B(3,1) which is the required
formula for C(1,1).
In the same way other coefficients of matrix C is evaluated.
● P70-matmult.f:
C MATRIX MULTIPLICATION
DIMENSION A(10,10),B(10,10),C(10,10)
WRITE(*,*)'ENTER ROW & COLUMN NOS OF THE 1ST MATRIX'
READ(*,*)N1,M1
WRITE(*,*)'ENTER ROW & COLUMN NOS OF THE 2ND MATRIX'
READ(*,*)N2,M2
WRITE(*,*)'ENTER THE 1ST MATRIX'
DO I=1,N1
READ(*,*)(A(I,J),J=1,M1)
END DO
WRITE(*,*)'ENTER THE 2ND MATRIX'
DO I=1,N2
READ(*,*)(B(I,J),J=1,M2)
END DO
!MULTIPLICATION
WRITE(*,*)'THE PRODUCT IS'
DO I=1,N1
DO J=1,M2
C(I,J)=0
DO K=1,M1
C(I,J)=C(I,J)+A(I,K)*B(K,J)
END DO
END DO
END DO
DO I=1,N1
WRITE(*,*)(C(I,J),J=1,M2)
END DO
STOP
END
OUTPUT-1:
C:\G77\work2>p70-matmult

ENTER ROW & COLUMN NOS OF THE 1ST MATRIX

33

ENTER ROW & COLUMN NOS OF THE 2ND MATRIX

33

ENTER THE 1ST MATRIX

123

456

789

ENTER THE 2ND MATRIX

10 11 12

13 14 15

16 17 18

THE PRODUCT IS

84. 90. 96.

201. 216. 231.

318. 342. 366.

OUTPUT-2:
C:\G77\work2>p70-matmult
ENTER ROW & COLUMN NOS OF THE 1ST MATRIX

23

ENTER ROW & COLUMN NOS OF THE 2ND MATRIX

34

ENTER THE 1ST MATRIX

123

456

ENTER THE 2ND MATRIX

1234

5678

9123

THE PRODUCT IS

38. 17. 23. 29.

83. 44. 59. 74.


We now write a program to calculate the mean, variance and standard deviation of a data set.
We know, if x1,x2,x3 …..xn are n data points then

Mean = (∑ xi )/n

Sample variance = (∑ (xi − xmean )2 )/(n − 1)

Population variance= (∑ (xi − xmean )2 )/n

Sample standard deviation = S qrt((∑ (xi − xmean )2 )/(n − 1))

Population standard deviation = S qrt((∑ (xi − xmean )2 )/n)

● P74-meanstd.f:
C calculation of mean and standard deviation
dimension x(100)
write(*,*) 'Input no of data points'
read(*,*) n
write(*,*) 'Input data '
read(*,*) (x(i),i=1,n)

c calculate mean
sx=0
do i=1,n
sx=sx+x(i)
enddo
xm=sx/n
C calculate variances and standard deviations
sdx=0
do i=1,n
sdx=sdx+(x(i)-xm)**2
enddo
vssd=sdx/(n-1)
vpsd=sdx/n
ssd=sqrt(vssd)
psd=sqrt(vpsd)
write(*,*) 'no of data points',n

write(*,*) 'data values',(x(i),i=1,n)


write(*,*) 'Mean',xm
write(*,*) 'sample variance',vssd
write(*,*) 'population variance',vpsd
write(*,*) 'sample standard deviation',ssd
write(*,*) 'population standard deviation',psd
end
OUTPUT:
C:\G77\work>p74-meanstd

Input no of data points

Input data

1.2

1.5

.8

1.3

1.4

no of data points 5

data values 1.20000005 1.5 0.800000012 1.29999995 1.39999998

Mean 1.24000001

sample variance 0.0729999915

population variance 0.0583999939


sample standard deviation 0.270185113

population standard deviation 0.241660908

SUBPROGRAMS AND SUBROUTINES


A subprogram is a separate program segment for doing a part job of the main job. The concept
of subprograms allows us to break a complex problem into subtasks so that we may develop
separate subprograms and later integrate them into a single program known as the main
program.
Subprograms are extensively used in numerical computation for tasks such as evaluation of
function, matrix multiplication, sorting, reading a table of values, printing a report etc.
There are two types of subprograms

1.FUNCTION SUBPROGRAM:
There are two types of function subprograms

a) Arithmetic statement function:


We have already used built-in library functions such as SQRT, SIN, COS, LOG etc. But if we want
to build our own function, not available as library function, then we can use the arithmetic
statement function. The statement function is a very simplified but restricted form of the
function subprogram. ​If it is possible to compress the calculation required into a single
statement, only then we may use a statement function​.
Such a function should be defined immediately before the first executable statement. Once
defined it can be used just like a library function. Since the statement function is specified
within a program segment, it may only be used within that segment, and cannot be referenced
from any other functions or subroutines discussed later.
Suppose we want to calculate F(A), F(B) and F(A)-F(B)+F(A*B) for given values of A and B where
F(x) = x.cos(x-3) + sin (x​2​). This can easily be done using arithmetic statement function as shown
in the following program. Here F is the function name. It is to be noted that the variable x used
to define F(x) is called a dummy variable since while calculating F(x) this is replaced by the
actual variable; for example while calculating F(A), x is replaced by A; x is replaced by A*B to
calculate F(AB); to calculate F(x), x is used as such. In the following program we use statement
function to solve the above problem.

● P76-function3.f:
C use of arithmetic statement function of one variable
REAL A,B,P,Q,R
F(X)=X*COS(X-3)+SIN(X*X) !function definition
WRITE(*,*)'ENTER VALUES OF A AND B'
READ(*,*) A,B
P=F(A) !calling f(x) to calculate f(a) ​call by function name
Q=F(B) !calling f(x) to calculate f(a)
R=P-Q+F(A*B) !calling f(x) to calculate f(a*b)
WRITE(*,*) 'VALUES OF A,B',A,B
WRITE(*,*) 'VALUES OF P,Q,R',P,Q,R
STOP
END
OUTPUT-1:
C:\G77\work>P76-function3

ENTER VALUES OF A AND B

1.5, 2.1

VALUES OF A,B 1.5 2.0999999

VALUES OF P,Q,R 0.884178996 0.350753069 3.17063046

OUTPUT-2:
C:\G77\work>P76-function3

ENTER VALUES OF A AND B


1.5 2.5

VALUES OF A,B 1.5 2.5

VALUES OF P,Q,R 0.884178996 2.16077709 2.46444893

Let us now consider a function of two variables.


Suppose we want to calculate the values of A,B,C and D given by
A=1/dist​3​ where dist is distance of the point (x1,y1) from origin
B=dist​2​/(4+dist) where dist is distance of the point (x2,y2) from origin
C= (cos(dist))​3​ where dist is distance of the point(A+1,B+2) from origin
D=exp(sin(dist)) where dist is distance of the point(x1+x2,y1+y2) from origin
See how we have used the arithmetic statement function and called it to get the required
results.

● P77-function4.f:
C use of arithmetic statement function
C function of two variables
DIST(X,Y)=SQRT(X*X+Y*Y) !definition of function DIST(x,y) which represents
write(*,*) 'input x1,y1 and x2,y2' !distance of the point(x,y) from origin
READ(*,*) x1,y1,x2,y2
A=1./DIST(x1,y1)**3 !calling DIST to calculate distance betn (0,0) & (x1,y1)
B=(DIST(x2,y2)**2)/(4.+DIST(x2,y2))
C=COS(DIST(A+1.,B+2.))**3
D=EXP(SIN(DIST(x1+x2,y1+y2)))
WRITE(*,*) 'VALUES OF x1,y1,x2,y2',x1,y1,x2,y2
WRITE(*,*) 'VALUES OF A,B,C,D',A,B,C,D
STOP
END
OUTPUT:
C:\G77\work>p77-function4
input x1,y1 and x2,y2

2345

VALUES OF x1,y1,x2,y2 2. 3. 4. 5.

VALUES OF A,B,C,D 0.0213346239 3.94112372 0.906155348 0.580409646

Modify above program and use format statement to print output in a nice manner

We show below another use of arithmetic statement function of two variables, where the
functions are:
f1(x,y)=x​2​ + y​2​ +2xy​2
f2(x,y)= x​2​ - y​2

● P78-function5.f:
C use of arithmetic statement function of two variables
f1(x,y)=x*x+y*y+2*x*y**2
f2(x,y)=x*x-y*y
write(*,*)'Input x,y'
read (*,*) x,y
pf1=f1(x,y+2) !to calculate f1 at the point x,y+2
pf2=f2(x+y,5) !to calculate f2 at the point x+y,5
pf3=f1(4.53,x-y) !to calculate f1 at the point 4.53,x-y
write(*,*)'x,y,pf1,pf2,pf3,(pf1+pf2)/pf3' !we want also a combination of
write(*,*)x,y,pf1,pf2,pf3,(pf1+pf2)/pf3 ! above function values
end
OUTPUT:
C:\G77\work>p78-function5

Input x,y

1.2 1.5

x,y,pf1,pf2,pf3,(pf1+pf2)/pf3

1.20000005 1.5 43.0900002 -17.7099991 21.426302 1.18452549


In the above two examples we have handled functions of one or two variables. Another
example is shown below to calculate a function of three variables. In case of more than one
variable cases, while calling the function, sequence of actual variables should be as that of the
dummy variables. For example, if we want that dummy variables of the defined function
F(X,Y,Z) should be replaced by actual variables C, A and B then it has to called as F(C,A,B).
In the following example, see how ​√​(A​2​+B​2​+C​2​), ​√​(7x+8y-8) and 4x/(​√​(x​2​+y​2​+z​2​))​3 have been
calculated calling the function SUMS(x,y,z) which calculates ​√​(x+y+z)
● P79-function6.f:
C use of arithmetic statement function to calculate functions of three variables
SUMS(X,Y,Z)=SQRT(X+Y+Z)
READ(*,*) A,B,C,X,Y,Z
AL=SUMS(A*A,B*B,C*C)
BT=SUMS(7.*X,8.*Y,-8.0)
GM=4.*X/SUMS(X*X,Y*Y,Z*Z)**3
WRITE(*,*) 'VALUES OF A,B,C,X,Y,Z',A,B,C,X,Y,Z
WRITE(*,*) 'VALUES OF AL,BT,GM',AL,BT,GM
STOP
END
OUTPUT:
987654

VALUES OF A,B,C,X,Y,Z 9. 8. 7. 6. 5. 4.

VALUES OF AL,BT,GM 13.9283886 8.60232544 0.0355201811


b) Function subprogram:
If we need more than one statement to define the required function we cannot use arithmetic
statement function, instead we use function subprogram. A function subprogram is an
independent program unit to compute and return a single value to the main program.
It has the following syntax:

where, FUNCTION is the key word with which the Function block begins
NAME is any name of the function, but name type decides the function value type
(integer, real or character) that is being returned to the main program
Arguments are the variables (and/or constants) necessary to define the function, their
types are decided by their names
Statements are the required statements for defining the function. There must be at
least one statement which assigns a value to the function name.
RETURN is the last key word which must be used
END is the last statement of the Function block

Function subprogram is called from the main program by the function name followed by
arguments in parentheses whose type, number and order must match with those of the
function arguments.
When the subprogram is called from the main program control is transferred to the statement
where the subprogram begins. When the Return key is encountered the control is transferred
back to the next line from where the subprogram was called.

Suppose we want calculate x​4​, y​4​, z​4 and (x+y)​4​. See how this can be done using function
subprogram. Here name of the function is FC which is real type and it is function of a real type
variable. Function FC is defined by only one line. In the main program it has been called four
time to calculate x​4​, y​4​, z​4​ and (x+y)​4​.

● P80-function7.f:
C function subprogram
C Main program
x=2
y=3
z=4
write(*,*) fc(x),fc(y),fc(z),fc(x+y)
end
C Function subprogram
function fc(x) ! name of the function is FC
fc=x**4 ! one line definition of the function FC
return
end
OUTPUT:
​ 16. 81. 256. 625.

But if we modify the function subprogram as follows:


function fc(x) ! name of the function is FC
fc=x**4 ! one line definition of function
write(*,*) FC
return
end
then, although the program compiles but following error message is given at the runtime:
I/O recursion: I/O started while already doing I/O
apparent state: unit 6 (unnamed)
last format: list io
lately writing direct formatted external IO
abnormal program termination.
This error message is given because in function subprogram only calculation of the value of the
function and returning that value to the main program is allowed, but no write statement is
allowed.
Now consider the following example:

F(x, y) = x​2​+2xy if x<y


=y​2​-2xy if x≥ y
This cannot be defined as a single arithmetic statement function. So we use function
subprogram to solve this problem. In the following program all the features of function
subprogram discussed above are used.
● P80-function8.f:
C TO DEMONSTRATE THE USE OF FUNCTION SUBPROGRAM
C Main Program
WRITE(*,*)'ENTER VALUES OF X AND Y'
READ(*,*) X,Y
WRITE(*,*)'ENTER VALUES OF A AND B'
READ(*,*) A,B
WRITE(*,*)'RESULTS OF F(X,Y) AND F(A,B)',F(X,Y),F(A,B)
C=F(X,Y)+F(A,B)
WRITE(*,*) 'SUM F(X,Y) AND F(A,B)',C
STOP
END

C Function subprogram
FUNCTION F(X,Y)
IF(X.LT.Y)THEN
F=X*X+2*X*Y
ELSE

F=Y*Y-2*X*Y
ENDIF
RETURN
END
OUTPUT:
ENTER VALUES OF X AND Y

23

ENTER VALUES OF A AND B

32

RESULTS OF F(X,Y) AND F(A,B) 16. -8.

SUM F(X,Y) AND F(A,B) 8.

In the above example, function subprogram is started with the key word Function and ended
with Return and end statements. Name of the function is simply F. Since name is real type
output will be real. Two real type dummy variables X and Y are used to define the function. We
need five statements to define the function. In the main program function is called twice by the
name F to calculate its value for the variables X and Y, and for A and B.
If the function name was given as MF, instead of F, first two results would have been in the
integer form although the arguments are real and the last result in real form, since C denotes
real variable.
By the function subprogram only one value is returned to the main program, in this case the
value of F. Even a statement like write(*,*) F is not allowed in function subprogram block as
discussed before.
One also has to remember that the variable names in the subprogram refer to different storage
locations (in other words, are different variables) than variables with same names in the main
program.
As a standard practice we have placed the main program first which is followed by the function
subprogram. But reverse order is also allowed.
One should also note that in the function subprogram defining the function in a single
statement as in arithmetic statement function is also allowed as done in the previous program.
We consider another example of the function subprogram to calculate the combinations of n
objects taken r at a time (​n​C​r​). We know n​​ C​r = n!/(r!*(n-r)!). In this case function name is given as
IFACT which is by default integer, so integer value will be returned by the function when called
from the main program. Its argument is also integer.
In the main program no default variable types are used (by use of Implicit none statement). All
variable used in the example are explicitly declared as integers. Note that this does not affect
the implicit variable types in the function subprogram.
In this example we have also used the ‘/’ feature of format statement to print output in
different lines.
● P81-combi.f:
C PROGRAM TO CALCULATE nCr
C USE OF FUNCTION SUBPROGRAM
C Main Program
​IMPLICIT NONE
INTEGER R,IFACT,N,I,NCR,nf,rf,nrf
write(*,*) 'Input values of n and r'
READ(*,*) N,R
​NF=IFACT(N);RF=IFACT(R);NRF=IFACT(N-R)
NCR=NF/(RF*NRF)
WRITE(*,10) N,R,NF,RF,NRF,NCR
10 FORMAT(1X,'n',I5,' r',I5/,'n!',I12,' r!',I12,' (n-r)!',I12/,

​1 'nCr',I10) ​ ! In fortran 90 by typing the character & at the end of the line
STOP ! it can be continued to the next line
END
FUNCTION ​IFACT​(N)
IFACT=1
DO I=2,N
IFACT=IFACT*I
END DO
RETURN
END
OUTPUT:
C:\G77\work>p81-combi

Input values of n and r

12 5

n 12 r 5

n! 479001600 r! 120 (n-r)! 5040

nCr 792

We write a program to calculate the Pearson Coefficient(r), often used in statistical calculations.
It is a measure of the linear ​correlation (dependence) between two variables ​X and ​Y​, giving a
value between +1 and −1 both inclusive, where 1 signify complete positive correlation, 0 no
correlation, and −1 complete negative correlation.
Coefficient r is given by the formula

∑(xi −x) (y i −y )
r​ =
√ 2
∑ (xi −x ) ∑ (y i −y )2

where x ​is the mean of n number x data points, y ​is mean of n number y data points. So, for
example, you could use this test to find out whether people's height and weight are correlated.
Positive correlation means with height, weight of persons increases. If correlation is negative, it
means weight does not increase with height. If the correlation coefficient is 0 or small positive
or small negative, there is no correlation meaning it is not possible to draw any conclusion,
weight varies with height randomly. All three types of results are shown below. Note that to
implement the objective we have used ​two function subprograms XM and SIG​.

● P83-pearson.f:
c PROGRAM TO CALCULATE PEARSON COEFFICIENT
C USE OF FUNCTION SUBPROGRAM
IMPLICIT NONE
INTEGER N,I
REAL X(10),Y(10),XM,YM,RA,A,B,C,PC,AM,SIG,SUM
READ(*,*) N
READ(*,*) (X(I),I=1,N)
READ(*,*) (Y(I),I=1,N)
XM=AM(X,N)
YM=AM(Y,N)
A=SIG(X,Y,XM,YM,N)
B=SIG(X,X,XM,XM,N)
C=SIG(Y,Y,YM,YM,N)
PC=A/SQRT(B*C)
WRITE(*,*)PC
STOP
END

FUNCTION AM(X,N) ​values of X and N supplied to the function subprogram

REAL X(10) !MUST ​it calculates and returns the value of AM


SUM=0
DO I=1,N
SUM=SUM+X(I)
END DO
AM=SUM/N
RETURN
END
FUNCTION SIG(X,Y,XM,YM,N)
REAL X(10),Y(10) !MUST
SUM=0
DO I=1,N
SUM=SUM+(X(I)-XM)*(Y(I)-YM)
END DO
SIG=SUM
RETURN
END
OUTPUT-1:
C:\G77\work>p83-pearson

Input no of data points

10

Input x data values

1 2 3 4 5 6 7 8 9 10

Input y data values

10 9 8 7 6 5 4 3 2 1

Pearson coefficient

-1.

OUTPUT-2:
Input no of data points

10

Input x data values

1 2 3 4 5 6 7 8 9 10

Input y data values

10 21 31 41 51 61 71 81 91 101

Pearson coefficient

0.99996078
OUTPUT-3:
Input no of data points

10

Input x data values

1 2 3 4 5 6 7 8 9 10

Input y data values

10 1 7 3 9 8 4 6 2 5

Pearson coefficient

-0.24848485

Note that we have used two function subprograms – AM(X,N) and SIG(X,Y,XM,YM,N). AM is
used to calculate the mean values and SIG is used to find the covariance. Notice how we
calculate the two types of variances just by calling the subprogram with different arguments.
Since variable in the subprogram refer to different variables than variables with same names in
the main program, we have declared X and Y variables in ​subprograms​ separately.

2. ​SUBROUTINE SUBPROGRAM:
A subroutine subprogram is also a separate subprogram which does a job required for
completing the main program. A subroutine subprogram, unlike a function subprogram which
always returns only one value, can ​return many values or no values at all (say, just prints the
values of some variables in the subprogram) to the main program.
where ​name ​is the subroutine name. In this case subroutine name has nothing to do with type
of the data. Instead of the Function key word here the key word is SUBROUTINE. Other things
are similar to the function subprogram. But to call a subroutine from the main program one has
to use a Call statement as follows:

When the subroutine is called from the main program control is transferred to the statement
where the subroutine begins. When the Return key is encountered the control is transferred
back to the next line from where the subroutine was called. A subroutine can be called as many
times as required. Calling a subroutine from within a subroutine is also allowed.

Writing a subroutine subprogram is explained with previous example of nCr calculation.

● P84-combi2.f
C PROGRAM TO CALCULATE nCr
C USE OF FUNCTION SUBROUTINE
WRITE(*,*)'ENTER n AND r'
READ(*,*)N,IR
CALL FACTORIAL(N,NF)
CALL FACTORIAL(IR,IFR)
CALL FACTORIAL(N-IR,IFNR)
NCR=NF/(IFR*IFNR)
WRITE(*,*)'n',N,' r',IR
WRITE(*,10)NF,IFR,IFNR,NCR
10 FORMAT(1X,'N!=',I10,/1X,'R!=',I10,/1X,'N-R!=',I10,/1X,'nCr=',I10)
STOP
END
SUBROUTINE FACTORIAL(N,FACT) ​value of N is supplied to the subroutine, it

INTEGER FACT calculates FACT and returns this value to main prog
FACT=1
DO I=1,N
FACT=FACT*I
ENDDO
RETURN
END
OUTPUT:
ENTER n AND r

10 4

n 10 r 4

N!= 3628800

R!= 24

N-R!= 720

nCr= 210

Next we consider the problem of ​sorting of numbers in ascending or descending order​. Altough
various methods are available, we have used a method called ​bubble sort which may not be
very efficient for very large data set but it is very easy to understand. First we store the data in
a one dimensional array. The numbers A(1), A(2), A(3) …….A(N) are said to be in ascending
order if A(I) ≤ A(J) for all I ≤ J. To sort in this order we proceed as follows:
Take A(1) and A(2). IF A(1) ≤ A(2) we do not make any change. But if A(1) > A(2) then we
interchange the numbers so that smaller data comes in A(1) position. Next consider A(1) and
A(3), check as before and interchange if necessary. Continue the process till the end. After one
such pass, smallest data will be at A(1). Next repeat the process starting with A(2) and
considering A(3), A(4), ….till the end of data. This will bring the second lowest data at location
A(2). We repeat the process starting with A(3), A(4),……….A(n-1) and considering A(4), A(5),
……..A(n) etc. till all the numbers are sorted in descending order. This job can be performed by
two do loops – I loop for I =1 to N-1, J loops from I+1 to N. Interchanging is done by the
following logic.
1. Store A(I) in temporary location T Fortran code: T=A(I)
2. Store A(J) in A(I) A(I)=A(J)
3. Store T in A(J) A(J)=T
Now we can write the complete code as an independent program. But we can also write the
code as a subroutine subprogram, call the subroutine for sorting different sets of data stored in
different arrays. Complete code of the program is given below in which we consider sorting of
two data sets.
● P85-sort1.f:
C sorting data in ascending and descending order
C BUBBLE SORT METHOD
C TWO DATA SETS ARE SORTED
DIMENSION A(100)
WRITE(*,*) 'Input data number in data set 1'
READ(*,*) N
WRITE(*,*) 'Input data of data set 1'
READ(*,*) (A(I),I=1,N)
CALL SORTDATA(N,A)
WRITE(*,*) 'Sorted data set 1 (ascending order)'
WRITE(*,*) (A(I),I=1,N)
WRITE(*,*) 'Sorted data set 1 (descending order)'
WRITE(*,*) (A(I),I=N,1,-1)
WRITE(*,*) 'Input data number in data set 2'
READ(*,*) N
WRITE(*,*) 'Input data of data set 2'
READ(*,*) (A(I),I=1,N)
CALL SORTDATA(N,A)
WRITE(*,*) 'Sorted data set 2 (ascending order)'
WRITE(*,*) (A(I),I=1,N)
WRITE(*,*) 'Sorted data set 2 (descending order)'
WRITE(*,*) (A(I),I=N,1,-1)
stop
end
SUBROUTINE SORTDATA(N,A)
DIMENSION A(100)
DO 10 I=1,N-1
DO 10 J=i+1,N
IF (A(I).GT.A(J)) THEN
T=A(I)
A(I)=A(J)
A(J)=T
ENDIF
10 CONTINUE
RETURN
END
OUTPUT:
Input data number in data set 1

Input data of data set 1

11 43 9 23 74

Sorted data set 1 (ascending order)

9. 11. 23. 43. 74.

Sorted data set 1 (descending order)

74. 43. 23. 11. 9.

Input data number in data set 2

Input data of data set 2

11.2 23.5 45 11.6 45.3 67 67.8 23.9

Sorted data set 2 (ascending order)

11.1999998 11.6000004 23.5 23.8999996 45. 45.2999992 67. 67.8000031


Sorted data set 2 (descending order)

67.8000031 67. 45.2999992 45. 23.8999996 23.5 11.6000004 11.1999998

It may be noted that we have ​printed the data in descending order using data sorted in
ascending order just by printing in reverse order​.
The program can also handle negative data as well as two or more data of same value. See the
following output.

OUTPUT:
C:\G77\work>p85-sort1

Input data number in data set 1

Input data of data set 1

1 3 56 5 7

Sorted data set 1 (ascending order)

1. 3. 5. 7. 56.

Sorted data set 1 (descending order)

56. 7. 5. 3. 1.

Input data number in data set 2

Input data of data set 2

-3 5 12 1 6 78 12

Sorted data set 2 (ascending order)

-3. 1. 5. 6. 12. 12. 78.

Sorted data set 2 (descending order)

78. 12. 12. 6. 5. 1. -3.

It is interesting to note that the same program may be used also to sort character data (for
example, names). Since in this case we have to handle string data instead of numeric data, we
need to change real array A(100) and temporary location real variable T to character array
A(100) and character string T by changing type declaration. We need to specify the maximum
width of our string data, which is taken as 40. While reading string data we use character format
statement so that data can be supplied as such. If we don’t do this we have to supply data
within quotes.
Just as numeric data are actually stored as binary numbers in computers, string data are also
stored as binary numbers following ASCII (American Standard Code for Information Interchange)
code. Characters A, B, C…… etc have ASCII codes 65, 66, 67 ……etc in decimal number system
while characters a,b, c…… etc have ASCII codes 97, 98, 99, ……etc. All numeric digits – when
used as character data – like 0,1 2,….. etc. also have ASCII codes 48, 49, 50,……etc. Therefore
sorting of string can be made by the same logic. Program listing is given below.

● P86-sort2.f:
C sorting string in alphabetical order
C BUBBLE SORT METHOD
C TWO DATA SETS ARE SORTED
CHARACTER *40 A(100),T
WRITE(*,*) 'Input data number in data set 1'
READ(*,*) N
WRITE(*,*) 'Input data of data set 1'
READ(*,11) (A(I),I=1,N)
11 FORMAT(A40)
CALL SORTDATA(N,A)
WRITE(*,*) 'Sorted data set 1 (alphabetical order)'
WRITE(*,*) (A(I),I=1,N)
WRITE(*,*) 'Input data number in data set 2'
READ(*,*) N
WRITE(*,*) 'Input data of data set 2'
READ(*,11) (A(I),I=1,N)
CALL SORTDATA(N,A)
WRITE(*,*) 'Sorted data set 2 (alphabetical order)'
WRITE(*,*) (A(I),I=1,N)
stop
end
SUBROUTINE SORTDATA(N,A)
CHARACTER *40 A(100),T
DO 10 I=1,N-1
DO 10 J=i+1,N
IF (A(I).GT.A(J)) THEN
T=A(I)
A(I)=A(J)
A(J)=T
ENDIF
10 CONTINUE
RETURN
END

OUTPUT:
Input data number in data set 1

Input data of data set 1

PRABAL

PRITAM

TRISHYA

TRINA

TANUJA

Sorted data set 1 (alphabetical order)

PRABAL

PRITAM

TANUJA

TRINA

TRISHYA

Input data number in data set 2

10

Input data of data set 2


RAM

SHYAM

JADU

MADHU

LAKSHMAN

SITA

PRABAL

PRITAM

TANUJA

TRISHYA

Sorted data set 2 (alphabetical order)

JADU

LAKSHMAN

MADHU

PRABAL

PRITAM

RAM

SHYAM

SITA

TANUJA

TRISHYA

Remember that since space or comma can also be part of a string data, in this case all data are
entered in separate lines. It can also handle names with name and title.
As the last example of Subroutine Subprogram we develop a program to do the following job:
1. Read four matrices A, B, AA, BB; all are square matrices of size nxn
2. Find the product matrices C=AxB and CC=AAxBB
3. Print all the matrices
Notice that we have used three subroutines – MATREAD to read the four matrices, MATWRITE
to write the matrices and MATPROD to find product of two matrices.

● P87-matmult2.f:
C MATRIX MULTIPLICATIONS USING SUBROUTINE
DIMENSION A(5,5),B(5,5),C(5,5),AA(5,5),BB(5,5),CC(5,5)
WRITE(*,*) 'Input order of the square matrices n ( max n =5)'
READ(*,*) N
WRITE(*,*) 'Input matrix A row wise'
CALL MATREAD(A,N)
WRITE(*,*) 'Input matrix B row wise'
CALL MATREAD(B,N)
WRITE(*,*) 'Input matrix AA row wise'
CALL MATREAD(AA,N)
WRITE(*,*) 'Input matrix BB row wise'
CALL MATREAD(BB,N)
WRITE(*,*)
WRITE(*,*) 'Matrix A '
CALL MATWRITE(A,N)
WRITE(*,*)
WRITE(*,*) 'Matrix B '
CALL MATWRITE(B,N)
CALL MATPROD(A,B,C,N)
WRITE(*,*) 'Matrix C=AxB '
CALL MATWRITE(C,N)
WRITE(*,*)
WRITE(*,*) 'Matrix AA '
CALL MATWRITE(AA,N)
WRITE(*,*)
WRITE(*,*) 'Matrix BB '
CALL MATWRITE(BB,N)
CALL MATPROD(AA,BB,CC,N)
WRITE(*,*) 'Matrix CC=AAxBB '
CALL MATWRITE(CC,N)
STOP
END
SUBROUTINE MATREAD(A,N)
DIMENSION A(5,5)
READ(*,*) ((A(I,J),J=1,N),I=1,N)
RETURN
END
SUBROUTINE MATWRITE(A,N)
DIMENSION A(5,5)
DO 10 I=1,N
10 WRITE(*,*) (A(I,J),J=1,N)
RETURN
END
SUBROUTINE MATPROD(A,B,C,N)
DIMENSION A(5,5),B(5,5),C(5,5)
DO 20 I=1,N
DO 20 J=1,N
C(I,J)=0
DO 20 K=1,N
20 C(I,J)=C(I,J)+A(I,K)*B(K,J)
RETURN
END
OUTPUT:
Input order of the square matrices n ( max n =5)

3
Input matrix A row wise

123

456

789

Input matrix B row wise

987

654

321

Input matrix AA row wise

11 12 13

14 15 16

17 18 19

Input matrix BB row wise

19 18 17

16 15 14

13 12 11

Matrix A

1. 2. 3.

4. 5. 6.

7. 8. 9.

Matrix B

9. 8. 7.

6. 5. 4.

3. 2. 1.

Matrix C=AxB

30. 24. 18.

84. 69. 54.

138. 114. 90.


Matrix AA

11. 12. 13.

14. 15. 16.

17. 18. 19.

Matrix BB

19. 18. 17.

16. 15. 14.

13. 12. 11.

Matrix CC=AAxBB

570. 534. 498.

714. 669. 624.

858. 804. 750.

DATA FILE HANDLING:


So far we have supplied data to a program by three methods – assignment statement, read
statement and data statement. But when we need to handle large number of data, it is better to
read and write data from and to a data file. One Input data file, from where data are read by a
program, may be used repeatedly or by different programs. Moreover, output data file (where
the calculated data are written) from one program can be used as input data file of another
program.
Data files are different from program files and execution files. test.f test.exe
Data file handling involves following steps.
A. OPEN A FILE:
The OPEN statement is used to create a new file and store data in it, or open an old file and
retrieve data from the file.

where,
n is the file number (integer)
NAME is the file name
s=’OLD’ if the file is an old file
s=’NEW’ if the file is created newly
NOTE: Writing STATUS is optional. If the named file exists in the working directory, it will be
opened to read/write data from/to it. If the named file does not exist in the working directory a
new blank file will be opened to write data to the file.
EXAMPLE-1:
OPEN (1, FILE=’RESULT.DAT’, STATUS=’NEW’)
This creates a new file with the file name RESULT.DAT with file number 1.
EXAMPLE-2:
OPEN (2, FILE=’MARKS.DAT’, STATUS=’OLD’)
The file with name MARKS.DAT already exists in the memory. It is opened with number 2.
OPEN (1, FILE=’RESULT.DAT’) and OPEN (2, FILE=’MARKS.DAT’) will do the same job. In fact we
will use these forms in our programmes.
B.READ DATA FROM A FILE:
Once an old (existing) file is opened we can read data from that file using READ statement.

where n is the file number, m is the format statement number and s is the statement number to
which the control is to be transferred when all the data are read. Value of n must be same with
which it was opened.
Here END=s is optional. In all programs we don’t need this.
C.WRITE DATA TO A FILE:
Once a file has been opened, we can write data to the file using WRITE statement.

where n is the file number and m is the format statement number and A, B are variables whose
values are to be written to data file. Here the value of n must be same with which the file was
opened.
D.CLOSING A FILE:
After opening a file and processing it, the file should be closed. The CLOSE or ENDFILE
statement is used to close a file.

or

where n is the file number with which the file was opened.
When execution of the program is terminated, operating system automatically closes all opened
files. So CLOSE or ENDFILE statement is optional.
Let us first see how we can create a data file named marks.dat wherein roll number, name and
marks of some students are to be written. Note that we have not used the Close statement.
Program listing is shown below:

● P89-file1.f:
C CREATE A NEW DATA FILE
C ROLL NUMBER, NAME AND MARKS OF SOME STUDENTS ARE WRITTEN
C CREATED DATA FILE NAME marks.dat
character *40 name
integer rn, mark
open(1,file='marks.dat') !status option not chosen, a new blank file will be created
write(*,*) 'Input no. of students'
Read(*,*) ns
do i=1,ns
write(*,*)'Enter rollno,name,mark of a student one after another'
read(*,*) rn
read (*,14) name
read(*,*) mark
write(1,15) rn,name,mark !writes three data to the file write(*,*)
14 format(A40)
15 format(I3,3x,A40,I5)
enddo
end
OUTPUT:
C:\G77\work>p89-file1

Input no. of students

Enter rollno,name,mark of a student one after another

aditya birla

65

Enter rollno,name,mark of a student one after another

pradipto bagchi

49

Enter rollno,name,mark of a student one after another

sukhen haldar

56
Enter rollno,name,mark of a student one after another

keya seth

77

Enter rollno,name,mark of a student one after another

vijay baul

72

RESULT:

Output is written in file marks.dat. One can see the content of the created data file marks.dat by
opening it using a text editor (say, notepad) or simply issuing the type command from command
prompt window as shown below.
C:\G77\work>type marks.dat

1 aditya birla 65

2 pradipto bagchi 49

3 sukhen haldar 56

4 keya seth 77

5 vijay baul 72

Issuing the following command will also show the content of the file in a different window.
C:\G77\work>notepad marks.dat
Before going for other file operations ​let us see how some more data can be added to the
created file marks.dat. In this case the file has to be opened in append mode as shown in the
following program listing, other things remain same.
● P90-file2.f:
C APPEND DATA TO AN EXISTING DATA FILE
C ROLL NUMBER, NAME AND MARKS OF SOME STUDENTS ARE WRITTEN
C EXISTING DATA FILE NAME marks.dat
character *40 name

integer rn, mark


​open(1,file='marks.dat',access='append')
write(*,*) 'Input no. of students'
Read(*,*) ns
do i=1,ns
write(*,*)'Enter rollno,name,mark of a student one after another'
read(*,*) rn
read (*,14) name
read(*,*) mark
write(1,15) rn,name,mark
14 format(A40)

15 format(I3,3x,A40,I5)
enddo
end
OUTPUT:
C:\G77\work>p90-file2

Input no. of students

Enter rollno,name,mark of a student one after another

6
papia nandi

82

Enter rollno,name,mark of a student one after another

bimal mazumdar

50

Enter rollno,name,mark of a student one after another

satya banerjee

61

Enter rollno,name,mark of a student one after another

dinesh bajpai

76

Enter rollno,name,mark of a student one after another

10

kamal saha

77

Present content of the file marks.dat is as follows:


C:\G77\work>notepad marks.dat

1 aditya birla 65

2 pradipto bagchi 49

3 sukhen haldar 56

4 keya seth 77

5 vijay baul 72

6 papia nandi 82

7 bimal mazumdar 50

8 satya banerjee 61

9 dinesh bajpai 76

10 kamal saha 77
So records of five more students have been added to the data file
Let us now see how we can read data from the existing data file marks.dat and print on the
monitor. Suppose we want to read ​only first five records out of 10 records​, each record
contains roll number, name and mark of a student. We also assume that we know in which
format the data were written in the file (15 format(I3,3x,A40,I5). END=20, in the 6​th line,
transfers control to statement 20 when all the data are read (irrespective of whether we are
reading less number of records than the existing records, or reading all records or trying to read
more records using - do i=1,5 OR do i=1,10 OR do i=1,15 statement (see 5​th line of the
program).
● P91-file3:
C Read data from a file and print
character *40 name
integer rn, mark
open(1,file='marks.dat')
do i=1,5
read(1,15,END=20) rn,name,mark
write(*,15) rn,name,mark
15 format(I3,3x,A40,I5)

enddo
20 write(*,*) 'END OF DATA'
End
OUTPUT:
C:\G77\work>p91-file3

1 aditya birla 65

2 pradipto bagchi 49

3 sukhen haldar 56

4 keya seth 77

5 vijay baul 72

END OF DATA
We must also note that these ​data files are called sequential file, we can read data from the file
only sequentially​. Suppose we need data of only the fourth record, even then we have to read
all the first four records and utilize data of the fourth record. To utilize data of the last record
we have to read data of all the records! ​Secondly, these data files are ASCII files​. ​These are
completely different from the program files and the execution files, contain only data.
To show utility of data files, we consider the following example. ​Suppose we want to prepare a
rank list from the students score stored in the data file marks.dat and store it in another data
file.​ To do the job we proceed as follows:
1. Read data from file marks.dat
2. Display those data in monitor to see if the data have been read correctly.
3. Sort data in descending order of marks using logic described before. Remember if
interchange of i-th and j-th mark data is necessary, all other records (roll number and
name) should also be interchanged.
4. Write the sorted data in another file, as well as display in monitor.
In addition, we want to read the name of input and output data files while running the program
unlike in previous cases where data file names were given in the program itself. ​This will give us
the opportunity of choosing a particular file from more than one existing files and choosing
different output file names in different runs of the program.
List of the required program is given below:
● P92-file4:
C Prepare rank list from score data file of students
C Read data from a file and write data to another file
character *40 name(20),tname,inpf,outf
integer rn(20), mark(20),trn,tmark
write(*,*) 'Input file name?'
read(*,14) inpf
write(*,*) 'Output file name?'
read(*,14) outf
14 format(A30)
write(*,*) 'No of data in input file?'
read(*,*) n
​open(3,file=inpf)
open(4,file=outf)
do i=1,n
read(3,15,END=20) rn(i),name(i),mark(i)
write(*,15) rn(i),name(i),mark(i)
15 format(I3,3x,A40,I5)
enddo
20 write(*,*) 'End of input data'
do i=1,n-1
do j=i+1,n
if (mark(i).lt.mark(j)) then
trn=rn(i) !to interchange roll no
rn(i)=rn(j)
rn(j)=trn
tname=name(i) !to interchange name
name(i)=name(j)
name(j)=tname
tmark=mark(i) !to interchange mark
mark(i)=mark(j)
mark(j)=tmark
endif
enddo
enddo
write(*,*)
write(*,*) 'Rank list'
write(*,*) ' Rank Roll NO. Name Marks'
write(4,*) 'Rank list'
write(4,*) ' Rank Roll NO. Name Marks'
do i=1,n
write(*,16) i,rn(i),name(i),mark(i)
write(4,16) i,rn(i),name(i),mark(i)
enddo
16 format(I3,2x,I3,10x,A27,I5)
close(3)
close(4)
c endfile 3
c endfile 4
end
OUTPUT:
C:\G77\work>p92-file4

Input file name?

marks.dat

Output file name?

rank.dat

No of data in input file?

10

1 aditya birla 65

2 pradipto bagchi 49
3 sukhen haldar 56

4 keya seth 77

5 vijay baul 72

6 papia nandi 82

7 bimal mazumdar 50

8 satya banerjee 61

9 dinesh bajpai 76

10 kamal saha 77

End of input data

Rank list

Rank Roll NO. Name Marks

1 6 papia nandi 82

2 4 keya seth 77

3 10 kamal saha 77

4 9 dinesh bajpai 76

5 5 vijay baul 72

6 1 aditya birla 65

7 8 satya banerjee 61

8 3 sukhen haldar 56

9 7 bimal mazumdar 50

10 2 pradipto bagchi 49

As before we can look into the content of the new data file rank.dat as follows and check
whether the rank list is prepared correctly.
C:\G77\work>type rank.dat

Rank list

Rank Roll NO. Name Marks

1 6 papia nandi 82

2 4 keya seth 77

3 10 kamal saha 77
4 9 dinesh bajpai 76

5 5 vijay baul 72

6 1 aditya birla 65

7 8 satya banerjee 61

8 3 sukhen haldar 56

9 7 bimal mazumdar 50

10 2 pradipto bagchi 49

Now suppose we want to prepare two lists from the marks.dat file – one rank file and one
alphabetical list file.
● P93-file5.f:
C Prepare rank and alphabetical list from score data file of students
C Read data from a file and write sorted data to two files
character *40 name(20),tname,inpf,outf1,outf2,jnk
integer rn(20),rank(20),mark(20),trn,tmark,trank
write(*,*) 'Input file name?'
read(*,14) inpf
write(*,*) 'Output rank file name?'
read(*,14) outf1
write(*,*) 'Output alphabetical file name?'
read(*,14) outf2
14 format(A30)
write(*,*) 'No of data in input file?'
read(*,*) n
​open(3,file=inpf)
open(4,file=outf1)
open(7,file=outf2)
do i=1,n
read(3,15,END=20) rn(i),name(i),mark(i)
write(*,15) rn(i),name(i),mark(i)
15 format(I3,3x,A40,I5)
enddo
20 write(*,*) 'End of input data'
C prepare rank file
do i=1,n-1
do j=i+1,n
if (mark(i).lt.mark(j)) then
trn=rn(i)
rn(i)=rn(j)
rn(j)=trn
tname=name(i)
name(i)=name(j)
name(j)=tname
tmark=mark(i)
mark(i)=mark(j)
mark(j)=tmark
endif
enddo
enddo
write(*,*)
write(*,*) 'Rank list'
write(*,*) ' Rank Roll NO. Name Marks'
write(4,*) 'Rank list'
write(4,*) ' Rank Roll NO. Name Marks'
do i=1,n
rank(i)=i
write(*,16) i,rn(i),name(i),mark(i)
write(4,16) i,rn(i),name(i),mark(i)
enddo
C prepare alphabetical list
do i=1,n-1
do j=i+1,n
if (name(i).gt.name(j)) then
trank=rank(i)
rank(i)=rank(j)
rank(j)=trank
trn=rn(i)
rn(i)=rn(j)
rn(j)=trn
tname=name(i)
name(i)=name(j)
name(j)=tname
tmark=mark(i)
mark(i)=mark(j)
mark(j)=tmark
endif
enddo
enddo
write(*,*)
write(*,*) 'Alphabetical list'
write(*,*) ' Rank Roll NO. Name Marks'
write(7,*) 'Alphabetical list'
write(7,*) ' Rank Roll NO. Name Marks'
do i=1,n
write(*,16) rank(i),rn(i),name(i),mark(i)
write(7,16) rank(i),rn(i),name(i),mark(i)
enddo
16 format(I3,2x,I3,10x,A27,I5)
close(3)
close(4)
close(7)
c endfile 3
c endfile 4
end
OUTPUT:
C:\G77\work>p93-file5

Input file name?

marks.dat

Output rank file name?

rankout.dat

Output alphabetical file name?

alphout.dat

No of data in input file?

10

1 aditya birla 76

2 pradipto bagchi 49

3 sukhen haldar 56

4 keya seth 77

5 vijay baul 72

6 papia nandi 82

7 bimal mazumdar 50
8 satya banerjee 61

9 dinesh bajpai 76

10 kamal saha 77

End of input data

Rank list

Rank Roll NO. Name Marks

1 6 papia nandi 82

2 4 keya seth 77

3 10 kamal saha 77

4 9 dinesh bajpai 76

5 1 aditya birla 76

6 5 vijay baul 72

7 8 satya banerjee 61

8 3 sukhen haldar 56

9 7 bimal mazumdar 50

10 2 pradipto bagchi 49

Alphabetical list

Rank Roll NO. Name Marks

5 1 aditya birla 76

9 7 bimal mazumdar 50

4 9 dinesh bajpai 76

3 10 kamal saha 77

2 4 keya seth 77

1 6 papia nandi 82

10 2 pradipto bagchi 49

7 8 satya banerjee 61

8 3 sukhen haldar 56

6 5 vijay baul 72
Since alphabetical list is prepared from the rank list, it will display their correct ranks.
We consider another example of data file creation. Suppose we first want to create a file
‘coord.dat’ containing name of a few atoms and their positional coordinates x,y,z. Next we
want to transform the coordinate as follows:

​xt(i)=x(i)-y(i)
yt(i)=y(i)-z(i)
zt(i)=x(i)+y(i)
and finally write these transformed coordinates along with their identities in a new file
‘tcoord.dat’. To keep data entry work less, we have considered data of only three atoms. Here
is the program listing for this:
● P94-file6.f:
C create an atomic coordinate file
C modify atomic coordinates and write in a new file
dimension atm(5),x(5),y(5),z(5), xt(5),yt(5),zt(5)
character *10 atm
open(2,file='coord.dat')
write(*,*) 'input atm name,x,y,z'
do 10 i=1,3
read(*,*) atm(i),x(i),y(i),z(i)
write(*,*) atm(i),x(i),y(i),z(i)
10 write(2,15) atm(i),x(i),y(i),z(i)
15 format(a10,3f7.2)
close (2)
open(2,file='coord.dat')
open(3,file='tcoord.dat')
do 20 i=1,3
20 read(2,*) atm(i),x(i),y(i),z(i)
do 30 i=1,3
xt(i)=x(i)-y(i)
yt(i)=y(I)-z(i)
30 zt(i)=x(i)+y(I)
do 40 i=1,3
40 write(3,15) atm(i),xt(i),yt(i),zt(i)
end
OUTPUT:
C:\G77\work>p94-file6

input atm name,x,y,z

C1,1.23,3.45,5.67

C1 1.23000002 3.45000005 5.67000008

N1 -2.56 -6.78 3.89

N1 -2.55999994 -6.78000021 3.8900001

H1,1.67 -3.72,6.21

H1 1.66999996 -3.72000003 6.21000004

Note that we have supplied data separated by comma or space.


Output file coord.dat:
C1 1.23 3.45 5.67

N1 2.34 3.45 4.56

O1 3.45 4.56 5.67

Output file tcoord.dat:


C1 -2.22 -2.22 4.68

N1 -1.11 -1.11 5.79

O1 -1.11 -1.11 8.01

Let us now explore how to merge two existing data files. In the following example, the two files
– coord.dat and tcoord.dat – which were created by the previous program have been merged
to the new file ‘fincoord.dat’.
● P95-file7.f:
C file operation merge two data files
dimension atm(5),x(5),y(5),z(5)
character *10 atm
open(12,file='coord.dat')
open(13,file='tcoord.dat')
open(14,file='fincoord.dat')
do i=1,3
read(12,*) atm(i),x(i),y(i),z(i)
write(*,*) atm(i),x(i),y(i),z(i)
write(14,15) atm(i),x(i),y(i),z(i)
enddo
15 format(a10,3f7.2)
do i=1,3
read(13,*) atm(i),x(i),y(i),z(i)
write(*,*) atm(i),x(i),y(i),z(i)
write(14,15) atm(i),x(i),y(i),z(i)
enddo
end
OUTPUT:
Content of fincoord.dat

C1 1.23 3.45 5.67

N1 2.34 3.45 4.56

O1 3.45 4.56 5.67

C1 -2.22 -2.22 4.68

N1 -1.11 -1.11 5.79

O1 -1.11 -1.11 8.01


COMPLEX NUMBERS:

A complex number a + ib is represented in ​FORTRAN as (a,b) where a and b are real constants.
For example, complex numbers 4 + 5i and 0.7 – 3.5i are represented as (4,5) and (0.7,-3.5).
Enclosing the real and imaginary parts in the parenthesis is must.
We need a specific declaration statement for handling this type of number. To declare a
variable as complex, the declaration statement COMPLEX is used.

Symbols for arithmetic operations on complex numbers are same. However, for some
compilers, library functions for complex numbers are different from those for real numbers.
Selected library functions, for those compilers, to process complex numbers are tabulated
below:

FUNCTION* MEANING

REAL (X) Real part of the complex number X

AIMAG(X) Imaginary part of the complex number X

CABS(X) Absolute value of the complex number X


CONJG(X) Complex conjugate of X

CLOG(X) Logarithm of the complex number X

CSQRT(X) Square root of the complex X

CEXP(X) e​x
CSIN(X) Sin (X)

CCOS(X) Cos (X)

CMPLX(X,Y)Where X and Y are real It refers to the complex number “ X + iY”

* For most compilers library functions are same for both real and complex variables
In the following program we have shown how to assign a value to a complex variable, how to
read a complex variable in free format as well as in pre-defined format, how to perform
different complex operations and output their values in free format and in formatted manner.

● P96-complex1.f:
C complex number operations
complex a,B,C,D,AA,BB,CC,P,Q,PP,QQ,CD,AC,AL,AS,AE,BS,BC,DL
REAL X,XX
a=(3,1)
b=(2,.2)
c=a+b
d=a-b
aa=a*b
bb=A/B
CC=a**3+B**2
WRITE(*,*) 'Given complex numbers A,B',A,B
WRITE(*,*) 'C,D,AA,BB,CC',C,D,AA,BB,CC
write(*,*)'Input a complex number in free format'
read(*,*)p
write(*,*)'Input a complex number in f5.2 format'
read(*,10)q
10 format(2f5.2)
pp=p+q
qq=p-q
write(*,*)'P,Q,PP, QQ',P,Q,PP,QQ
X=REAL(P) !REAL PART OF P
XX=AIMAG(Q) !IMAGINARY PART OF Q
CD=CMPLX(X,XX) !COMPLEX NUMBER WITH RP AS X AND IP AS XX
XAB=CABS(P) !MODULUS OF P
AC=CONJG(P) !COMPLEX CONJUGATE OF P
AL=CLOG(P) !NATURAL LOGARITHM OF P
AS=CSQRT(P) !SQUARE ROOT OF P
AE=CEXP(P) !EXPONENTIAL OF P
BS=CSIN(P) !SIN OF P
BC=CCOS(P) !COS OF P
WRITE(*,*) 'X,XX,CD,XAB,AC'
WRITE(*,*) X,XX,CD,XAB,AC
WRITE(*,*) 'X,XX,CD,XAB,AC'
WRITE(*,12) X,XX,CD,XAB,AC
WRITE(*,*) 'AL,AS,AE,BS,BC'
WRITE(*,*) AL,AS,AE,BS,BC
WRITE(*,*) 'AL,AS,AE,BS,BC'
WRITE(*,12) AL,AS,AE,BS,BC
12 FORMAT(10F7.3)
END
OUTPUT:
C:\G77\work>p96-complex1

Given complex numbers A,B (3.,1.) (2.,0.200000003) ( 3,1) (2,.2)

C,D,AA,BB,CC (5.,1.20000005) (1.,0.800000012) (5.80000019,2.5999999)

(1.53465343,0.34653464) (21.9599991,26.7999992)

Input a complex number in free format

(3,1)

Input a complex number in f5.2 format

2.12 4.57

P,Q,PP,QQ (3.,1.) (2.11999989,4.57000017) (5.11999989,5.57000017)

(0.880000114,-3.57000017)
X,XX,CD,XAB,AC

3. 4.57000017 (3.,4.57000017) 3.1622777 (3.,-1.)

X,XX,CD,XAB,AC

3.000 4.570 3.000 4.570 3.162 3.000 -1.000

AL,AS,AE,BS,BC

(1.15129256,0.321750551) (1.75531733,0.284848779) (10.8522615,16.9013958)

(0.21775955,-1.16344035) (-1.5276382,-0.165844396)

AL,AS,AE,BS,BC

1.151 0.322 1.755 0.285 10.852 16.901 0.218 -1.163 -1.528 -0.166

Numerical methods:
EVALUATION OF DEFINITE INTEGRALS

b
∫ f (x) dx
a

Simpson’s rule, Weddles rule and trapezoidal rule.


In all these methods integration is evaluated by finding the area under the function curve
between the two limiting ordinates and the x-axis. To increase the accuracy, the given interval
is subdivided into smaller intervals and some weight is attached to the function values at those
points.
Thus formula used in Simpson’s rule is
I=h/3[f(a)+4{f(x​1​)+f(x​3​)+f(x​5​)+….} +2{f(x​2​)+f(x​4​)+f(x​6​)+….}+f(b)]
where, a and b are the lower and upper limits of integration.
The step size h is given by
h=(b-a)/n
n being no of intervals taken between the limits which must be even. Successive x values are
generated by the expression:
x​n​=a + nh
Program listing is given below.
● P122-simp.f:
C integration by simpson's rule
f(x)=1+exp(-x)*sin(4*x)
c f(x)=exp(-x*x)
c f(x)=2+sin(2*sqrt(x))
write(*,*) 'Input a,b,no of division'
read*,a,b,n
h=(b-a)/n
s1=0
s2=0
C write(*,*) f(a),f(b)
do 10 i=1,(n-1),2
x=a+h*i
C write(*,*) x,f(x)
10 s1=s1+f(x)
do 20 i=2,(n-2),2
x=a+h*i
C write(*,*) x,f(x)
20 s2=s2+f(x)
s=h*(f(a)+f(b)+4*s1+2*s2)/3
write(*,*) "Value of integral ",s
C write(*,*) 2/sqrt(3.14)*s
end
OUTPUT-1:
For f(x)=1+exp(-x)*sin(4*x)

Input a,b,no of division

0 1 16

Value of integral 1.30825496


OUTPUT-2:
Input a,b,no of division

0 1 32

Value of integral 1.30825078

OUTPUT-3:
Input a,b,no of division

0 1 64

Value of integral 1.30825067

OUTPUT-4:
Input a,b,no of division

0 1 100

Value of integral 1.30825067

Notice that increasing subdivision indefinitely does not increase the accuracy.
To get the integral value of other integrands you have to change only the f(x) statement and
recompile the program.

OUTPUT-5:
for f(x)=sin(x)-log(x)+exp(x)

Input a,b,no of division

.2 1.4 12

Value of integral 4.05105734

OUTPUT-6:
Input a,b,no of division

.2 1.4 20

Value of integral 4.05096388

OUTPUT-7:
Input a,b,no of division
.2 1.4 100

Value of integral 4.05094814

OUTPUT-8:
Input a,b,no of division

.2 1.4 150

Value of integral 4.05094719

OUTPUT-8:
Input a,b,no of division

.2 1.4 200

Value of integral 4.05094767

OUTPUT-9:
Input a,b,no of division

.2 1.4 180

Value of integral 4.05094814

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy