Fortran Programming
Fortran Programming
Fortran Programming
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
● 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 (^)
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
write a program using base height formula, (a) given base and height
(b) given a, b, c
…………………………………………………………………………………………………………………………..
LIBRARY FUNCTIONS:
Function Description
Trigonometric Functions
ASIN(X) sin-1x
ACOS(X) cos-1x
ATAN(X) tan-1x
answer is in radian
Hyperbolic Functions
…………………………………………………………………………………………………………………………..
We want to find sine, cosine and tangent values for theta equal to 0, 30, 45 and 60 degrees.
P14-trig1.f
OUTPUT:
P15-root1.f
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:\G77\work>P16-mod
24. 12.
36
-10
DATA STATEMENT:
1. By assignment statement
2. By READ statement
………………………………………………………………………………………………………………………………………………..
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.
…………………………………………………………………………………………………………………………..
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(*,*) ????
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
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)
end
OUTPUT:
C:\G77\work>p18-time
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.
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)
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
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
GIVEN VALUE IS = 3
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
−𝑏 ± √𝑏 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
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
SUM=1
I=0
N=N-1
10 I=I+1
SUM=SUM+X**I 1+x+x2+
IF(I-N)10,20,20
2,3
OUTPUT-2:
PROGRAM TO FIND THE SUM OF A SERIES USING ARITHMATIC IF STATEMENT
OUTPUT-3:
PROGRAM TO FIND THE SUM OF A SERIES USING ARITHMATIC IF STATEMENT
-1.5
4
THE SERIES SUM IS= -1.625 Modify to get sum upto X^N terms
2. Logical IF statement:
STATEMENT2
Equal to .EQ. ==
…………………………………………………………………………………………………………………………..
P22-function2.f
OUTPUT-2:
ENTER THE VALUE OF X
3
THE VALUE OF THE FUNCTION IS= 9.27941513
OUTPUT-3:
ENTER THE VALUE OF X
GO TO N
P23-sum.f:
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
P24-valid1.f:
C DATA VALIDATION USING LOGICAL IF STATEMENT
REAL VEL
READ(*,*) VEL
WRITE(*,*) 'Velocity',VEL
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.
P26-promotion.f:
C:\G77\work>p26-promotion
100
63
OUTPUT-2:
C:\G77\work>p26-promotion
50
18
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*,''
PRINT*,''
SUM=1
I=0
10 I=I+1
IF(I.EQ.N) GOTO 20
SUM=SUM+X**I
GOTO 10
STOP
END
OUTPUT:
-1.5 4
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
x2-x-1=0. [Run program P19-root2 to verify].
Where I is the integer variable, N1, N2, ……….NK are the statement numbers.
If I=1, the control goes to statement no. N1
=2, the control goes to statement no. N2
…………………………………………
..………………………………………
=k, the control goes to statement no. Nk
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
…………………………………………………………………………………………………
………………………..
● 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.
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
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
else
endif
stop
endif
stop
endif
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
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
● 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
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:
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.
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
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.
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= * 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.
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= * 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.
…………………………………………………………………………………………………………………………..
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
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.
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.52x1012 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
…………………………………………………………………………………………………
………………………..
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
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
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
456
0.23 12.93
OUTPUT-2:
Input components of first vector
12.35 3.45 -7.89
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
2nd 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 6th 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
formatted c, t and s
c e15.5 0.30000E+11
t e15.5 0.78200E+06
s e15.4 0.2346E+17
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 6th 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
formatted c, t and s
c e15.5 0.30000E+11
t e15.5 0.78200E+06
s e15.4 0.2346E+17
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.
C:\G77\work>p48-format2
Sarat Chatterjee
Mahua Chatterjee
Manab Chatterjee
Name of candidate
Sarat Chatterjee
Name of parents
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
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.
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. 21st data element and
A(10,10) refers to 100th data element. A is called a two dimensional variable (or array) of size
100.
Similarly, a three dimensional array can be declared as:
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.
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
12
31
42
35
67
89
92
30
66
61
Scored numbers
12 31 42 35 67 89 92 30 66 61
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
1234
5678
9 10
Scored numbers
1597654321
• 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
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
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:
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
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
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
OUTPUT-2:
INPUT THE VALUE OF N
10
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
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
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
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
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
1111
OUTPUT-2:
C:\G77\work>p64b-bindec
1010101
1 0 1 0 1 1111101
Position number of the digits 4 3 2 1 0
Value 1x24 + 0x23 + 1x22 + 0x21 +1x20 = 21
Number at the zeroth position is found by mod(10101,10)=1 decimal value= 1x20
To get the 1st position number we first do integer division 10101/10 which gives 1010, the
mod(1010,10) gives the required number=0 decimal value=0x21
This process is continued till the integer division results in 1. Its decimal value=1x24.
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
1111
OUTPUT-2:
C:\G77\work>p64b-bindec
1010101
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
.15625
OUTPUT-2:
Input decimal fraction number
.2
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
OUTPUT-2:
Input decimal number
OUTPUT-3:
Input decimal number
14.2
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 ai,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:
23
123
456
THE MATRIX IS
1. 2. 3.
4. 5. 6.
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
123
456
789
987
654
321
1. 2. 3.
4. 5. 6.
7. 8. 9.
9. 8. 7.
6. 5. 4.
3. 2. 1.
ADDITION MATRIX
TRANSPOSE MATRIX
Similarly one can write a program to get transpose (B) of a given matrix (A), by generating it
using the relation: bij=aji. 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
33
123
456
789
THE MATRIX IS
123
456
789
147
258
369
OUTPUT-2:
C:\G77\work>p69-transmat
34
1234
5678
9 10 11 12
THE MATRIX IS
1234
5678
9 10 11 12
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
33
33
123
456
789
10 11 12
13 14 15
16 17 18
THE PRODUCT IS
OUTPUT-2:
C:\G77\work2>p70-matmult
ENTER ROW & COLUMN NOS OF THE 1ST MATRIX
23
34
123
456
1234
5678
9123
THE PRODUCT IS
Mean = (∑ xi )/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
Input data
1.2
1.5
.8
1.3
1.4
no of data points 5
Mean 1.24000001
1.FUNCTION SUBPROGRAM:
There are two types of function subprograms
● 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
1.5, 2.1
OUTPUT-2:
C:\G77\work>P76-function3
● 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.
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)=x2 + y2 +2xy2
f2(x,y)= x2 - y2
● 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
VALUES OF A,B,C,X,Y,Z 9. 8. 7. 6. 5. 4.
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 x4, y4, z4 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 x4, y4, z4 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.
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
32
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 (nCr). We know n Cr = 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
12 5
n 12 r 5
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
10
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
Pearson coefficient
-1.
OUTPUT-2:
Input no of data points
10
1 2 3 4 5 6 7 8 9 10
10 21 31 41 51 61 71 81 91 101
Pearson coefficient
0.99996078
OUTPUT-3:
Input no of data points
10
1 2 3 4 5 6 7 8 9 10
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.
● 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
11 43 9 23 74
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
1 3 56 5 7
1. 3. 5. 7. 56.
56. 7. 5. 3. 1.
-3 5 12 1 6 78 12
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
PRABAL
PRITAM
TRISHYA
TRINA
TANUJA
PRABAL
PRITAM
TANUJA
TRINA
TRISHYA
10
SHYAM
JADU
MADHU
LAKSHMAN
SITA
PRABAL
PRITAM
TANUJA
TRISHYA
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
987
654
321
11 12 13
14 15 16
17 18 19
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
Matrix BB
Matrix CC=AAxBB
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
aditya birla
65
pradipto bagchi
49
sukhen haldar
56
Enter rollno,name,mark of a student one after another
keya seth
77
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
15 format(I3,3x,A40,I5)
enddo
end
OUTPUT:
C:\G77\work>p90-file2
6
papia nandi
82
bimal mazumdar
50
satya banerjee
61
dinesh bajpai
76
10
kamal saha
77
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 6th 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 5th 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
marks.dat
rank.dat
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
Rank list
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
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
marks.dat
rankout.dat
alphout.dat
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
Rank list
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
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
C1,1.23,3.45,5.67
H1,1.67 -3.72,6.21
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
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
CEXP(X) ex
CSIN(X) Sin (X)
* 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
(1.53465343,0.34653464) (21.9599991,26.7999992)
(3,1)
2.12 4.57
(0.880000114,-3.57000017)
X,XX,CD,XAB,AC
X,XX,CD,XAB,AC
AL,AS,AE,BS,BC
(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
0 1 16
0 1 32
OUTPUT-3:
Input a,b,no of division
0 1 64
OUTPUT-4:
Input a,b,no of division
0 1 100
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)
.2 1.4 12
OUTPUT-6:
Input a,b,no of division
.2 1.4 20
OUTPUT-7:
Input a,b,no of division
.2 1.4 100
OUTPUT-8:
Input a,b,no of division
.2 1.4 150
OUTPUT-8:
Input a,b,no of division
.2 1.4 200
OUTPUT-9:
Input a,b,no of division
.2 1.4 180
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: