SlideShare a Scribd company logo
1 of 35
Download to read offline
KHULNA UNIVERSITY
An assignment on
Simulation Lab-I
(Fortran Programming Language)
5th
year 1st
term
COURSE NO: 0541 12 Math-5114
COURSE TITLE: Simulation Lab-I
Submitted To:
Prof. Dr. Munnujahan Ara
Head of the depertment,
Mathematics Discipline
&
Dr. Ariful Islam
Professor,
Mathematics Discipline
Khulna University,
Khulna-9208.
Submitted By:
Student Name: Md. Al-Amin
Student ID: MSc-231206
Mathematics Discipline,
Khulna University,
Khulna-9208.
Date of Submission: 12th
February,2023
Question
no
Question Name Page interval
01
List the library functions (at least 30) in a table for Fortran
programming language. Also give a few examples in how to
use them in computer code.
01-03
02 Describe data types and different constants in fortran with
examples.
04-06
03 Describe assignment statements, expressions and hierarchy of
operations in Fortran with proper examples.
06-07
04 Describe the BLOCK IF structure with its syntax. Write two
Fortran codes by using the BLOCK IF structure.
08-09
05
Describe DO LOOP and NESTED DO LOOP with its syntax.
Write two Fortran codes to explain the DO LOOP and
NESTED DO LOOP.
10-12
06
Explain unconditional transfer with examples. Write two
different Fortran programs as an example of unconditional
transfer.
13-15
07
Describe arrays and subprogram with examples. Illustrate it
graphically where applicable. Develop two different Fortran
codes as an example of arrays and subprogram.
15-17
08
Describe SELECT case constructs. Give two examples by
developing Fortran programs related to the SELECT case
construct.
18-21
09
What is function subprogram? Describe the syntax of function
subprogram. Give two different Fortran codes as an example
of function subprogram.
21-23
Table of contents
10 What is subroutine subprogram? Explain subroutine
subprogram graphically with examples.
24-27
11
Explain the common statement with its syntax. Use graphical
notations where applicable. Also write a Fortran program to
illustrate the common statement.
28-29
12 Describe File processing with examples. 30-32
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 1
Fortran is a computer programming language that is extensively used in numerical,
scientific computing. While except the scientific community, Fortran has declined in
popularity over the years, it still has a strong user base with scientific programmers, and is
also used in organizations such as weather forecasters, financial trading, and in engineering
simulations. Fortran programs can be highly optimized to run-on high-performance
computers, and in general the language is suited to producing code where performance is
important. Fortran is a compiled language, or more specifically it is compiled ahead-of-
time. In other words, you must perform a special step called compilation of your written
code before you are able to run it on a computer. This is where Fortran differs
to interpreted languages such as Python and R which run through an interpreter which
executes the instructions directly, but at the cost of compute speed. We use a function by
placing its name (followed by its arguments) in an expression. We must take great care to
match the type, number and order of arguments required for the function. We summarize
the most common functions below.
Serial Name Description Argument Result Example
1. abs(x) absolute
value
integer
real
double
integer
real
double
j=abs(-15)
x=abs(-2.66)
z=abs(-0.1d06)
2. sqrt(x) square root real
double
real
double
x=sqrt(6.2)
x=sqrt(0.17d1)
3. mod(i,j) integer
reminder of
i/j
integer integer j=mod(22,3)
4. int(x) converts to
integer
real
double
integer
integer
j=int(2.6666)
j=int(0.266d01)
5. float(i) converts to
real
integer
double
real
real
x=float(2)
x=float(0.6d01)
6. floor(x) floor value integer
real
integer
real
x=floor(2.6)
x=floor(2.2)
Question 01: List the library functions (at least 30) in a table for Fortran programming
language. Also give a few examples in how to use them in computer code.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 2
7. ceiling(x) ceiling value integer
real
integer
real
x= ceiling(2.6)
x= ceiling(2.2)
8. exp(x) exponential real
double
real
double
x=exp(2.0)
x=exp(1.0d0)
9. nint(x) round to
nearest
integer
real
double
integer
integer
j=nint(2.66)
j=nint(0.6d02)
10. real(i) convert to
real
integer
double
real
real
x=real(2)
x=real(0.26d02)
11. sin(x) sine real(rad)
double(rad)
real
double
x=sin(0.6202)
x=sin(0.62d02)
12. cos(x) cosine real(rad)
double
real
double
x=cos(1.047)
x=cos(1.047d0)
13. tan(x) tangent real(rad)
double
real
double
x=tan(0.622)
x=tan(0.622d0)
14. acos(x) arccosine real
double
real(rad)
double(rad)
x=acos(0.6)
x=acos(0.6d0)
15. asin(x) arcsine real
double
real(rad)
double(rad)
x=asin(0.6)
x=asin(0.6d0)
16. alog(x) natural
logarithm
real
double
real
double
x=alog(2.61)
x=alog(2.6d1)
17. alog10(x) logarithm
base 10
real
double
real
double
x=alog10(2.61)
x=alog10(2.6d1)
18. atan(x) arctangent real
double
real(rad)
double(rad)
x=atan(1.0)
x=atan(1.0d0)
19. dble(x) Converts to
double
integer
real
double
double
x=dble(3)
x=dble(3.0)
20. amax(..) Returns
lagest value
integer
real
double
integer
real
double
i=amax(5,2,6,7)
x=amax(0.2,5.6)
x=amax(1d0,3d3
)
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 3
21. amin(..) returns
smallest
value
integer
real
double
integer
real
double
i=amin(5,-2,6,7)
x=amin(0.2,5.6)
x=amin(1d0,3d3)
22. fraction(x) fractional
part of a
number
real real x= fraction(6.22)
23. huge (x) largest
number of
the model
real real x=huge (1.66)
24. maxexpone
nt(x)
maximum
exponent
integer
real
integer
real
x=maxexponent(
1.6)
25. tiny (x) smallest
positive
number
integer
real
integer
real
x=tiny (10.6)
26. digits (x) significant
digits
integer
real
integer
real
x=digits (1.22)
27. cosh (x) hyperbolic
cosine
integer
real
integer
real
x=cosh (1.0)
28.
dim (x, y)
it returns the
positive
difference of
x and y.
integer
real
integer
real
z=dim (11, -10)
z=dim (11, -10)
29. dble (x) converts x to
a double
precision
real number
integer
real
integer
real
z=dble (10.5)
z=dble (10.5)
30. modulo(a,p) returns the
remainder of
a on division
by p
integer
real
integer
real
z=modulo (10, 3)
z=modulo (10, 3)
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 4
The smallest common grouping of bits is called a byte. A byte is a group of 8 bits. Fortran
77 contains six intrinsic data types that are built automatically into the language. These are
divided into two categories: numerical and nonnumerical.
Data types
1. Integer constant
The integer data type consists of the positive, negative and zero. The range of values
that can be represented on a computer depends specifically on the computer. However,
a typical range is from -232-1
to 232-1
-1 for a 32-bit computer.
Question 02: Describe data types and different constants in fortran with examples.
Numerical Nonnumerical
3. Integer
4. Real
5. Double precision
6. Complex
1. Character
2. Logical
Valid examples
-666
10
+10
111 111 111
Invalid examples and reason
66/6 (no fraction)
10.0 (no decimal points)
111,111,111 (no commas)
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 5
2. Real constants
Real number stores the floating point numbers such as 2.0, 3.1416 etc. real numbers are
stored in the computer as two components: a mantissa ranging between 0.1 and 1.0 also
an exponent that indicates the appropriate power of 10. Real constants are those that we
think of as fractional numbers which may be positive or negative and always have a
decimal point. Real constant can also be used with scientific notation.
3. Double precision constants
If more than 7 digits of accuracy are required, then we can use a double precision
constant, which is accurate to 14 to 16 decimal places, depending on machine. Double
precision is simple to use. Instead of using E for the exponent, double precision simply
substitutes the letter D.
4. Complex constants
This is used for storing complex numbers. A complex number has two parts, the real
part and imaginary part.
Valid examples
-6.6
0.0026
+2.2
122 62.0
1E2
0.0E0
0.1E-24
Invalid examples and reason
66 (requires a decimal point)
$10.0 (only numbers permitted)
111,111,111 (no commas)
0.1E-6.5 (exponent must be integer)
0.1E-126 (value too small on most computer)
0.1E+126 (value too big on most computer)
Valid examples
0.6D6
0.0D0
0.23D-94
122 62.0
Invalid examples and reason
0.123E23 (Not double precision)
2.163E26 (Not double precision)
16.3E26 (Not double precision)
Valid examples
(1.23, 6.2)
(+1.2E3, 0.0)
3.0C-5.0i
Invalid examples and reason
(1, 2) (integer not allowed)
(1.2D3, 3.4) (both not match in precision)
(1, 2.1) (integer not allowed)
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 6
5. Character constants
The character data type consists of characters and symbols.
Letters of the alphabet (upper or lower case)
Numbers 0 to 9
Special character + - * / ( ) . {} [ ] ! @ # ^ , = ‘’ $
Blank space
The most important coding system is ASCII.
6. Logical constants
There are only two logical values: .true. and .false.
Assignment statement: The assignment statement is the primary means of storing data in
variables. As the name assignment statement implies, we are telling the computer to assign
a value to a given variable. The general form of the assignment statement is:
Target  Value from an expression
Invalid examples and reason
True (requires periods)
.F. (must spell out complete word)
.T . (must spell out complete word)
Question 03: Describe assignment statements, expressions and hierarchy of operations
in Fortran with proper examples.
Valid examples
‘Imam’
‘Ar’’salan’
‘231206’
Invalid examples and reason
Imam (missing quote marks)
“Imam” (must be single quotes)
‘I > math’ (illegal character >)
Valid examples
.True.
.False.
.false.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 7
The interpretation of this statement is “The target receives a value obtained from the
expression”. The way this is implemented in Fortran is:
Variable = Value from an expression
The expression on the right hand side (RHS) of the equal sign can be one of several types
as discussed below.
Expression Type of Expression
Result = 3.72
CGPA = Result
Y = sqrt(CGPA)
Constant assigned to the variable Result
The value of the variable Result assigned to CGPA
Evaluate the square root of CGPA
Expressions and hierarchy of operations: All of the examples of expressions have been
simple ones. They’ve consisted simply of multiplication, or addition and subtraction. There
are only five basic arithmetic operations possible with Fortran. They are addition,
subtraction, multiplication, division and exponentiation as presented in the following table:
Priority Algebraic symbol Fortran symbol Meaning
1
2
3
3
4
4
(…)
𝐴𝑏

÷
+
-
(…)
**
*
/
+
-
Parentheses
Exponentiation
Multiplication
Division
Addition
Subtraction
In order to create mathematical expressions, we must use the symbols listed in the table on
a single text line entered into our program. While algebra permits the use of multiple line
expressions, Fortran requires us to place the expression on a single line. For all of the
operators with equivalent position within the hierarchy (expect **), evaluation is from left
to right. For exponentiation, the direction is from right to left. For example 6.0/2.0*5.0 gives
15.0, since the division is done first and then the multiplication.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 8
The IF statement is useful when we have only a single instruction to execute after the test
condition is evaluated. But when we have more than one instruction, we need a different
structure. In Fortran this is BLOCK IF structure. As its name implies, it consists of blocks
of instruction will execute when the test condition is false. The general form of the BLOCK
IF construct is as follows:
IF (Test condition) THEN
Block of statement if test condition is true
ELSE
Block of statements if test condition is false
END IF
Here it is noticeable that, on the same line as the THEN, ELSE, or END IF key words.
Example: 01
!input marks and print the grade obtained using else if
PROGRAM GRADE
PRINT*,'input marks'
READ*,MARKS
IF(MARKS>=80 .AND. MARKS<=100) THEN
PRINT*,'GRADE A+'
ELSE IF(MARKS>=75 .AND. MARKS<=79) THEN
PRINT*,'GRADE A'
ELSE IF(MARKS>=70 .AND. MARKS<=74) THEN
PRINT*,'GRADE A-'
ELSE IF(MARKS>=65 .AND. MARKS<=69) THEN
PRINT*,'GRADE B+'
ELSE IF(MARKS>=60 .AND. MARKS<=64) THEN
PRINT*,'GRADE B'
ELSE IF(MARKS>=55 .AND. MARKS<=59) THEN
PRINT*,'GRADE B-'
ELSE IF(MARKS>=50 .AND. MARKS<=54) THEN
PRINT*,'GRADE C+'
ELSE IF(MARKS>=45 .AND. MARKS<=49) THEN
PRINT*,'GRADE C'
ELSE IF(MARKS>=40 .AND. MARKS<=44) THEN
PRINT*,'GRADE D'
ELSE
PRINT*,'GRADE F'
END IF
END PROGRAM GRADE
Question 04: Describe the BLOCK IF structure with its syntax. Write two Fortran codes
by using the BLOCK IF structure.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 9
Example: 02
!largest and smallest value amoung 3 values
PROGRAM NAME
implicit none
real a,b,c
print*,'enter the values of a,b and c'
read*,a,b,c
if(a>b .AND. a>c) then
print*,'the largest value a is ',a
else if(b>a .AND. b>c) then
print*,'the largest value b is ',b
else
print*,'the largest value c is ',c
end if
if(a<b .AND. a<c) then
print*,'the Smallest value a is ',a
else if(b<a .AND. b<c) then
print*,'the smallest value b is ',b
else
print*,'the smallest value c is ',c
end if
end program
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 10
Do loop: The do loop construct enables a statement, or a series of statements, to be carried
out iteratively, while a given condition is true. The general form of the do loop is
do var = start, stop [,step]
! statement(s)
…
end do
Where,
▪ the loop variable var should be an integer
▪ start is initial value
▪ stop is the final value
▪ step is the increment, if this is omitted, then the variable var is increased by unity
Example: 01
!max value amount given values
PROGRAM NAME
implicit none
integer N,i
real max,a
print*,'How many numbers you want to give as input?'
read*,N
print*,'Enter values'
max=0
do i=1,N,1
read*,a
if(max < a) then
max=a
end if
end do
print*,'The maximum value is'
Print*,max
end program
Question 05: Describe DO LOOP and NESTED DO LOOP with its syntax. Write two
Fortran codes to explain the DO LOOP and NESTED DO LOOP.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 11
Nested do loop: Just like an IF-THEN-ELSE-END IF can contain another IF-THEN-
ELSE-END IF (see nested IF for the details), a DO-loop can contain other DO-loops in its
body. The body of the contained DO-loop, usually referred to as the nested DO-loop, must
be completely inside the containing DO-loop. Note further that an EXIT statement only
brings the control out of the inner-most DO-loop that contains the EXIT statement.
Suppose we have the following nested DO loops:
DO
statements-1
DO
statement-2
END DO
statement-3
END DO
Each iteration of the outer DO starts with statements-1. When the control reaches the
inner DO, statements-2 is executed until some condition of the inner DO brings the control
out of it. Then, statements-3 is executed and this completes one iteration. Any EXIT in the
inner DO brings the control out of the inner DO to the first statement in statement-3.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 12
Example: 02
!SUM OF THE SERIES 1+2+3+4+...+N using nested do
PROGRAM NUMBER
implicit none
integer:: i,j,sum,N
PRINT*,'input the value of N'
READ*,N
do i=1,N
SUM=0
DO j=1,i
SUM=SUM+j
END DO
end do
PRINT*,'THE ANS OF SUM OF THIS SERIES IS',SUM
END PROGRAM NUMBER
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 13
Unconditional transfer: The unconditional transfer statement, or GO TO statement, is the
simplest transfer operation. It provides a means by which control transfer to another line in
the program. The line to receive the control must be labeled using a statement label. The
general form of the GO TO statement is:
GO TO statement label
When an unconditional GO TO is encountered, control is immediately transferred to the
executable statement labelled with the label. Whilst it is sometimes necessary to use
unconditional go to statements in a program, they should be used sparingly lest unreadable
'spaghetti' code result. A GO TO statement may be used to transfer control out of a
block if or do loop but not in to them. The unconditional GO TO statement is often used in
conjunction with logical or block if statements to construct loops when a simple do loop is
not appropriate.
10 CONTINUE
WRITE(*,*)'Enter a positive value'
READ(*,*)A
IF (A .LE. 0.0) GO TO 10
The statement labelled 10 is a continue statement which is often used at the beginning or
end of a loop structure. This program fragment executes the continue statement (which does
nothing) and then prints out the statement enter a positive value. The program then reads in
a value from the standard input device and stores it in the variable a. At this point a is tested
to see if it is positive. If it is, then control passes to the next executable statement, but if it
isn't, then the GO TO 10 statement is executed and the program returns to
the continue statement. The program then goes through the write and read statements again
and tests the new value of a. The program will not break out of this loop until a is positive.
The indentation of the loop body makes the structure of the program that much more
readable.
Question 06: Explain unconditional transfer with examples. Write two different Fortran
programs as an example of unconditional transfer.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 14
Example:- 01 (Using parallel studio XE 2010)
program MAIN
integer a
goto 11
10 write(*,'("Here we go again")')
! lots of lines of your code
11 write(*,'("Enter 1 to go around again:")')
read(*,*) a
if (a.eq.1) goto 10
end
Example:- 02
program computed
integer day
write(*,*)'Enter the day of a week'
read(*,*)day
goto (20,10,12,13,15,16,18),day
10 write(*,*)'The day is Sunday'
goto 25
12 write(*,*)'The day is Monday'
goto 25
13 write(*,*)'The day is Tuesday'
goto 25
15 write(*,*)'The day is Wednesday'
goto 25
16 write(*,*)'The day is Thursday'
goto 25
18 write(*,*)'The day is Friday'
goto 25
20 write(*,*)'The day is Saturday'
25 stop
end program computed
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 15
Array: An array is a group of variables denoted by a single name having same type. That
means, an array of strings is a collection of strings. Where, an ordinary variable holds only
a single value. And an array variable holds multiple values. If an array is not initialized, the
contents of the array elements are undefined. Suppose, array j is an example of uninitialized
array.
integer, dimension(10)::j
write(*,*) j(1)
There are three techniques to initialized the elements in an array:-
1. Using assignment statement
real, dimension(10)::a
do i=1,10
a(i)=0.0
end do
2. Using real statement
real, dimension(10)::a
do i=1,10
read*,a(i)
end do
3. Initializing array in the type declaration statement.
real, dimension(3)::a=(/1,2,3/)
Question 07: Describe arrays and subprogram with examples. Illustrate it graphically
where applicable. Develop two different Fortran codes as an example of arrays and
subprogram.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 16
Arrays and Subprograms: Here our main focus on passing single valued variables to
subprograms. But we can pass arrays also if we declare the arrays in both modules. While
this sounds like a duplication of effort, recall that subprograms are standalone modules.
Thus, if we are going to use an array in the module we must declare it in the main and
subprogram modules where they are used.
Example:- 01
!Multiplication of given numbers
program name
implicit none
integer,dimension(100)::a
integer::n,i
real::ave,sum
Print*,'Enter the how many numbers do you want to multiplication:'
read*,n
print*,'Please Enter the number:'
do i=1,n
read*,a(i)
end do
call mark(a,n,sum)
print*,'Multiplication of given numbers is',sum
end
subroutine mark(a1,n1,sum1)
integer,dimension(100)::a1
integer::n1,i
sum1=1.0
do i=1,n1
sum1=sum1*a1(i)
end do
return
stop
end
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 17
Example:- 02
!Sum of given numbers
program name
implicit none
integer,dimension(100)::a
integer::n,i
real::ave,sum
Print*,'Enter the how many numbers do you want to sum:'
read*,n
print*,'Please Enter numbers:'
do i=1,n
read*,a(i)
end do
call mark(a,n,sum)
print*,'Sum of given numbers is',sum
end
subroutine mark(a1,n1,sum1)
integer,dimension(100)::a1
integer::n1,i
sum1=0.0
do i=1,n1
sum1=sum1+a1(i)
end do
return
stop
end
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 18
The select case provides a means of selecting an action (which can be a block of statements)
by comparing the value of an expression against a list of values. The general form of the
select case construct is:
SELECT CASE (expression)
CASE(selector list 1)
Block 1
CASE(selector list 2)
Block 2
…
CASE DEFAULT
Block n
END SELECT
As with the previous block structures, there are key words to mark the beginning and end
of the structure- the SELECT CASE and END SELECT statements respectively. In between
are a series of CASES, only one of which is executed based on the value of the expression
in the SELECT CASE statement. The expression is a scalar (single-valued) expression
which can have integer, character, or logical data type. Once this expression is evaluated,
its value is compared with the values contained in the selector lists until a match is found.
The list of instructions that follow this CASE is then executed. If the expression in the CASE
SELECT expression has match among the various selector lists, then the instructions in the
CASE DEFAULT are executed. The CASE DEFAULT statement is optional. The selector
list for each of the CASES can be a single value, a list, or a range of values specified by
low-value: high-value, or a list of values which include ranges. This will become me obvious
in the following examples. Also, the selector lists must not overlap in values. The type of
the expression and selectors must match. Thus, if the expression is a character string, then
the selectors must also be character strings. Lengths of strings do not necessarily have to
match. If the expression is of type integer or logical, then the selectors also be of the same
type. SELECT CASE construct determines which block is to be executed by checking if
the expression equals any of the values defined by the selectors. If the equality is true, then
that block is executed and control passes to the END SELECT command.
Question 08: Describe SELECT case constructs. Give two examples by developing
Fortran programs related to the SELECT case construct.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 19
Example:- 01
!Input N numbers and how many operations can be done?Show all the
operation.
PROGRAM NAME
implicit none
real N,A,sum
integer i,option
character press
print*,'How many numbers you want to give as input?'
read*,N
5 print*,'What operation do you want to do?'
print*,'press 1 for addition'
print*,'press 2 for multiplication'
read*,option
select case(option)
case(1)
i=0
sum=0
print*,'Please input the N numbers'
10 read*,A
i=i+1
sum=A+sum
if(i .ne. N) goto 10
Print*,'Addition of the input numbers= ',sum
case(2)
i=0
sum=1
print*,'Please input the N numbers'
1 read*,A
i=i+1
sum=A*sum
if(i .ne. N) goto 1
Print*,'Multiplication of the input numbers= ',sum
case default
print*,'wrong input'
end select
stop
END PROGRAM
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 20
Example:- 02
!Input 3 numbers and use case case.
PROGRAM NAME
implicit none
real a,b,c
integer i,option
character press
5 print*,'What operation do you want to do?'
print*,'press 1 for Largest value'
print*,'press 2 for Smallest value'
read*,option
select case(option)
case(1)
print*,'Enter the values of a,b and c'
10 read*,a,b,c
if(a>b .AND. a>c) then
print*,'The largest value a is ',a
else if(b>a .AND. b>c) then
print*,'The largest value b is ',b
else
print*,'The largest value c is ',c
end if
case(2)
print*,'Enter the values of a,b and c'
1 read*,a,b,c
if(a<b .AND. a<c) then
print*,'The Smallest value a is ',a
else if(b<a .AND. b<c) then
print*,'The smallest value b is ',b
else
print*,'The smallest value c is ',c
end if
case default
print*,'wrong input'
end select
stop
END PROGRAM
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 21
The simplest type of subprogram is the function subprogram whose purpose is to calculate
a single numerical answer and return the result. Function subprogram receive one or more
values from calling program and can return only one value to the calling program.
The general form of function subprogram is given below:
Type FUNCTION name (a1, a2, …, ap)
…
…
Name=expression
…
…
Return
End
The first line of the subprogram states that this is a function and gives it a name, which is
the same as the one to be used in the main program calling statement. This name is also used
as a variable within the subprogram to which the desired value will be assigned. Because
the function name is also a variable inside the function, the type of the variable may need to
be declared. That is why there is a typing option at the beginning of the function statement.
Following the name is an optional list of variables that the function needs for the calculation.
Question 09: What is function subprogram? Describe the syntax of function
subprogram. Give two different Fortran codes as an example of function subprogram.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 22
Example:01
!factorial using sub program sub function
program name
print*,'enter the number'
read*,n
print*,'factorial of',n,' is',ifact(n)
end
function ifact(m)
ifact=1
do i=1,m
ifact=ifact*i
end do
m=445456569
return
stop
end
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 23
Example:02
!find sum and average using sub program sub function
program name
implicit none
integer,dimension(100)::a
integer::n,i
real::ave,sum
Print*,'Enter the how many numbers do you want to sum:'
read*,n
print*,'Please Enter the number:'
do i=1,n
read*,a(i)
end do
call averagemark(a,n,ave,sum)
print*,'Sum of given numbers is',sum
print*,'Average of given numbers is',ave
end
function averagemark(a1,n1,ave1,sum1)
integer,dimension(100)::a1
integer::n1,i
sum1=0.0
do i=1,n1
sum1=sum1+a1(i)
end do
ave1=sum1/n1
return
stop
end
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 24
The second type of subprogram is the subroutine. Like the function, it stands outside the
main program and uses local variables. Received one or more values from the calling
program and can return several values to the calling program. As with functions, the use of
a subroutine requires a three-step process to
▪ call the subroutine from the main program
▪ pass data to the subroutine
▪ set up the subroutine to receive the passed data, process it, and return the results
The procedure for calling a subroutine is a little different from that for a function because
of the larger amount of data returned. We used functions when a single numerical answer
was sufficient. But with subroutines, we can return any amount of data. Therefore, the
subroutine is more versatile. With subroutines, we pass data to and from the subroutine with
the calling statement:
CALL subroutinename (variablel, variable2, . . ., variableN)
where subroutinename is the name of the specific subroutine that you want to use and
variablel...variableN is a list of variables passing back and forth between the main and the
subroutine. These variables are two-way variables. They may pass data to the subroutine or
they may receive results, depending upon the context. The corresponding statements which
set up the subroutine are:
SUBROUTINE subroutinename (variable1, variable2, . . . , variableN)
…
…
RETURN
END
The identifier subroutinename must be identical with the one in the calling statement and
must follow the standard rules for any variable name. The argument list in the calling
Question 10: What is subroutine subprogram? Explain subroutine subprogram
graphically with examples.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 25
statement and in the subroutine statement must have the same number of variables, and each
must agree in type with its counterpart. They need not have the same variable names. Thus:
…
CALL ADD ( X , Y, Z, I, SUM )
…
SUBROUTINE ADD ( A, B, C, L, TOT )
…
RETURN
END
In this example, the first variable in the subroutine argument list A receives the value of the
first variable in the calling argument list X. Similarly, B receives the value of Y, C receives
the value of Z, and so forth. Also, the variables sending and receiving the data must match
in type. Thus, if X is real, A must be real, and if I is an integer, then L must also be an
integer. The variables in the argument lists can either send or receive data. Usually, this will
be obvious from the context of the problem. In the example given, X, Y, Z, and I are sending
data to the subroutine, while SUM is the variable where the returned answer is stored. But
each variable is also a two-way variable. Thus, we may use X to send data down, but if the
subprogram modifies the corresponding variable A, then X will change also.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 26
Example :01
!maximum and minimum value using subroutine sub program
program name
implicit none
real,dimension(100)::a
integer::n,i
real::ave,sum,max,min
Print*,'Enter the how many numbers do you want to take:'
read*,n
print*,'Please Enter the number:'
do i=1,n
read*,a(i)
end do
call mark(a,n,max,min)
print*,'Maximum of given numbers is',max
print*,'Minimum of given numbers is',min
end
subroutine mark(a1,n1,ma,mi)
real,dimension(100)::a1
integer::n1,i
real::ma,mi
ma=a1(1)
mi=a1(1)
do i=1,n1
if(ma<a1(i)) ma=a1(i)
if(mi>a1(i)) mi=a1(i)
end do
return
stop
end
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 27
Example:- 02
!multiplication value using subroutine sub program
program name
implicit none
integer,dimension(100)::a
integer::n,i
real::ave,sum
Print*,'Enter the how many numbers do you want to
multiplication:'
read*,n
print*,'Please Enter the number:'
do i=1,n
read*,a(i)
end do
call mark(a,n,sum)
print*,'Multiplication of given numbers is',sum
end
subroutine mark(a1,n1,sum1)
integer,dimension(100)::a1
integer::n1,i
sum1=1.0
do i=1,n1
sum1=sum1*a1(i)
end do
return
stop
end
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 28
Fortran 77 has no global variables, i.e. variables that are shared among several program
units (subroutines). The only way to pass information between subroutines we have seen so
far is to use the subroutine parameter list. Sometimes this is inconvenient, e.g., when many
subroutines share a large set of parameters. In such cases one can use a common block. This
is a way to specify that certain variables should be shared among certain subroutines. But
in general, the use of common blocks should be minimized.
Suppose you have two parameters alpha and beta that many of your subroutines need. The
following example shows how it can be done using common blocks.
program main
some declarations
real alpha, beta
common /coeff/ alpha, beta
statements
stop
end
subroutine sub1 (some arguments)
declarations of arguments
real alpha, beta
common /coeff/ alpha, beta
statements
return
end
subroutine sub2 (some arguments)
declarations of arguments
real alpha, beta
common /coeff/ alpha, beta
statements
return
end
Here we define a common block with the name coeff. The contents of the common block
are the two variables alpha and beta. A common block can contain as many variables as
you like. They do not need to all have the same type. Every subroutine that wants to use any
of the variables in the common block has to declare the whole block.
Question 11: Explain the common statement with its syntax. Use graphical notations
where applicable. Also write a Fortran program to illustrate the common statement.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 29
Note that in this example we could easily have avoided common blocks by passing alpha
and beta as parameters (arguments). A good rule is to try to avoid common blocks if
possible. However, there are a few cases where there is no other solution.
COMMON / name / list-of-variables
Here, we should know that
▪ The common statement should appear together with the variable declarations,
before the executable statements.
▪ Different common blocks must have different names (just like variables).
▪ A variable cannot belong to more than one common block.
▪ The variables in a common block do not need to have the same names each place
they occur (although it is a good idea to do so), but they must be listed in the same
order and have the same type and size.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 30
A file is a list of records, each of which is a list of values or characters. A FORTRAN
program can read from and write to the files stored on an external storage device. Instead of
the usual READ statement, file processing employs a more general form of READ
statement. Also, WRITE command replaces the PRINT command.
READ (cilist) input_list
WRITE (cilist) output_list
cilist is a list of specifiers pointing to the file, its format, and other processing details with
commas in between. Some of the specifiers are UNIT, FMT, ERR, and END. In cilist, the
order of the specifiers does not matter. The value of the UNIT specifier gives a unit identifier
specific to a file. For instance, each file is associated with a unit number, which is an integer
between 1 to 99. Integers 5 & 6 specifies standard input & output respectively. Asterisk (*)
refers to the keyboard for input and screen for the output. The value of the FORMAT
specifier FMT is the label of FORMAT statement.
READ (UNIT = 5, FMT = 100) X, Y, Z
or
READ (FMT = 100, UNIT = 5) X, Y, Z
Here, order of the specifiers does not matter. If one requires reading the content of the file
as it is i.e without any formatting, write unit specifier in the first place without the keyword
UNIT and in place of FORMAT specifier place an asterisk (*) symbol.
Open/Create the file:
A unit identifier is assigned to the files other than the standard I/O files. An OPEN statement
calls the file with its name and labels it with a unit identifier.
OPEN (open_list)
open_list is a list of specifiers of the form keyword= value with commas in between. It
includes two specifiers: UNIT and FILE. The value of the UNIT is the identifier of the file
and the value of FILE is the name of the file. If no such file exists, a new file appears in
York directory with this name. For example:
Question 12: Describe File processing with examples.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 31
OPEN ( UNIT = 8, FILE = 'MYFILE.DAT' )
Close the file:
Close command closes a single or several files simultaneously. For example: First statement
below close a single file with unit number 6. The second command three files
simultaneously. However, it is not necessary to close the files using CLOSE command.
STOP or END statements close them automatically.
CLOSE (6)
CLOSE (1,2,3)
Here is a simple example of how to write to a data file named EXPER.DAT:
OPEN (UNIT=2, FILE='EXPER. DAT', STATUS=' NEW')
WRITE (2,*) DIST, TIME, VELOC
CLOSE (2)
The first statement, OPEN(...), contains all the information needed to set up the file with the
name 'EXPER.DAT'. We will call this for simplicity the UNIT. This unit number comes in
handy since it is easier to type the single number (2) than to use the full file name in every
I/O statement. Thus, in subsequent statements when we refer to 2, we are referring to its
equivalent file name 'EXPER.DAT'. The final listing in the OPEN statement shows the
status of the file. As we will see shortly, it will be either 'NEW', 'OLD', 'SCRATCH', or
'UNKNOWN' indicating whether the file needs to be created, already exists, is only
temporary, or unknown respectively. The second statement, WRITE(2,*) list, is used to
direct the output to the desired file. Remember that we have given the file the short name of
2. Thus, the WRITE statement tells the computer to send the output to the unit that has the
file name 'EXPER.DAT' and associated with UNIT=2. The final statement of the example,
CLOSE(...), simply closes the file after we finish with it. A similar set of statements can be
used to read from a data file. The primary difference from the output statement is that the
file must already exist to read from it. Therefore, its STATUS will be 'OLD'.
Here is a simple example of how to read a data file:
we will read data from a file named 'NOBEL.DAT' and assign the data to the variables
WEIGHT, MASS, and DENSIT. Notice that the file must already exist in order to read from
it.
A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 32
OPEN (UNIT=3, FILE='NOBEL. DAT', STATUS=' OLD')
READ (3, *) WEIGHT, MASS, DENSIT
CLOSE (3)
Notice that the READ statement goes to unit #3, which is the shorthand notation for the file
'NOBEL.DAT'. Also note that the status of the file is 'OLD', which indicates that it is a valid
file for reading. If the status had not been 'OLD', a syntax error would have resulted.
Example:
program fileprocess
implicit none
real, dimension(10) :: x, y
real, dimension(10) :: a, b
integer :: i
! data
do i = 1,10
x(i) = i * 0.1
y(i) = sin(x(i)) * (1-cos(x(i)/3.0))
end do
! output data into a file
open(1, file = 'data1.dat', status='new')
do i = 1,10
write(1,*) x(i), y(i)
end do
close(1)
! opening the file for reading
open (2, file = 'data1.dat', status = 'old')
do i = 1,10
read(2,*) a(i), b(i)
end do
close(2)
do i = 1,10
write(*,*) a(i), b(i)
end do
end program fileprocess

More Related Content

What's hot

日曜数学者のための面白いと思ってもらえるプレゼン術
日曜数学者のための面白いと思ってもらえるプレゼン術日曜数学者のための面白いと思ってもらえるプレゼン術
日曜数学者のための面白いと思ってもらえるプレゼン術Junpei Tsuji
 
Mathematicaで 機械学習してみた
Mathematicaで機械学習してみたMathematicaで機械学習してみた
Mathematicaで 機械学習してみたYu(u)ki IWABUCHI
 
FA技術の最新動向と今後の課題
FA技術の最新動向と今後の課題FA技術の最新動向と今後の課題
FA技術の最新動向と今後の課題nagaok
 
No Cloning Theorem with essential Mathematics and Physics
No Cloning Theorem with essential Mathematics and PhysicsNo Cloning Theorem with essential Mathematics and Physics
No Cloning Theorem with essential Mathematics and PhysicsRitajit Majumdar
 
Schönhage Strassen Algorithm
Schönhage Strassen AlgorithmSchönhage Strassen Algorithm
Schönhage Strassen Algorithmcookies 146
 
エキスパートGo
エキスパートGoエキスパートGo
エキスパートGoTakuya Ueda
 
200604material ozaki
200604material ozaki200604material ozaki
200604material ozakiRCCSRENKEI
 
電路學 - [第二章] 電路分析方法
電路學 - [第二章] 電路分析方法電路學 - [第二章] 電路分析方法
電路學 - [第二章] 電路分析方法Simen Li
 
SpectreBustersあるいはLinuxにおけるSpectre対策
SpectreBustersあるいはLinuxにおけるSpectre対策SpectreBustersあるいはLinuxにおけるSpectre対策
SpectreBustersあるいはLinuxにおけるSpectre対策Masami Hiramatsu
 
Coq Tutorial
Coq TutorialCoq Tutorial
Coq Tutorialtmiya
 
Software Development for Space-group Analysis: Magnetic Space Group and Irred...
Software Development for Space-group Analysis: Magnetic Space Group and Irred...Software Development for Space-group Analysis: Magnetic Space Group and Irred...
Software Development for Space-group Analysis: Magnetic Space Group and Irred...Kohei Shinohara
 
LIGO - General Information
LIGO - General InformationLIGO - General Information
LIGO - General InformationIan Rothbarth
 
Gravitational waves
Gravitational wavesGravitational waves
Gravitational wavesnaveen yadav
 
Lie-Trotter-Suzuki分解、特にフラクタル分解について
Lie-Trotter-Suzuki分解、特にフラクタル分解についてLie-Trotter-Suzuki分解、特にフラクタル分解について
Lie-Trotter-Suzuki分解、特にフラクタル分解についてMaho Nakata
 
Quantum entanglement (1).pptx
Quantum entanglement (1).pptxQuantum entanglement (1).pptx
Quantum entanglement (1).pptxSandraJoseph49
 
龍騰[掌握]數學A複習講義
龍騰[掌握]數學A複習講義龍騰[掌握]數學A複習講義
龍騰[掌握]數學A複習講義lungtengtech
 
qubitによる波動関数の虚時間発展のシミュレーション: a review
qubitによる波動関数の虚時間発展のシミュレーション: a reviewqubitによる波動関数の虚時間発展のシミュレーション: a review
qubitによる波動関数の虚時間発展のシミュレーション: a reviewMaho Nakata
 

What's hot (20)

日曜数学者のための面白いと思ってもらえるプレゼン術
日曜数学者のための面白いと思ってもらえるプレゼン術日曜数学者のための面白いと思ってもらえるプレゼン術
日曜数学者のための面白いと思ってもらえるプレゼン術
 
Mathematicaで 機械学習してみた
Mathematicaで機械学習してみたMathematicaで機械学習してみた
Mathematicaで 機械学習してみた
 
FA技術の最新動向と今後の課題
FA技術の最新動向と今後の課題FA技術の最新動向と今後の課題
FA技術の最新動向と今後の課題
 
No Cloning Theorem with essential Mathematics and Physics
No Cloning Theorem with essential Mathematics and PhysicsNo Cloning Theorem with essential Mathematics and Physics
No Cloning Theorem with essential Mathematics and Physics
 
Schönhage Strassen Algorithm
Schönhage Strassen AlgorithmSchönhage Strassen Algorithm
Schönhage Strassen Algorithm
 
エキスパートGo
エキスパートGoエキスパートGo
エキスパートGo
 
200604material ozaki
200604material ozaki200604material ozaki
200604material ozaki
 
電路學Chapter5
電路學Chapter5電路學Chapter5
電路學Chapter5
 
電路學 - [第二章] 電路分析方法
電路學 - [第二章] 電路分析方法電路學 - [第二章] 電路分析方法
電路學 - [第二章] 電路分析方法
 
SpectreBustersあるいはLinuxにおけるSpectre対策
SpectreBustersあるいはLinuxにおけるSpectre対策SpectreBustersあるいはLinuxにおけるSpectre対策
SpectreBustersあるいはLinuxにおけるSpectre対策
 
Fortran tutorial
Fortran tutorialFortran tutorial
Fortran tutorial
 
Coq Tutorial
Coq TutorialCoq Tutorial
Coq Tutorial
 
Software Development for Space-group Analysis: Magnetic Space Group and Irred...
Software Development for Space-group Analysis: Magnetic Space Group and Irred...Software Development for Space-group Analysis: Magnetic Space Group and Irred...
Software Development for Space-group Analysis: Magnetic Space Group and Irred...
 
LIGO - General Information
LIGO - General InformationLIGO - General Information
LIGO - General Information
 
Gravitational waves
Gravitational wavesGravitational waves
Gravitational waves
 
Quantum entanglement
Quantum entanglementQuantum entanglement
Quantum entanglement
 
Lie-Trotter-Suzuki分解、特にフラクタル分解について
Lie-Trotter-Suzuki分解、特にフラクタル分解についてLie-Trotter-Suzuki分解、特にフラクタル分解について
Lie-Trotter-Suzuki分解、特にフラクタル分解について
 
Quantum entanglement (1).pptx
Quantum entanglement (1).pptxQuantum entanglement (1).pptx
Quantum entanglement (1).pptx
 
龍騰[掌握]數學A複習講義
龍騰[掌握]數學A複習講義龍騰[掌握]數學A複習講義
龍騰[掌握]數學A複習講義
 
qubitによる波動関数の虚時間発展のシミュレーション: a review
qubitによる波動関数の虚時間発展のシミュレーション: a reviewqubitによる波動関数の虚時間発展のシミュレーション: a review
qubitによる波動関数の虚時間発展のシミュレーション: a review
 

Similar to Fortran Programming Language in short with fortran codes.pdf

Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionSvetlin Nakov
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxskilljiolms
 
Perspective in Informatics 3 - Assignment 2 - Answer Sheet
Perspective in Informatics 3 - Assignment 2 - Answer SheetPerspective in Informatics 3 - Assignment 2 - Answer Sheet
Perspective in Informatics 3 - Assignment 2 - Answer SheetHoang Nguyen Phong
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.pptcpphtp4_PPT_03.ppt
cpphtp4_PPT_03.pptSuleman Khan
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoreambikavenkatesh2
 
Fuzzy Logic And Application Jntu Model Paper{Www.Studentyogi.Com}
Fuzzy Logic And Application Jntu Model Paper{Www.Studentyogi.Com}Fuzzy Logic And Application Jntu Model Paper{Www.Studentyogi.Com}
Fuzzy Logic And Application Jntu Model Paper{Www.Studentyogi.Com}guest3f9c6b
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
 
Lecture 3 and 4.pptx
Lecture 3 and 4.pptxLecture 3 and 4.pptx
Lecture 3 and 4.pptxMAHAMASADIK
 
Application of Fuzzy Algebra in Coding Theory
Application of Fuzzy Algebra in Coding TheoryApplication of Fuzzy Algebra in Coding Theory
Application of Fuzzy Algebra in Coding TheoryIJERA Editor
 
Application of Fuzzy Algebra in Coding Theory
Application of Fuzzy Algebra in Coding TheoryApplication of Fuzzy Algebra in Coding Theory
Application of Fuzzy Algebra in Coding TheoryIJERA Editor
 

Similar to Fortran Programming Language in short with fortran codes.pdf (20)

C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 
CPPDS Slide.pdf
CPPDS Slide.pdfCPPDS Slide.pdf
CPPDS Slide.pdf
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptx
 
Session2
Session2Session2
Session2
 
Perspective in Informatics 3 - Assignment 2 - Answer Sheet
Perspective in Informatics 3 - Assignment 2 - Answer SheetPerspective in Informatics 3 - Assignment 2 - Answer Sheet
Perspective in Informatics 3 - Assignment 2 - Answer Sheet
 
Compiler notes--unit-iii
Compiler notes--unit-iiiCompiler notes--unit-iii
Compiler notes--unit-iii
 
1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.pptcpphtp4_PPT_03.ppt
cpphtp4_PPT_03.ppt
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
Fuzzy Logic And Application Jntu Model Paper{Www.Studentyogi.Com}
Fuzzy Logic And Application Jntu Model Paper{Www.Studentyogi.Com}Fuzzy Logic And Application Jntu Model Paper{Www.Studentyogi.Com}
Fuzzy Logic And Application Jntu Model Paper{Www.Studentyogi.Com}
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Sample paper i.p
Sample paper i.pSample paper i.p
Sample paper i.p
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
 
Lecture 3 and 4.pptx
Lecture 3 and 4.pptxLecture 3 and 4.pptx
Lecture 3 and 4.pptx
 
Application of Fuzzy Algebra in Coding Theory
Application of Fuzzy Algebra in Coding TheoryApplication of Fuzzy Algebra in Coding Theory
Application of Fuzzy Algebra in Coding Theory
 
Application of Fuzzy Algebra in Coding Theory
Application of Fuzzy Algebra in Coding TheoryApplication of Fuzzy Algebra in Coding Theory
Application of Fuzzy Algebra in Coding Theory
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 

Fortran Programming Language in short with fortran codes.pdf

  • 1. KHULNA UNIVERSITY An assignment on Simulation Lab-I (Fortran Programming Language) 5th year 1st term COURSE NO: 0541 12 Math-5114 COURSE TITLE: Simulation Lab-I Submitted To: Prof. Dr. Munnujahan Ara Head of the depertment, Mathematics Discipline & Dr. Ariful Islam Professor, Mathematics Discipline Khulna University, Khulna-9208. Submitted By: Student Name: Md. Al-Amin Student ID: MSc-231206 Mathematics Discipline, Khulna University, Khulna-9208. Date of Submission: 12th February,2023
  • 2. Question no Question Name Page interval 01 List the library functions (at least 30) in a table for Fortran programming language. Also give a few examples in how to use them in computer code. 01-03 02 Describe data types and different constants in fortran with examples. 04-06 03 Describe assignment statements, expressions and hierarchy of operations in Fortran with proper examples. 06-07 04 Describe the BLOCK IF structure with its syntax. Write two Fortran codes by using the BLOCK IF structure. 08-09 05 Describe DO LOOP and NESTED DO LOOP with its syntax. Write two Fortran codes to explain the DO LOOP and NESTED DO LOOP. 10-12 06 Explain unconditional transfer with examples. Write two different Fortran programs as an example of unconditional transfer. 13-15 07 Describe arrays and subprogram with examples. Illustrate it graphically where applicable. Develop two different Fortran codes as an example of arrays and subprogram. 15-17 08 Describe SELECT case constructs. Give two examples by developing Fortran programs related to the SELECT case construct. 18-21 09 What is function subprogram? Describe the syntax of function subprogram. Give two different Fortran codes as an example of function subprogram. 21-23 Table of contents
  • 3. 10 What is subroutine subprogram? Explain subroutine subprogram graphically with examples. 24-27 11 Explain the common statement with its syntax. Use graphical notations where applicable. Also write a Fortran program to illustrate the common statement. 28-29 12 Describe File processing with examples. 30-32
  • 4. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 1 Fortran is a computer programming language that is extensively used in numerical, scientific computing. While except the scientific community, Fortran has declined in popularity over the years, it still has a strong user base with scientific programmers, and is also used in organizations such as weather forecasters, financial trading, and in engineering simulations. Fortran programs can be highly optimized to run-on high-performance computers, and in general the language is suited to producing code where performance is important. Fortran is a compiled language, or more specifically it is compiled ahead-of- time. In other words, you must perform a special step called compilation of your written code before you are able to run it on a computer. This is where Fortran differs to interpreted languages such as Python and R which run through an interpreter which executes the instructions directly, but at the cost of compute speed. We use a function by placing its name (followed by its arguments) in an expression. We must take great care to match the type, number and order of arguments required for the function. We summarize the most common functions below. Serial Name Description Argument Result Example 1. abs(x) absolute value integer real double integer real double j=abs(-15) x=abs(-2.66) z=abs(-0.1d06) 2. sqrt(x) square root real double real double x=sqrt(6.2) x=sqrt(0.17d1) 3. mod(i,j) integer reminder of i/j integer integer j=mod(22,3) 4. int(x) converts to integer real double integer integer j=int(2.6666) j=int(0.266d01) 5. float(i) converts to real integer double real real x=float(2) x=float(0.6d01) 6. floor(x) floor value integer real integer real x=floor(2.6) x=floor(2.2) Question 01: List the library functions (at least 30) in a table for Fortran programming language. Also give a few examples in how to use them in computer code.
  • 5. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 2 7. ceiling(x) ceiling value integer real integer real x= ceiling(2.6) x= ceiling(2.2) 8. exp(x) exponential real double real double x=exp(2.0) x=exp(1.0d0) 9. nint(x) round to nearest integer real double integer integer j=nint(2.66) j=nint(0.6d02) 10. real(i) convert to real integer double real real x=real(2) x=real(0.26d02) 11. sin(x) sine real(rad) double(rad) real double x=sin(0.6202) x=sin(0.62d02) 12. cos(x) cosine real(rad) double real double x=cos(1.047) x=cos(1.047d0) 13. tan(x) tangent real(rad) double real double x=tan(0.622) x=tan(0.622d0) 14. acos(x) arccosine real double real(rad) double(rad) x=acos(0.6) x=acos(0.6d0) 15. asin(x) arcsine real double real(rad) double(rad) x=asin(0.6) x=asin(0.6d0) 16. alog(x) natural logarithm real double real double x=alog(2.61) x=alog(2.6d1) 17. alog10(x) logarithm base 10 real double real double x=alog10(2.61) x=alog10(2.6d1) 18. atan(x) arctangent real double real(rad) double(rad) x=atan(1.0) x=atan(1.0d0) 19. dble(x) Converts to double integer real double double x=dble(3) x=dble(3.0) 20. amax(..) Returns lagest value integer real double integer real double i=amax(5,2,6,7) x=amax(0.2,5.6) x=amax(1d0,3d3 )
  • 6. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 3 21. amin(..) returns smallest value integer real double integer real double i=amin(5,-2,6,7) x=amin(0.2,5.6) x=amin(1d0,3d3) 22. fraction(x) fractional part of a number real real x= fraction(6.22) 23. huge (x) largest number of the model real real x=huge (1.66) 24. maxexpone nt(x) maximum exponent integer real integer real x=maxexponent( 1.6) 25. tiny (x) smallest positive number integer real integer real x=tiny (10.6) 26. digits (x) significant digits integer real integer real x=digits (1.22) 27. cosh (x) hyperbolic cosine integer real integer real x=cosh (1.0) 28. dim (x, y) it returns the positive difference of x and y. integer real integer real z=dim (11, -10) z=dim (11, -10) 29. dble (x) converts x to a double precision real number integer real integer real z=dble (10.5) z=dble (10.5) 30. modulo(a,p) returns the remainder of a on division by p integer real integer real z=modulo (10, 3) z=modulo (10, 3)
  • 7. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 4 The smallest common grouping of bits is called a byte. A byte is a group of 8 bits. Fortran 77 contains six intrinsic data types that are built automatically into the language. These are divided into two categories: numerical and nonnumerical. Data types 1. Integer constant The integer data type consists of the positive, negative and zero. The range of values that can be represented on a computer depends specifically on the computer. However, a typical range is from -232-1 to 232-1 -1 for a 32-bit computer. Question 02: Describe data types and different constants in fortran with examples. Numerical Nonnumerical 3. Integer 4. Real 5. Double precision 6. Complex 1. Character 2. Logical Valid examples -666 10 +10 111 111 111 Invalid examples and reason 66/6 (no fraction) 10.0 (no decimal points) 111,111,111 (no commas)
  • 8. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 5 2. Real constants Real number stores the floating point numbers such as 2.0, 3.1416 etc. real numbers are stored in the computer as two components: a mantissa ranging between 0.1 and 1.0 also an exponent that indicates the appropriate power of 10. Real constants are those that we think of as fractional numbers which may be positive or negative and always have a decimal point. Real constant can also be used with scientific notation. 3. Double precision constants If more than 7 digits of accuracy are required, then we can use a double precision constant, which is accurate to 14 to 16 decimal places, depending on machine. Double precision is simple to use. Instead of using E for the exponent, double precision simply substitutes the letter D. 4. Complex constants This is used for storing complex numbers. A complex number has two parts, the real part and imaginary part. Valid examples -6.6 0.0026 +2.2 122 62.0 1E2 0.0E0 0.1E-24 Invalid examples and reason 66 (requires a decimal point) $10.0 (only numbers permitted) 111,111,111 (no commas) 0.1E-6.5 (exponent must be integer) 0.1E-126 (value too small on most computer) 0.1E+126 (value too big on most computer) Valid examples 0.6D6 0.0D0 0.23D-94 122 62.0 Invalid examples and reason 0.123E23 (Not double precision) 2.163E26 (Not double precision) 16.3E26 (Not double precision) Valid examples (1.23, 6.2) (+1.2E3, 0.0) 3.0C-5.0i Invalid examples and reason (1, 2) (integer not allowed) (1.2D3, 3.4) (both not match in precision) (1, 2.1) (integer not allowed)
  • 9. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 6 5. Character constants The character data type consists of characters and symbols. Letters of the alphabet (upper or lower case) Numbers 0 to 9 Special character + - * / ( ) . {} [ ] ! @ # ^ , = ‘’ $ Blank space The most important coding system is ASCII. 6. Logical constants There are only two logical values: .true. and .false. Assignment statement: The assignment statement is the primary means of storing data in variables. As the name assignment statement implies, we are telling the computer to assign a value to a given variable. The general form of the assignment statement is: Target  Value from an expression Invalid examples and reason True (requires periods) .F. (must spell out complete word) .T . (must spell out complete word) Question 03: Describe assignment statements, expressions and hierarchy of operations in Fortran with proper examples. Valid examples ‘Imam’ ‘Ar’’salan’ ‘231206’ Invalid examples and reason Imam (missing quote marks) “Imam” (must be single quotes) ‘I > math’ (illegal character >) Valid examples .True. .False. .false.
  • 10. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 7 The interpretation of this statement is “The target receives a value obtained from the expression”. The way this is implemented in Fortran is: Variable = Value from an expression The expression on the right hand side (RHS) of the equal sign can be one of several types as discussed below. Expression Type of Expression Result = 3.72 CGPA = Result Y = sqrt(CGPA) Constant assigned to the variable Result The value of the variable Result assigned to CGPA Evaluate the square root of CGPA Expressions and hierarchy of operations: All of the examples of expressions have been simple ones. They’ve consisted simply of multiplication, or addition and subtraction. There are only five basic arithmetic operations possible with Fortran. They are addition, subtraction, multiplication, division and exponentiation as presented in the following table: Priority Algebraic symbol Fortran symbol Meaning 1 2 3 3 4 4 (…) 𝐴𝑏  ÷ + - (…) ** * / + - Parentheses Exponentiation Multiplication Division Addition Subtraction In order to create mathematical expressions, we must use the symbols listed in the table on a single text line entered into our program. While algebra permits the use of multiple line expressions, Fortran requires us to place the expression on a single line. For all of the operators with equivalent position within the hierarchy (expect **), evaluation is from left to right. For exponentiation, the direction is from right to left. For example 6.0/2.0*5.0 gives 15.0, since the division is done first and then the multiplication.
  • 11. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 8 The IF statement is useful when we have only a single instruction to execute after the test condition is evaluated. But when we have more than one instruction, we need a different structure. In Fortran this is BLOCK IF structure. As its name implies, it consists of blocks of instruction will execute when the test condition is false. The general form of the BLOCK IF construct is as follows: IF (Test condition) THEN Block of statement if test condition is true ELSE Block of statements if test condition is false END IF Here it is noticeable that, on the same line as the THEN, ELSE, or END IF key words. Example: 01 !input marks and print the grade obtained using else if PROGRAM GRADE PRINT*,'input marks' READ*,MARKS IF(MARKS>=80 .AND. MARKS<=100) THEN PRINT*,'GRADE A+' ELSE IF(MARKS>=75 .AND. MARKS<=79) THEN PRINT*,'GRADE A' ELSE IF(MARKS>=70 .AND. MARKS<=74) THEN PRINT*,'GRADE A-' ELSE IF(MARKS>=65 .AND. MARKS<=69) THEN PRINT*,'GRADE B+' ELSE IF(MARKS>=60 .AND. MARKS<=64) THEN PRINT*,'GRADE B' ELSE IF(MARKS>=55 .AND. MARKS<=59) THEN PRINT*,'GRADE B-' ELSE IF(MARKS>=50 .AND. MARKS<=54) THEN PRINT*,'GRADE C+' ELSE IF(MARKS>=45 .AND. MARKS<=49) THEN PRINT*,'GRADE C' ELSE IF(MARKS>=40 .AND. MARKS<=44) THEN PRINT*,'GRADE D' ELSE PRINT*,'GRADE F' END IF END PROGRAM GRADE Question 04: Describe the BLOCK IF structure with its syntax. Write two Fortran codes by using the BLOCK IF structure.
  • 12. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 9 Example: 02 !largest and smallest value amoung 3 values PROGRAM NAME implicit none real a,b,c print*,'enter the values of a,b and c' read*,a,b,c if(a>b .AND. a>c) then print*,'the largest value a is ',a else if(b>a .AND. b>c) then print*,'the largest value b is ',b else print*,'the largest value c is ',c end if if(a<b .AND. a<c) then print*,'the Smallest value a is ',a else if(b<a .AND. b<c) then print*,'the smallest value b is ',b else print*,'the smallest value c is ',c end if end program
  • 13. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 10 Do loop: The do loop construct enables a statement, or a series of statements, to be carried out iteratively, while a given condition is true. The general form of the do loop is do var = start, stop [,step] ! statement(s) … end do Where, ▪ the loop variable var should be an integer ▪ start is initial value ▪ stop is the final value ▪ step is the increment, if this is omitted, then the variable var is increased by unity Example: 01 !max value amount given values PROGRAM NAME implicit none integer N,i real max,a print*,'How many numbers you want to give as input?' read*,N print*,'Enter values' max=0 do i=1,N,1 read*,a if(max < a) then max=a end if end do print*,'The maximum value is' Print*,max end program Question 05: Describe DO LOOP and NESTED DO LOOP with its syntax. Write two Fortran codes to explain the DO LOOP and NESTED DO LOOP.
  • 14. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 11 Nested do loop: Just like an IF-THEN-ELSE-END IF can contain another IF-THEN- ELSE-END IF (see nested IF for the details), a DO-loop can contain other DO-loops in its body. The body of the contained DO-loop, usually referred to as the nested DO-loop, must be completely inside the containing DO-loop. Note further that an EXIT statement only brings the control out of the inner-most DO-loop that contains the EXIT statement. Suppose we have the following nested DO loops: DO statements-1 DO statement-2 END DO statement-3 END DO Each iteration of the outer DO starts with statements-1. When the control reaches the inner DO, statements-2 is executed until some condition of the inner DO brings the control out of it. Then, statements-3 is executed and this completes one iteration. Any EXIT in the inner DO brings the control out of the inner DO to the first statement in statement-3.
  • 15. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 12 Example: 02 !SUM OF THE SERIES 1+2+3+4+...+N using nested do PROGRAM NUMBER implicit none integer:: i,j,sum,N PRINT*,'input the value of N' READ*,N do i=1,N SUM=0 DO j=1,i SUM=SUM+j END DO end do PRINT*,'THE ANS OF SUM OF THIS SERIES IS',SUM END PROGRAM NUMBER
  • 16. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 13 Unconditional transfer: The unconditional transfer statement, or GO TO statement, is the simplest transfer operation. It provides a means by which control transfer to another line in the program. The line to receive the control must be labeled using a statement label. The general form of the GO TO statement is: GO TO statement label When an unconditional GO TO is encountered, control is immediately transferred to the executable statement labelled with the label. Whilst it is sometimes necessary to use unconditional go to statements in a program, they should be used sparingly lest unreadable 'spaghetti' code result. A GO TO statement may be used to transfer control out of a block if or do loop but not in to them. The unconditional GO TO statement is often used in conjunction with logical or block if statements to construct loops when a simple do loop is not appropriate. 10 CONTINUE WRITE(*,*)'Enter a positive value' READ(*,*)A IF (A .LE. 0.0) GO TO 10 The statement labelled 10 is a continue statement which is often used at the beginning or end of a loop structure. This program fragment executes the continue statement (which does nothing) and then prints out the statement enter a positive value. The program then reads in a value from the standard input device and stores it in the variable a. At this point a is tested to see if it is positive. If it is, then control passes to the next executable statement, but if it isn't, then the GO TO 10 statement is executed and the program returns to the continue statement. The program then goes through the write and read statements again and tests the new value of a. The program will not break out of this loop until a is positive. The indentation of the loop body makes the structure of the program that much more readable. Question 06: Explain unconditional transfer with examples. Write two different Fortran programs as an example of unconditional transfer.
  • 17. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 14 Example:- 01 (Using parallel studio XE 2010) program MAIN integer a goto 11 10 write(*,'("Here we go again")') ! lots of lines of your code 11 write(*,'("Enter 1 to go around again:")') read(*,*) a if (a.eq.1) goto 10 end Example:- 02 program computed integer day write(*,*)'Enter the day of a week' read(*,*)day goto (20,10,12,13,15,16,18),day 10 write(*,*)'The day is Sunday' goto 25 12 write(*,*)'The day is Monday' goto 25 13 write(*,*)'The day is Tuesday' goto 25 15 write(*,*)'The day is Wednesday' goto 25 16 write(*,*)'The day is Thursday' goto 25 18 write(*,*)'The day is Friday' goto 25 20 write(*,*)'The day is Saturday' 25 stop end program computed
  • 18. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 15 Array: An array is a group of variables denoted by a single name having same type. That means, an array of strings is a collection of strings. Where, an ordinary variable holds only a single value. And an array variable holds multiple values. If an array is not initialized, the contents of the array elements are undefined. Suppose, array j is an example of uninitialized array. integer, dimension(10)::j write(*,*) j(1) There are three techniques to initialized the elements in an array:- 1. Using assignment statement real, dimension(10)::a do i=1,10 a(i)=0.0 end do 2. Using real statement real, dimension(10)::a do i=1,10 read*,a(i) end do 3. Initializing array in the type declaration statement. real, dimension(3)::a=(/1,2,3/) Question 07: Describe arrays and subprogram with examples. Illustrate it graphically where applicable. Develop two different Fortran codes as an example of arrays and subprogram.
  • 19. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 16 Arrays and Subprograms: Here our main focus on passing single valued variables to subprograms. But we can pass arrays also if we declare the arrays in both modules. While this sounds like a duplication of effort, recall that subprograms are standalone modules. Thus, if we are going to use an array in the module we must declare it in the main and subprogram modules where they are used. Example:- 01 !Multiplication of given numbers program name implicit none integer,dimension(100)::a integer::n,i real::ave,sum Print*,'Enter the how many numbers do you want to multiplication:' read*,n print*,'Please Enter the number:' do i=1,n read*,a(i) end do call mark(a,n,sum) print*,'Multiplication of given numbers is',sum end subroutine mark(a1,n1,sum1) integer,dimension(100)::a1 integer::n1,i sum1=1.0 do i=1,n1 sum1=sum1*a1(i) end do return stop end
  • 20. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 17 Example:- 02 !Sum of given numbers program name implicit none integer,dimension(100)::a integer::n,i real::ave,sum Print*,'Enter the how many numbers do you want to sum:' read*,n print*,'Please Enter numbers:' do i=1,n read*,a(i) end do call mark(a,n,sum) print*,'Sum of given numbers is',sum end subroutine mark(a1,n1,sum1) integer,dimension(100)::a1 integer::n1,i sum1=0.0 do i=1,n1 sum1=sum1+a1(i) end do return stop end
  • 21. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 18 The select case provides a means of selecting an action (which can be a block of statements) by comparing the value of an expression against a list of values. The general form of the select case construct is: SELECT CASE (expression) CASE(selector list 1) Block 1 CASE(selector list 2) Block 2 … CASE DEFAULT Block n END SELECT As with the previous block structures, there are key words to mark the beginning and end of the structure- the SELECT CASE and END SELECT statements respectively. In between are a series of CASES, only one of which is executed based on the value of the expression in the SELECT CASE statement. The expression is a scalar (single-valued) expression which can have integer, character, or logical data type. Once this expression is evaluated, its value is compared with the values contained in the selector lists until a match is found. The list of instructions that follow this CASE is then executed. If the expression in the CASE SELECT expression has match among the various selector lists, then the instructions in the CASE DEFAULT are executed. The CASE DEFAULT statement is optional. The selector list for each of the CASES can be a single value, a list, or a range of values specified by low-value: high-value, or a list of values which include ranges. This will become me obvious in the following examples. Also, the selector lists must not overlap in values. The type of the expression and selectors must match. Thus, if the expression is a character string, then the selectors must also be character strings. Lengths of strings do not necessarily have to match. If the expression is of type integer or logical, then the selectors also be of the same type. SELECT CASE construct determines which block is to be executed by checking if the expression equals any of the values defined by the selectors. If the equality is true, then that block is executed and control passes to the END SELECT command. Question 08: Describe SELECT case constructs. Give two examples by developing Fortran programs related to the SELECT case construct.
  • 22. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 19 Example:- 01 !Input N numbers and how many operations can be done?Show all the operation. PROGRAM NAME implicit none real N,A,sum integer i,option character press print*,'How many numbers you want to give as input?' read*,N 5 print*,'What operation do you want to do?' print*,'press 1 for addition' print*,'press 2 for multiplication' read*,option select case(option) case(1) i=0 sum=0 print*,'Please input the N numbers' 10 read*,A i=i+1 sum=A+sum if(i .ne. N) goto 10 Print*,'Addition of the input numbers= ',sum case(2) i=0 sum=1 print*,'Please input the N numbers' 1 read*,A i=i+1 sum=A*sum if(i .ne. N) goto 1 Print*,'Multiplication of the input numbers= ',sum case default print*,'wrong input' end select stop END PROGRAM
  • 23. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 20 Example:- 02 !Input 3 numbers and use case case. PROGRAM NAME implicit none real a,b,c integer i,option character press 5 print*,'What operation do you want to do?' print*,'press 1 for Largest value' print*,'press 2 for Smallest value' read*,option select case(option) case(1) print*,'Enter the values of a,b and c' 10 read*,a,b,c if(a>b .AND. a>c) then print*,'The largest value a is ',a else if(b>a .AND. b>c) then print*,'The largest value b is ',b else print*,'The largest value c is ',c end if case(2) print*,'Enter the values of a,b and c' 1 read*,a,b,c if(a<b .AND. a<c) then print*,'The Smallest value a is ',a else if(b<a .AND. b<c) then print*,'The smallest value b is ',b else print*,'The smallest value c is ',c end if case default print*,'wrong input' end select stop END PROGRAM
  • 24. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 21 The simplest type of subprogram is the function subprogram whose purpose is to calculate a single numerical answer and return the result. Function subprogram receive one or more values from calling program and can return only one value to the calling program. The general form of function subprogram is given below: Type FUNCTION name (a1, a2, …, ap) … … Name=expression … … Return End The first line of the subprogram states that this is a function and gives it a name, which is the same as the one to be used in the main program calling statement. This name is also used as a variable within the subprogram to which the desired value will be assigned. Because the function name is also a variable inside the function, the type of the variable may need to be declared. That is why there is a typing option at the beginning of the function statement. Following the name is an optional list of variables that the function needs for the calculation. Question 09: What is function subprogram? Describe the syntax of function subprogram. Give two different Fortran codes as an example of function subprogram.
  • 25. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 22 Example:01 !factorial using sub program sub function program name print*,'enter the number' read*,n print*,'factorial of',n,' is',ifact(n) end function ifact(m) ifact=1 do i=1,m ifact=ifact*i end do m=445456569 return stop end
  • 26. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 23 Example:02 !find sum and average using sub program sub function program name implicit none integer,dimension(100)::a integer::n,i real::ave,sum Print*,'Enter the how many numbers do you want to sum:' read*,n print*,'Please Enter the number:' do i=1,n read*,a(i) end do call averagemark(a,n,ave,sum) print*,'Sum of given numbers is',sum print*,'Average of given numbers is',ave end function averagemark(a1,n1,ave1,sum1) integer,dimension(100)::a1 integer::n1,i sum1=0.0 do i=1,n1 sum1=sum1+a1(i) end do ave1=sum1/n1 return stop end
  • 27. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 24 The second type of subprogram is the subroutine. Like the function, it stands outside the main program and uses local variables. Received one or more values from the calling program and can return several values to the calling program. As with functions, the use of a subroutine requires a three-step process to ▪ call the subroutine from the main program ▪ pass data to the subroutine ▪ set up the subroutine to receive the passed data, process it, and return the results The procedure for calling a subroutine is a little different from that for a function because of the larger amount of data returned. We used functions when a single numerical answer was sufficient. But with subroutines, we can return any amount of data. Therefore, the subroutine is more versatile. With subroutines, we pass data to and from the subroutine with the calling statement: CALL subroutinename (variablel, variable2, . . ., variableN) where subroutinename is the name of the specific subroutine that you want to use and variablel...variableN is a list of variables passing back and forth between the main and the subroutine. These variables are two-way variables. They may pass data to the subroutine or they may receive results, depending upon the context. The corresponding statements which set up the subroutine are: SUBROUTINE subroutinename (variable1, variable2, . . . , variableN) … … RETURN END The identifier subroutinename must be identical with the one in the calling statement and must follow the standard rules for any variable name. The argument list in the calling Question 10: What is subroutine subprogram? Explain subroutine subprogram graphically with examples.
  • 28. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 25 statement and in the subroutine statement must have the same number of variables, and each must agree in type with its counterpart. They need not have the same variable names. Thus: … CALL ADD ( X , Y, Z, I, SUM ) … SUBROUTINE ADD ( A, B, C, L, TOT ) … RETURN END In this example, the first variable in the subroutine argument list A receives the value of the first variable in the calling argument list X. Similarly, B receives the value of Y, C receives the value of Z, and so forth. Also, the variables sending and receiving the data must match in type. Thus, if X is real, A must be real, and if I is an integer, then L must also be an integer. The variables in the argument lists can either send or receive data. Usually, this will be obvious from the context of the problem. In the example given, X, Y, Z, and I are sending data to the subroutine, while SUM is the variable where the returned answer is stored. But each variable is also a two-way variable. Thus, we may use X to send data down, but if the subprogram modifies the corresponding variable A, then X will change also.
  • 29. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 26 Example :01 !maximum and minimum value using subroutine sub program program name implicit none real,dimension(100)::a integer::n,i real::ave,sum,max,min Print*,'Enter the how many numbers do you want to take:' read*,n print*,'Please Enter the number:' do i=1,n read*,a(i) end do call mark(a,n,max,min) print*,'Maximum of given numbers is',max print*,'Minimum of given numbers is',min end subroutine mark(a1,n1,ma,mi) real,dimension(100)::a1 integer::n1,i real::ma,mi ma=a1(1) mi=a1(1) do i=1,n1 if(ma<a1(i)) ma=a1(i) if(mi>a1(i)) mi=a1(i) end do return stop end
  • 30. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 27 Example:- 02 !multiplication value using subroutine sub program program name implicit none integer,dimension(100)::a integer::n,i real::ave,sum Print*,'Enter the how many numbers do you want to multiplication:' read*,n print*,'Please Enter the number:' do i=1,n read*,a(i) end do call mark(a,n,sum) print*,'Multiplication of given numbers is',sum end subroutine mark(a1,n1,sum1) integer,dimension(100)::a1 integer::n1,i sum1=1.0 do i=1,n1 sum1=sum1*a1(i) end do return stop end
  • 31. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 28 Fortran 77 has no global variables, i.e. variables that are shared among several program units (subroutines). The only way to pass information between subroutines we have seen so far is to use the subroutine parameter list. Sometimes this is inconvenient, e.g., when many subroutines share a large set of parameters. In such cases one can use a common block. This is a way to specify that certain variables should be shared among certain subroutines. But in general, the use of common blocks should be minimized. Suppose you have two parameters alpha and beta that many of your subroutines need. The following example shows how it can be done using common blocks. program main some declarations real alpha, beta common /coeff/ alpha, beta statements stop end subroutine sub1 (some arguments) declarations of arguments real alpha, beta common /coeff/ alpha, beta statements return end subroutine sub2 (some arguments) declarations of arguments real alpha, beta common /coeff/ alpha, beta statements return end Here we define a common block with the name coeff. The contents of the common block are the two variables alpha and beta. A common block can contain as many variables as you like. They do not need to all have the same type. Every subroutine that wants to use any of the variables in the common block has to declare the whole block. Question 11: Explain the common statement with its syntax. Use graphical notations where applicable. Also write a Fortran program to illustrate the common statement.
  • 32. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 29 Note that in this example we could easily have avoided common blocks by passing alpha and beta as parameters (arguments). A good rule is to try to avoid common blocks if possible. However, there are a few cases where there is no other solution. COMMON / name / list-of-variables Here, we should know that ▪ The common statement should appear together with the variable declarations, before the executable statements. ▪ Different common blocks must have different names (just like variables). ▪ A variable cannot belong to more than one common block. ▪ The variables in a common block do not need to have the same names each place they occur (although it is a good idea to do so), but they must be listed in the same order and have the same type and size.
  • 33. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 30 A file is a list of records, each of which is a list of values or characters. A FORTRAN program can read from and write to the files stored on an external storage device. Instead of the usual READ statement, file processing employs a more general form of READ statement. Also, WRITE command replaces the PRINT command. READ (cilist) input_list WRITE (cilist) output_list cilist is a list of specifiers pointing to the file, its format, and other processing details with commas in between. Some of the specifiers are UNIT, FMT, ERR, and END. In cilist, the order of the specifiers does not matter. The value of the UNIT specifier gives a unit identifier specific to a file. For instance, each file is associated with a unit number, which is an integer between 1 to 99. Integers 5 & 6 specifies standard input & output respectively. Asterisk (*) refers to the keyboard for input and screen for the output. The value of the FORMAT specifier FMT is the label of FORMAT statement. READ (UNIT = 5, FMT = 100) X, Y, Z or READ (FMT = 100, UNIT = 5) X, Y, Z Here, order of the specifiers does not matter. If one requires reading the content of the file as it is i.e without any formatting, write unit specifier in the first place without the keyword UNIT and in place of FORMAT specifier place an asterisk (*) symbol. Open/Create the file: A unit identifier is assigned to the files other than the standard I/O files. An OPEN statement calls the file with its name and labels it with a unit identifier. OPEN (open_list) open_list is a list of specifiers of the form keyword= value with commas in between. It includes two specifiers: UNIT and FILE. The value of the UNIT is the identifier of the file and the value of FILE is the name of the file. If no such file exists, a new file appears in York directory with this name. For example: Question 12: Describe File processing with examples.
  • 34. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 31 OPEN ( UNIT = 8, FILE = 'MYFILE.DAT' ) Close the file: Close command closes a single or several files simultaneously. For example: First statement below close a single file with unit number 6. The second command three files simultaneously. However, it is not necessary to close the files using CLOSE command. STOP or END statements close them automatically. CLOSE (6) CLOSE (1,2,3) Here is a simple example of how to write to a data file named EXPER.DAT: OPEN (UNIT=2, FILE='EXPER. DAT', STATUS=' NEW') WRITE (2,*) DIST, TIME, VELOC CLOSE (2) The first statement, OPEN(...), contains all the information needed to set up the file with the name 'EXPER.DAT'. We will call this for simplicity the UNIT. This unit number comes in handy since it is easier to type the single number (2) than to use the full file name in every I/O statement. Thus, in subsequent statements when we refer to 2, we are referring to its equivalent file name 'EXPER.DAT'. The final listing in the OPEN statement shows the status of the file. As we will see shortly, it will be either 'NEW', 'OLD', 'SCRATCH', or 'UNKNOWN' indicating whether the file needs to be created, already exists, is only temporary, or unknown respectively. The second statement, WRITE(2,*) list, is used to direct the output to the desired file. Remember that we have given the file the short name of 2. Thus, the WRITE statement tells the computer to send the output to the unit that has the file name 'EXPER.DAT' and associated with UNIT=2. The final statement of the example, CLOSE(...), simply closes the file after we finish with it. A similar set of statements can be used to read from a data file. The primary difference from the output statement is that the file must already exist to read from it. Therefore, its STATUS will be 'OLD'. Here is a simple example of how to read a data file: we will read data from a file named 'NOBEL.DAT' and assign the data to the variables WEIGHT, MASS, and DENSIT. Notice that the file must already exist in order to read from it.
  • 35. A n A s s i g n m e n t o n F o r t r a n P r o g r a m m i n g P a g e | 32 OPEN (UNIT=3, FILE='NOBEL. DAT', STATUS=' OLD') READ (3, *) WEIGHT, MASS, DENSIT CLOSE (3) Notice that the READ statement goes to unit #3, which is the shorthand notation for the file 'NOBEL.DAT'. Also note that the status of the file is 'OLD', which indicates that it is a valid file for reading. If the status had not been 'OLD', a syntax error would have resulted. Example: program fileprocess implicit none real, dimension(10) :: x, y real, dimension(10) :: a, b integer :: i ! data do i = 1,10 x(i) = i * 0.1 y(i) = sin(x(i)) * (1-cos(x(i)/3.0)) end do ! output data into a file open(1, file = 'data1.dat', status='new') do i = 1,10 write(1,*) x(i), y(i) end do close(1) ! opening the file for reading open (2, file = 'data1.dat', status = 'old') do i = 1,10 read(2,*) a(i), b(i) end do close(2) do i = 1,10 write(*,*) a(i), b(i) end do end program fileprocess