0% found this document useful (0 votes)
8 views

Fortran Tutorials2 (1)

Uploaded by

22ipmp13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Fortran Tutorials2 (1)

Uploaded by

22ipmp13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 231

Fortran tutorials

Fortran - Introduction

Fortran character set

No of symbols Type Values


26 Uppercase letters A-Z
26 Lowercase letters A-z
10 Digits 0-9
01 Underscore character _
05 Arithmetic symbols +, -, *, /, **
17 Miscellaneous symbols () . = ‘ $ : ! “ % & ; < > ?
And blank space

Its case sensitive upper case and lower case can use simultaneously
Two types of statements
• Executable statements – actions the program takes when it is executed
• Non- Executable statements – provide information necessary for the proper operation of the program

The structure of the Fortran program – top to down approach


• Declaration section – a group of non-executable statements at the beginning of the program (variables)
• Execution section – consists of one or more statements describing the actions to be performed
• Termination section – statements stopping the execution and telling the compiler that the program is complete
CONSTANTS AND VARIABLES
Constants – data object that is defined before a program is executed and that does not change value during the execution of a
program
Variables - that can change value during the execution of a program
• Each variable should have unique name
• Maximum 31 characters long
• Alphabetic characters, digits underscore(_) character
• First letter should be alphabet
• Valid variable examples: distance , time, A_plus, aplha123
• Invalid variable example: 3 days, A$, This_is_a_long_variable_name

• Fortran has five intrinsic types of constant and variables


integers, real, character, logical, complex
• Fortran allows one to define their own derived data types

Valid data types examples


In-Valid data types examples
Integer real character logical
Integer real character Logical
0 1110. ‘This is a test’ .TRUE.
1,00,00 1,00,00. This is a test! TRUE
-999 -999.9 ‘‘ .FALSE.
-100. 111E3 ‘true” .FALSE
12345 1.0E-3 ‘ {*}’
1.23E2 -12.0E1.5 ‘man’s friend’
+16 123.45E20 “3.14593”
CONSTANTS AND VARIABLES

• By default, if not explicitly declared, the variables starting with the letters
I,J,K,L,M&N are assumed to be integer type

• Type declaration statements – Syntax


i. INTEGER :: var1, var2, var3,…..
ii. REAL :: var1, var2, var3,…..
iii. LOGICAL ::var1, var2, var3,…..
iv. CHARACTER (lem=n=<len>) :: var1, var2, var3,…..

• Examples
INTEGER :: count, day, month
REAL :: second, length, time
LOGICAL :: test1, test2
CHARACTER (15) :: char

• Declaring constants?
type, PARAMETER :: name=value
REAL, PARAMETER :: pi = 3.141593
Assignment statements and arithmetic calculations
• Precedence of operations in expression

• Calculations are specified in Fortran with an operator precedence


assignment statement () First
1. variable_name = expression
Unary- Second
2. i = i+1
3. = Assignment operator ** Third
• Arithmetic operators : +,-,*,/,** *,/ Fourth
a+b addition
+,- fifth
a-b substraction
a*b multiplication
a/b division Mathematical expression Fortran assignment statement
a ** b exponentiation ab+cd+𝑓𝑔
𝑒
(a*b)+(c*d)+e/f**g
• Integer arithmetic operators
𝑒
• Real arithmetic operators a(b+c)d + (𝑓)g a*(b+c)*d**(e/f)**g
• Mixed-mode arithmetic operators
a(b+c)(d+e)/fg a*(b+c)*(d+e)/fg
𝑎𝑏 a*b/(c+d**k/m+k)+a
+𝑎
𝑑𝑘
𝑐+ 𝑚 +𝑘
𝑧
𝑥𝑦+𝑛𝑝+𝑗+𝑥 ((x=y)=z/(n*p+)+x)/y+z)
+z
𝑦
Logical statements and logical calculations
• Calculations are specified in fortran with a logical
statement
1. logical_variable_name = logical expression
2. relational logic operators, combinational
Combinational logical operators:
logic operators
o .AND. Logical AND
• Relational operators:
o .OR. Logical OR
• == (or) .EQ. equal to
o .NOT. Logical NOT
• /= (or) .NE. Not equal to
o .EQV. Logical equivalence
• > (or) .GT. Greater than
o .NEQV. Logical non-equivalece
• >= (or) .GE. Greater than or equal to
• < (or) .LT. less than
Examples
• <= (or) .LE. Less than or equal to
o a .AND. b Result is true TRUE if both a and b are TRUE
o a .OR. b results id TRUE if either or both a and b are TRUE
o .NOT. a result is TRUE if a is FALSE, and FALSE is a is TRUE
o a .EQV. b Result is TRUE if a is same as b
Examples o a .NEQV. b Result is true if one of a and b is TRUE and the
• 3<4 .TRUE. other one is FALSE
• 3==4 .FALSE.
• 3>= 4 .FALSE.
• 4<=4 .TRUE.
• 3>4 .FALSE.
Character variables
• Calculations are specified in Fortran with a character statement
character_variable_name = character expression
• Examples
CHARACTER(len=8) :: a, b, c
a = ‘ABCDEFGHIJ’
b = ‘12345678’
C = a(5:7)

Input and output statements


• Input statement
An input statements reads one or more values from an input device and stores them into variables specified by the
programmer
READ (*,*) input_list
• List directed input – the types of the variables in the variable list determine the required format of the input data
• Example
INTEGER :: I,j
REAL = a
CHARACTER(len=12) :: chars
READ(*,*)i,j,a,chars
• Input data supplied are 2.3,5,3, ‘This one’
• Result 2, 5, 3.0, ‘This one’
Input and output statements
Output statement
An output statement writes one or more values to an
output device
WRITE (*,*) output_list
• List directed output- the types of the values in the
output list of the write statement determine the
format of the output data
INTEGER :; ix = 1
REAL :: theta = 3.141593
WRITE(*,*) ‘IX = ‘, ix
WRITE(*,*) ‘THETA = ‘, theta
WRITE(*,*) ‘COS(THETA) = ‘, cos(theta)
WRITE(*,*) REAL(ix), NINT(theta)

• Output
IX = i
THETA = 3.141593
COS(THETA) = -0.9999999999678646
1.0, 3
Initialization of Variables

Why initialization is important ? Consider a program


PROGRAM init
INTEGER :: i
WRITE(*,*) i The IMPLICIT NONE statement
END PROGRAM
Another very important non-executable statement is
Output? May be zero, arbitrary numbers, previous value of the variable the IMPLICIT NONE statement. When it is used, the
We don’t know! default type declaration provisions of the Fortran are
The variable i is an example of an uninitialized variable disabled

The program should be program test1


PROGRAM init IMPLICIT NONE
INTEGER :: i real :: time = 10
i=1
WRITE(*,*) i
write(*,*) 'time', time
END PROGRAM end program
READ statement can also be used to initialize variables
INTRINSIC FUNCTIONS
Besides the simple arithmetic operations, a number of useful built-in functions, known as intrinsic functions, are available
Function_name(variable_name)

Function name Function value Function name and Function value


and arguments arguments
SQRT(x) 𝑥 MOD(x)
ABS(x) |x| MAX(A,B)
IABS(x) Integer|x| MIN(A,B)
SIN(x) Sin(x) ASIN(x) Sin-1(x)
COS(x) Cos(x) ACOS(x) cos-1 (x)
TAN(x) Tan(x) ATAN(x) tan-1 (x)
EXP(x) 𝑒𝑥 SINH(x) Sinh(x)
LOG(x) Log(x)
LOG10(x) log10(x)
INT(x) The trigonometric functions expect their arguments to be in
radians (1800= *radians)
NINT(x)
Y=SIN(theta*(3.141593/180.0))
REAL(x)
Maths expression Fortran equivalent
 A1*COS(om*t+phi)/SQRT(a1**2+om**2)
cos(𝜔𝑡 + 𝜑)
𝛼 2 + 𝜔2
𝑥 LOG(SQRT(x/y*z)))
loge 𝑦𝑧

1 − 𝑒 −𝛼 𝑥 (1.-EXP(a1+SQRT(x)))/1.+EXP(-ABS(x))
1 + 𝑒 −|𝑥|
Acos2x+bcos3x A*COS(x)**2+b*COS(x)**3
Write a program to convert degrees Fahrenheit to Kelvin Write the program to find the time period of the
simple pendulum
𝑙
5 T = 2
𝑓 − 32 + 273.15 𝑔
9

program time_period
implicit none
PROGRAM temp_conver real, parameter :: pi = 3.141593, g = 9.81
IMPLICIT NONE real l, t, d, dr, x
REAL :: fahrenheit, kelvin write(*,*) "Enter the length of the simple pendulam“
WRITE(*,*) 'Enter the temperature in degrees fahrenheit’ read (*,*)l
READ(*,*) Fahrenheit t=2*pi*sqrt(l/g)
kelvin=(5.0/9.0)*(fahrenheit-32.0)+273.15 write(*,*)"The time period is", t
WRITE(*,*) fahrenheit, 'degrees Fahrenheit is', kelvin, write(*,*) "Enter the value of theta in terms of degrees:“
'kelvins’ read(*,*)d
END PROGRAM dr = d*(pi/180)
x = sin(dr)
write(*,*) " The value of theta in terms of radiance is :", dr
write(*,*) "The value of sine is:", x
Stop
end
If a and b are the two sides of the triangle, and  is the
angle included by these sides. Find the length of the
third side and area of the triangle

𝑎2 + 𝑏2 + 2𝑎𝑏𝑐𝑜𝑠𝜃

program area_triangle
implicit none
real :: a, b, c, theta, area, rad_theta
real, parameter :: pi = 3.141593
write(*,*) "Enter the value of a, b, and angle“
read(*,*) a, b, theta
rad_theta = theta*(pi/180.0)
c = SQRT(a**2+b**2-2*a*b*COS(rad_theta))
area = 0.5*a*b*SIN(rad_theta)
write(*,*) "side c is", c, 'area is', area
Stop
end
Debugging Fortran programs

• The program won’t work the first time


• A better way of learning programming is locating and eliminating BUGS – Debugging
• Syntax error: errors in Fortran statement itself
1. such as spelling errors, punctuation errors, wrong syntax
2. The compiler finds these mistakes
• Run-time error: due to illegal mathematical operations during execution
• Logical error: occurs when the program compiles and runs successfully, but produces the wrong answer
• To avoid common errors
1. Break long assignment statements
2. check the placement of parentheses
3. initialize all the variables and constants
4. be sure the functions are in the correct units
5. check the possible errors due to integer and mixed mode arithmetic
Control constructs: branches

• Till now we have written instructions run from the top to down
• Branches are Fortran statements that permit us to select and execute specific sections of code while skipping
other sections of code
• Blocked IF construct
• Logical IF construct
• IF …..THEN ……ELSE construct
• Nested IF construct
Example
IF ((b**2-4*a*c) .LT. 0) THEN
WRITE (*,*)’There are two complex roots’
END IF

Logical IF construct – Syntax


IF (logical_expr) statement
IF (a .GT. B) WRITE(*,*) ‘a is greater’

program if_statement
Implicit none

Real::a
Write(*,*) ‘Enter one number’
Read(*,*)a

If (a .gt. 0) then
Write(*,*) ‘The entered number is positive
valued’
End if
Stop
end
Blocked IF for multiple statements otherwise we
can use logical one
If we are using THEN, we should conclude with
ENDIF
IF (logical_exp1)THEN
Statement1
Statement2
….
ELSE
IF(logical expression2) THEN
Statement3
Statement4
…..
ELSE
Statement5
Statement6
……
END IF

IF ….THEN….ELSE Example

IF ((b**2-4*a*c) .LT. 0) THEN


WRITE(*,*) ‘There are two complex roots’
ELSE IF ((b**2-4*a*c) .EQ. 0) THEN
WRITE (*,*) ‘there are two identical real roots’
ELSE
WRITE(*,) ‘There are two distinct real roots’
END IF
1 2

3
Find the largest of three number
Named Block IF Construct

In Fortran, it is possible to assign a name to a • Name may be up to 31 alphanumeric characters


block IF consctruct • Name should be unique, and beginning with letter
• Names are optional pn the ELSE, ELSEIF
[name:] IF (logical_exp1) THEN statements, if used, they must be the same name
Statement1
Statement2 Nested IF construct
…..
ELSE IF(logical expression2) THEN [name] [name:] IF (logical_expr1) THEN
Statement3 …
Statement4 [name2:] IF (logical_expr2) THEN
….. ….
ELSE [name] END IF [name2]
Statement5 ..
Statement6 END IF [name1]
……
END IF[name]
Nested IF construct: example
PROGRAM named_nested_if
PROGRAM NESTED_IF ….
……. Outer: IF(test1) THEN
IF(test1) THEN ……
…….. middle: IF(test2) THEN
IF(test2) THEN ….
…….. inner: IF(test3) THEN
IF(test3) THEN ….
…… ENDIF inner
ENDIF …..
….. ENDIF middle
ENDIF ……
….. END IF outer
ENDIF
Usage of ELSEIF and nested IF constructs : EXAMPLE
Suppose that we are writing a program that reads the marks in
neumerical grade in assigns a letter grade to it according to the
following table:
95 < grade A
80 < grade  95 B
65 < grade  80 C
50 < grade  65 D
0 < grade  50 F
Write a Fortran code

There's not really a difference. The if, else if, else conditional is
actually the same as the nested one with one of the {}
enclosures removed. When you have only a single statement
within a {} enclosure, you can usually eliminate the {}.
program else_if
implicit none
real :: grade, a, b, c, d, f
write(*,*) ‘enter the marks in
numbers:’
read(*,*) grade
if (grade .gt. 100.0) then
write (*,*) ‘invalid mark’
elseif (grade .gt. 95.0) then
write (*,*) ‘the grade is A.’
elseif (grade .gt. 80.0) then
write (*,*) ‘the grade is B.’
elseif (grade .gt. 65.0) then
write (*,*) ‘the grade is C.’
elseif (grade .gt. 50.0) then
write (*,*) ‘the grade is D.’
else
write (*,*) ‘the grade is F.’
Endif

Stop
end
program nested_if
implicit none
real :: grade, a, b, c, d, f
write(*,*) ‘enter the marks in numbers:’
read(*,*) grade
if1: if (grade .gt. 100.0) then
write (*,*) ‘invalid mark’
if2: if(grade .gt. 95.0) then
write (*,*) ‘the grade is A.’
if3: if(grade .gt. 80.0) then
write (*,*) ‘the grade is B.’
if4: if(grade .gt. 65.0) then
write (*,*) ‘the grade is C.’
if5: if(grade .gt. 50.0) then
write (*,*) ‘the grade is D.’
else
write (*,*) ‘the grade is F.’
endif if5
endif if4
endif if3
endif if2
endif if1
Stop
end
1. Write a program segment to read a number x and display its sign.
More precisely, if x is positive, a + is displayed; if x is negative, a -
is displayed; otherwise, a 0 is displayed. Using IF-THEN-ELSE
IF-END IF

2.Given a x, we want to display the value of -x if x < 0, the value


of x*x if x is in the range of 0 and 1 inclusive, and the value
of 2*x if x is greater than 1

3.finding the smallest of three given numbers.


The case construct

It permits the programmer to select a particular code block to execute based on the value of a
single integer, character or logical expression
[name:] SELECT CASE (case_expr)
CASE (case_1) [name]
statement1
Statement2
….
CASE (case_2) [name]
statement3
Statement4
….
CASE DEFAULT [name]
statement5
Statement6
….
END SELECT [name]
The CASE construct

• The CASES should not overlap- the given value can appear in only one of the cases
• The case_selector can take one of the four forms:

Case_value execute block if case_value = case_expr


Low_value execute block if low_value  case_expr
High_value execute block if case_expr  high_val
low_value:high_value execute block if low_value  case_expr  high_value
Or it can be list of any combination of these forms separated by commas
program case_example1 program case_example2
implicit none implicit none
integer:: temp_c integer:: nvalue
write(*,*) “enter today’s emperature in degree write(*,*) “enter an integer between 1
celsius” to 10”
read(*,*) tem_c read(*,*) nvalue

temp: select case (temp_c) case1: select case (nvalue)


case (:-1) case(1,3,5,7,9)
write(*,*) “it’s below freezing today” write(*,*)”the entered number is odd”
case(0) case(2,4,6,8)
write(*,*)”its exactly at the freezing point” write(*,*) “the entered value is even”
case(1:20) case(11:)
write(*,*)” its cool day” write(*,*)”the value is too high”
case(21:33) case default
write(*,*)”its warm day today” write(*,*)”the value is negative or zero”
case(34:) end select case1
write(*,*)”its hot today”
end select temp stop
end
stop
end
Control constructs : loops
• Loops are Fortran constructs that permit us to execute a sequence of statements more than once
• While loop and iterative loop (counting loops)
• Difference is how the repetition is controlled
• While loop is repeated an infinite number of times until some user-specified condition is satisfied
• Iterative loops repeated a specified number of times, and the number of repetition is known before the loop starts

The Do loop
The DO loop is a block of statements that are repeated indefinitely as long as some condition is satisfied

DO
DO
WRITE(*,*)’Enter
……..
Number:’
IF (logical_expr)
READ (*,*) x
EXIT
IF (x .LT. 0) EXIT
….
n=n+1
END DO
END DO

The statements between DO and END DO are repeated indefinitely until the logical_expr becomes true and EXIT statement
is executed.
After the EXIT statement is executed, control transfers to the first statement after the END DO
program std_dev
implicit none

integer :: n = 0
real :: std_dev, sum_x = 0., sum_x2=0., x, x_bar

DO
write(*,*) ‘enter number:’ x_bar = sum_x/real(n)
read(*,*)x std_dev = sqrt((real(n)*sum_x2-sum_x**2)/(real(n)*real(n-1))
write(*,*) ‘the mean of the set is:’ ,x_bar
IF (x .lt. 0) EXIT write(*,*)‘the standard deviation is :’, std_dev
N = n+1 write(*,*)’the number of data entered:’, n
Sum_x = sum_x + x END IF
Sum_x2 = sum_x2 +x**2 STOP
END DO END

IF (n .lt. 2) THEN
Write(*,*) ‘at least two values must be entered.’
ELSE
The DO WHILE loop

Fortran 90 has an alternate form of DO loop, called DO WHILE loop.

DO WHILE (logical_expr)
……..
……..
…….
END DO

If the logical_expr is true, the block will be executed. The process will be repeated until the logical
expression becomes true

If the logical_expr is false, the program will execute the first statement after the END DO
Control construct: loops
The iterative loop

In fortran 90, a loop that execute a block of statements a


specified number of times is called iterative DO loop

DO index = istart, iend, incr


statement 1
………….
statement n
END DO

Where the index is an integer variable used as a loop


counter. The inter quantities istart, iend, incr are the
parameters of the counting loop. Incr is optional. If not
given assumed to be 1
The number of iterations to be perormed by the DO loop
𝑖𝑒𝑛𝑑−𝑖𝑠𝑡𝑎𝑟𝑡+𝑖𝑛𝑐𝑟
may be calculated using iter = 𝑖𝑛𝑐𝑟
Index*incr  iend*incr
DO i = 1, 10
statement 1 DO i = 1, 10, 2
………… statement 1
statement n …………
END DO statement n
END DO
DO i= 1, 10, -1
statement 1 DO i= 3, -3, -2
………… statement 1
statement n …………
END DO statement n
END DO

Where index is an inter variable used as a loop counter

The integer quantities istart, iend, incr are the parameters of the counting loop
𝑁 σ𝑁 2 𝑁
𝑖=1 𝑥𝑖 − (σ𝑖=1 𝑥𝑖 )
2
1. Find the standard deviation of the entered numbers
𝑁(𝑁−1)
2. Find the factorial of the given number
Standard deviation

program std_dev_using_do
implicit none

integer :: i, n = 0
real :: std_dev, sum_x = 0., sum_x2=0., x= 0., X_bar = sum_x/real(n)
x_bar std_dev = sqrt((real(n)*sum_x2-sum_x**2)/(real(n)*real(n-1))
write(*,*) ‘enter number of points’ write(*,*) ‘the mean of the set is:’ ,x_bar
read(*,*)n write(*,*)‘the standard deviation is :’, std_dev
write(*,*)’the number of data entered:’, n
IF (n .lt. 2) THEN END IF
Write(*,*) ‘at least two values must be entered.’ STOP
ELSE END
DO i = 1, n
Write(*,*) ‘enter number’
read (*,*)x
Sum_x = sum_x + x
Sum_x2 = sum_x2 + x**2
END DO
program factorial
implicit none
integer:: i, n, fact = 1.
write(8,*)’enter the value of n:
read(*,*)n

DO i=1, n
Fact= fact* I
END DO
Write(8,*) ‘the factorial is:’, fact

Stop
End program
Control constructs: loops
The CYCLE and EXIT statements

Two additional statements can be used to control the operation of loops are CYCLE and EXIT
If the CYCLE statement is executed, the execution of the body will stop and control will be returned to
the top of the loop
Program test_cycle
Inplicit none
1
2
DO I=1,5
4
IF (I .EQ. 3) CYCLE
5
WRITE(8,*)
End of the loop
END DO
WRITE(*,*0 ‘end of loop:’
STOP
END PROGRAM

Two CYCLE statements was executed on the iteration when I was 3 and control returned to the top of the loop
without executing the WRITE statement
4. Convert Celsius to Fahrenheit

5
Write program for multiplication table

program multiplication_table
implicit none
integer :: i, j, n ! Read the multiplication table number from the
user
print *, 'Enter the number for the multiplication table: ‘
read *, n ! Loop to generate the multiplication table
Do
i = 1, 10
print *, n, ' x ', i, ' = ', n * i
end do
end program multiplication_table
• sum of the first 10 natural numbers.
• Sum of Array Elements
• Finding the Greatest Common Divisor (GCD)
• Calculate the Average of Numbers
• Checking for Prime Numbers
• Fibonacci Series
program sum_of_natural_numbers
implicit none
integer :: i, sum

! Initialize sum to zero


sum = 0

! Loop to calculate the sum of the first 10 natural numbers


do i = 1, 10
sum = sum + i
end do

! Print the result


print *, 'The sum of the first 10 natural numbers is: ', sum
end program sum_of_natural_numbers
program array_sum
implicit none
integer, dimension(5) :: arr = [1, 2, 3, 4, 5]
integer :: i
integer :: sum

! Initialize sum
sum = 0

! Calculate sum of array elements


do i = 1, size(arr)
sum = sum + arr(i)
end do

! Print the result


print *, 'The sum of array elements is ', sum
end program array_sum
program gcd
implicit none
integer :: a, b, gcd_result

! Read two integers from the user


gcd = x
print *, 'Enter two integers: '
remainder = y
read *, a, b
do while (remainder /= 0)
! Calculate GCD
gcd = remainder
gcd_result = gcd(a, b)
remainder = mod(gcd, remainder)
end do
! Print the result
end function gcd
print *, 'The GCD of ', a, ' and ', b, ' is ', gcd_result
end program gcd
contains
integer function gcd(x, y)
integer, intent(in) :: x, y
integer :: remainder
program average
implicit none
real, dimension(5) :: numbers
real :: sum, average
integer :: i

! Read five numbers from the user


print *, 'Enter five numbers: '
read *, numbers

! Calculate sum and average


sum = 0.0
do i = 1, size(numbers)
sum = sum + numbers(i)
end do
average = sum / size(numbers)

! Print the average


print *, 'The average is: ', average
end program average
program prime_check
implicit none
integer :: n, i
logical :: is_prime

! Read an integer from the user


print *, 'Enter an integer: '
read *, n
! Print the result
if (is_prime) then
! Initialize is_prime
print *, n, ' is a prime number.'
is_prime = .true.
else
print *, n, ' is not a prime number.'
! Check if the number is prime
end if
if (n <= 1) then
end program prime_check
is_prime = .false.
else
do i = 2, n / 2
if (mod(n, i) == 0) then
is_prime = .false.
exit
end if
end do
end if
program fibonacci
implicit none
integer :: n, i
integer, dimension(:), allocatable :: fib

! Read the number of terms from the user


print *, 'Enter the number of terms: '
read *, n

! Allocate array for Fibonacci series


allocate(fib(n))

! Initialize the first two terms


fib(1) = 0
if (n > 1) fib(2) = 1

! Calculate the Fibonacci series


do i = 3, n
fib(i) = fib(i - 1) + fib(i - 2)
end do

! Print the Fibonacci series


print *, 'The Fibonacci series is: ', fib
end program fibonacci
Whats next?

• Arrays
1D array
2D array
• Subroutines
• User-defined functions
• Formatted input and output statements
• Random numbers generation
• Plotting - Gnuplot
• Arrays – a group of variables or constants, all of the same
type, that are referred to by a single name

• The values in the group occupy consecutive locations in the


computer’s memory
a(1)
• array element – an individual value within the array
a(2)
a(3)
• Array elements can be identified by the name of the array
a(4)
with a subscript pointing to the particular location
a(5)
a(6)
• The first variable is referred to as a(1), and the fifth
variable is referred as a(5)
• Arrays are very powerful tools
• Arrays permit us to apply the same algorithm over and over again to many
different data items with a simple DO loop
• Example
DO i = 1, 100
a(i) = SQRT (a(i))
END DO
• Without using an array, we would have to write out
a1 = SQRT (a1)
a2 = SQRT (a2)
……….
a100 = SQRT (a100)
• As 100 separate statements
Declaring Arrays

• Before array can be used, its type and the number of elements must be declares first
TYPE, DIMENSION (array_length) :: variable_name
REAL, DIMENSION(20) :: array
• The DIMENSION attribute in the type declaration declare size of the array
• The elements in array araay would be addressed as array(1), ….array(20)
• An alternative way to declare an array is

TYPE :: variable_name(array_length)
REAL :: array (20)
• Its fully equivalent to the array declaration shown above
• Arrays may be declared with more than one subscripts – two or more
dimensions
• The number of subscripts declared for a giveb array is called rank of the array
• The number of elements in a given array is called extent of the array
• The shape of an array is defined as the combination of its rank and the extent
of the array in each dimension
• The size of an array is the total number of elements declared in that array
• Array constants may also be defined. It is defined by placing the constant values
between the array constructs
• Example (/1, 2, 3, 4, 5 /)
program basic_array
implicit none
integer, dimension(5) :: arr ! Declare an
array of size 5
integer :: i

! Initialize the array OUTPUT


arr = (/1, 2, 3, 4, 5/) Element 1 = 1
Element 2 = 2
Element 3 = 3
! Print the array elements Element 4 = 4
do i = 1, 5 Element 5 = 5
print *, 'Element ', i, ' = ', arr(i)
end do
end program basic_array
program array_operations
implicit none
integer, dimension(3) :: a = (/2, 4, 6/)
integer, dimension(3) :: b = (/1, 3, 5/)
integer, dimension(3) :: c
integer :: i

! Perform element-wise addition


c=a+b
Result of a + b:
! Print the result c( 1 ) = 3
print *, 'Result of a + b:' c( 2 ) = 7
c( 3 ) = 11
do i = 1, 3
print *, 'c(', i, ') = ', c(i)
end do
end program array_operations
program multidimensional_array
implicit none
integer, dimension(3, 3) :: matrix
integer :: i, j

! Initialize the 3x3 matrix


matrix = reshape((/1, 2, 3, 4, 5, 6, 7, 8, 9/), Matrix:
shape(matrix)) matrix( 1 , 1 ) = 1
matrix( 1 , 2 ) = 2
! Print the matrix matrix( 1 , 3 ) = 3
print *, 'Matrix:' matrix( 2 , 1 ) = 4
do i = 1, 3 matrix( 2 , 2 ) = 5
do j = 1, 3 matrix( 2 , 3 ) = 6
print *, 'matrix(', i, ',', j, ') = ', matrix(i, j) matrix( 3 , 1 ) = 7
matrix( 3 , 2 ) = 8
end do
matrix( 3 , 3 ) = 9
end do
end program multidimensional_array
Whole array operation
Whole arrays may be used in arithmetic calculations as though they are ordinarvariables
If two arrays are the same shape, the they can be used in ordinary arithmetic
y
Procedures and structured programming
Passing Arrays to subroutines
Reading and printing matrix
Write the program for solution of the quadratic equation using subroutines
False Position method
A projectile is launched with an initial velocity 0 at an angle θ above the horizontal. Using the laws of motion,
calculate the following:
1.Maximum height reached by the projectile.
2.Time of flight.
3.Horizontal range.
program projectile_motion ! Calculate maximum height
implicit none height = (v0**2 * (sin(theta)**2)) / (2 * g)
real :: v0, theta, g, height, time_of_flight, range
real, parameter :: pi = 3.14159265358979 ! Calculate time of flight
g = 9.81 ! Acceleration due to gravity in m/s^2 time_of_flight = (2 * v0 * sin(theta)) / g

! Input: initial velocity and angle ! Calculate horizontal range


print*, 'Enter the initial velocity (m/s): ' range = (v0**2 * sin(2.0 * theta)) / g
read*, v0
print*, 'Enter the angle of projection (degrees): ' ! Output the results
read*, theta print*, 'Maximum height reached by the projectile (m): ',
height
! Convert angle to radians print*, 'Total time of flight (s): ', time_of_flight
theta = theta * pi / 180.0 print*, 'Horizontal range of the projectile (m): ', range
end program projectile_motion
program projectile_with_air_resistance
implicit none
! Initial conditions
real, parameter :: g = 9.81 ! Gravitational acceleration
vx = v0 * cos(theta)
(m/s^2)
vy = v0 * sin(theta)
real, parameter :: m = 0.1 ! Mass of projectile (kg)
x = 0.0
real, parameter :: k = 0.1 ! Drag coefficient (kg/s)
y = 0.0
real, parameter :: dt = 0.01 ! Time step (s)
t = 0.0
real, parameter :: pi = 3.14159265358979
integer, parameter :: steps = 1000
! Euler's method for numerical integration
real :: v0, theta, t, vx, vy, x, y
do i = 1, steps
real, dimension(steps) :: x_pos, y_pos, v_x, v_y, time
! Store positions and velocities at each step
integer :: i
x_pos(i) = x
y_pos(i) = y
! Input initial velocity and angle
v_x(i) = vx
print*, 'Enter the initial velocity (m/s): '
v_y(i) = vy
read*, v0
time(i) = t
print*, 'Enter the angle of projection (degrees): '
read*, theta
! Update positions
x = x + vx * dt
! Convert angle to radians
y = y + vy * dt
theta = theta * pi / 180.0
! Update velocities using Newton's Second Law (with air
resistance)
vx = vx - (k/m) * vx * dt
vy = vy - g * dt - (k/m) * vy * dt

! Update time
t = t + dt

! Stop if the projectile hits the ground


if (y <= 0.0) exit
end do

! Output results
print*, 'Time (s)', 'x position (m)', 'y position (m)', 'vx (m/s)',
'vy (m/s)'
do i = 1, steps
print*, time(i), x_pos(i), y_pos(i), v_x(i), v_y(i)
if (y_pos(i) <= 0.0) exit
end do
end program projectile_with_air_resistance
program schrodinger_1D_infinite_well
implicit none
real, parameter :: hbar = 1.0545718e-34 ! Reduced Planck's
constant (J·s)
real, parameter :: m = 9.10938356e-31 ! Mass of electron
(kg)
real, parameter :: pi = 3.14159265358979
real :: L, E_n
integer :: n

! Input: width of the potential well


print*, 'Enter the width of the potential well (m): '
read*, L

! Input: quantum number


print*, 'Enter the quantum number (n): '
read*, n

! Calculate energy levels


E_n = (n**2 * pi**2 * hbar**2) / (2 * m * L**2)

! Output the energy level


print*, 'Energy level for n = ', n, ' is E_n (J): ', E_n
end program schrodinger_1D_infinite_well
Write a program for average_of_numbers

Write program for reverse_string

program sum_even_odd

program count_vowels
program harmonic_oscillator
implicit none

! Declare variables
real(8) :: x, v, a, m, k, dt, t, t_max
real(8) :: t_half_step, x_half_step

! Constants
m = 1.0d0 ! Mass of the oscillator (kg)
k = 1.0d0 ! Spring constant (N/m)
dt = 0.01d0 ! Time step for numerical integration (s)
t_max = 10.0d0 ! Maximum simulation time (s)

! Initial conditions
x = 1.0d0 ! Initial displacement from equilibrium (m)
v = 0.0d0 ! Initial velocity (m/s)
t = 0.0d0 ! Initial time (s)

! Output header
print*, ' Time (s) X (m) V (m/s)'

! Calculate the initial acceleration


a = -k * x / m
! Time-stepping loop using the Velocity Verlet method
do while (t <= t_max)
! Print current time, displacement and velocity
print*, t, x, v

! Step 1: Calculate the position at the half-step


x_half_step = x + v * dt * 0.5d0
! Step 5: Update the velocity using the new
acceleration
! Step 2: Calculate the new velocity at the half-step
v = t_half_step + a * dt * 0.5d0
t_half_step = v + a * dt * 0.5d0
! Update time
! Step 3: Update the position using the half-step
t = t + dt
velocity
end do
x = x + t_half_step * dt
print*, 'Simulation complete.'
! Step 4: Calculate the new acceleration based on
the updated position
end program harmonic_oscillator
a = -k * x / m
program average_of_numbers
implicit none
! Calculate the sum
integer :: n, i
sum = 0.0
real :: sum, average
do i = 1, n
real, dimension(:), allocatable :: numbers
sum = sum + numbers(i)
end do
! Input: number of terms
print*, 'Enter the number of terms:'
! Calculate the average
read*, n
average = sum / n
! Allocate the array
! Output the average
allocate(numbers(n))
print*, 'The average is:', average
! Input: numbers
! Deallocate array
print*, 'Enter the numbers:'
deallocate(numbers)
do i = 1, n
read*, numbers(i)
end program average_of_numbers
end do
program reverse_string
implicit none
character(len=100) :: str, rev_str
integer :: i, len_str

! Input: string to reverse


print*, 'Enter a string:'
read*, str

! Find length of the string


len_str = len_trim(str)

! Reverse the string


do i = 1, len_str
rev_str(i:i) = str(len_str-i+1:len_str-i+1)
end do

! Output the reversed string


print*, 'Reversed string is:', trim(rev_str)

end program reverse_string


program sum_even_odd
implicit none
integer :: i, n, sum_even, sum_odd ! Calculate sums of even and odd numbers
do i = 1, n
! Input: range upper limit if (mod(i, 2) == 0) then
print*, 'Enter a positive integer:' sum_even = sum_even + i
read*, n else
sum_odd = sum_odd + i
! Initialize sums end if
sum_even = 0 end do
sum_odd = 0
! Output the sums
print*, 'Sum of even numbers:', sum_even
print*, 'Sum of odd numbers:', sum_odd

end program sum_even_odd


! Count vowels
program count_vowels do i = 1, len_str
implicit none ch = str(i:i)
character(len=100) :: str if (ch == 'a' .or. ch == 'e' .or. ch == 'i' .or. ch == 'o'
integer :: i, len_str, vowel_count .or. ch == 'u' &
character :: ch .or. ch == 'A' .or. ch == 'E' .or. ch == 'I' .or. ch
== 'O' .or. ch == 'U') then
! Input: string vowel_count = vowel_count + 1
print*, 'Enter a string:' end if
read*, str end do

len_str = len_trim(str) ! Output the count of vowels


vowel_count = 0 print*, 'Number of vowels in the string:', vowel_count

end program count_vowels


1. Projectile Motion Using Euler's Method

2. Damped Harmonic Oscillator Using Euler's Method

3. Write a program that simulates the orbit of a planet around a star, assuming gravitational force and
using Euler's method for time-stepping.

4. Radioactive Decay Using Euler's Method

5. program computes the trajectory of a charged particle in an electromagnetic field, solving the
Lorentz force equation using Euler's method.

6. solve the motion of a driven harmonic oscillator with damping using Euler’s method.

7. Flow of a Viscous Fluid (Stokes' Law) Using Euler’s Method

8. Simple 1D Fluid Flow Using Euler's Method (Euler Equation)

9. simulates the orbital motion of two bodies using a central gravitational force (inverse-square law).
! Euler's method for time-stepping
PROGRAM ProjectileEuler
DO i = 1, steps
IMPLICIT NONE
! Update positions and velocities using Euler's method
REAL, PARAMETER :: g = 9.81, dt = 0.01
x = x + vx * dt
REAL :: t, x, y, vx, vy
y = y + vy * dt
INTEGER :: steps, i
vy = vy - g * dt ! Update y-velocity due to gravity
t = t + dt
! Initial conditions
t = 0.0 ! Start time
! Stop if the projectile hits the ground
x = 0.0 ! Initial position (x)
IF (y <= 0.0) EXIT
y = 0.0 ! Initial position (y)
vx = 10.0 ! Initial velocity in x-direction (m/s)
! Output time, position, and velocity
vy = 10.0 ! Initial velocity in y-direction (m/s)
PRINT *, t, x, y, vx, vy
steps = 500 ! Number of time steps
END DO
END PROGRAM ProjectileEuler
! Euler's method for time-stepping
PROGRAM DampedOscillatorEuler
DO i = 1, steps
IMPLICIT NONE
a = -k/m * x - b/m * v ! Acceleration due to spring
REAL, PARAMETER :: k = 1.0, m = 1.0, b = 0.1,
and damping force
dt = 0.01
v = v + a * dt ! Update velocity
REAL :: t, x, v, a
x = x + v * dt ! Update position
INTEGER :: steps, i
t = t + dt ! Update time
! Initial conditions
! Output time, position, and velocity
t = 0.0 ! Start time
PRINT *, t, x, v, a
x = 1.0 ! Initial displacement (m)
END DO
v = 0.0 ! Initial velocity (m/s)
END PROGRAM DampedOscillatorEuler
steps = 1000 ! Number of time steps
! Euler's method for time-stepping
DO i = 1, steps
! Calculate distance and acceleration due to gravity
PROGRAM PlanetaryMotionEuler
r = SQRT(x**2 + y**2)
IMPLICIT NONE
ax = -G * M * x / r**3
REAL, PARAMETER :: G = 1.0, M = 1.0, dt = 0.001
ay = -G * M * y / r**3
REAL :: t, x, y, vx, vy, r, ax, ay
INTEGER :: steps, i
! Update velocities and positions using Euler's method
vx = vx + ax * dt
! Initial conditions (assume a circular orbit)
vy = vy + ay * dt
t = 0.0 ! Start time
x = x + vx * dt
x = 1.0 ! Initial position in x (AU)
y = y + vy * dt
y = 0.0 ! Initial position in y (AU)
t = t + dt
vx = 0.0 ! Initial velocity in x (AU/day)
vy = 1.0 ! Initial velocity in y (AU/day)
! Output time, position, and velocity
steps = 100000 ! Number of time steps
PRINT *, t, x, y, vx, vy
END DO
END PROGRAM PlanetaryMotionEuler
PROGRAM RadioactiveDecayEuler
IMPLICIT NONE
REAL, PARAMETER :: lambda = 0.1, dt = 0.1
REAL :: t, N
INTEGER :: steps, i

! Initial conditions
t = 0.0 ! Start time
N = 100.0 ! Initial number of radioactive nuclei
steps = 100 ! Number of time steps

! Euler's method for time-stepping


DO i = 1, steps
N = N - lambda * N * dt ! Update number of nuclei
t = t + dt ! Update time

! Output time and number of remaining nuclei


PRINT *, t, N
END DO
END PROGRAM RadioactiveDecayEuler
! Euler's method for time-stepping
PROGRAM LorentzForceEuler DO i = 1, steps
IMPLICIT NONE ! Lorentz force F = q(E + v x B)
REAL, PARAMETER :: q = 1.0, m = 1.0, dt = 0.01 F(1) = q * (E(1) + v(2) * B(3) - v(3) * B(2))
REAL :: t, x(3), v(3), E(3), B(3), F(3) F(2) = q * (E(2) + v(3) * B(1) - v(1) * B(3))
INTEGER :: steps, i F(3) = q * (E(3) + v(1) * B(2) - v(2) * B(1))

! Initial conditions ! Update velocity and position


t = 0.0 v = v + (F/m) * dt
x = (/0.0, 0.0, 0.0/) ! Initial position (x, y, z) x = x + v * dt
v = (/1.0, 0.0, 0.0/) ! Initial velocity (vx, vy, vz) t = t + dt
E = (/0.0, 1.0, 0.0/) ! Electric field (Ex, Ey, Ez)
B = (/0.0, 0.0, 1.0/) ! Magnetic field (Bx, By, Bz) ! Output time, position, and velocity
steps = 1000 ! Number of time steps PRINT *, t, x(1), x(2), x(3), v(1), v(2), v(3)
END DO
END PROGRAM LorentzForceEuler
PROGRAM DrivenOscillatorEuler ! Euler's method for time-stepping
IMPLICIT NONE DO i = 1, steps
REAL, PARAMETER :: k = 1.0, m = 1.0, b = F_ext = A * SIN(omega_d * t) ! External driving
0.1, A = 1.0, omega_d = 0.5, dt = 0.01 force
REAL :: t, x, v, a, F_ext a = (-k*x - b*v + F_ext) / m ! Acceleration due to
INTEGER :: steps, i spring, damping, and external force
v = v + a * dt ! Update velocity
! Initial conditions x = x + v * dt ! Update position
t = 0.0 ! Start time t = t + dt ! Update time
x = 1.0 ! Initial displacement (m)
v = 0.0 ! Initial velocity (m/s) ! Output time, position, velocity, and external force
steps = 1000 ! Number of time steps PRINT *, t, x, v, F_ext
END DO
END PROGRAM DrivenOscillatorEuler
! Euler's method for time-stepping
PROGRAM StokesFlowEuler DO i = 1, steps
IMPLICIT NONE F_gravity = m * g ! Force due to gravity
REAL, PARAMETER :: g = 9.81, m = F_drag = 6.0 * PI * eta * r * v ! Drag force (Stokes'
0.01, eta = 0.001, r = 0.01, dt = 0.01 law)
REAL :: t, v, a, F_drag, F_gravity a = (F_gravity - F_drag) / m ! Net acceleration
INTEGER :: steps, i v = v + a * dt ! Update velocity
t = t + dt ! Update time
! Initial conditions
t = 0.0 ! Start time ! Output time, velocity, acceleration
v = 0.0 ! Initial velocity (m/s) PRINT *, t, v, a
steps = 1000 ! Number of time steps END DO
END PROGRAM StokesFlowEuler
PROGRAM EulerEquation1D ! Time-stepping loop
IMPLICIT NONE DO t = 1, t_steps
REAL, PARAMETER :: dx = 0.1, dt = 0.01 ! Compute fluxes
REAL, PARAMETER :: L = 10.0, t_max = 10.0 DO i = 2, nx-1
INTEGER, PARAMETER :: nx = 100 F_rho(i) = rho(i)*u(i)
REAL :: rho(nx), u(nx), p(nx), E(nx), F_rho(nx), F_u(nx), F_u(i) = rho(i)*u(i)**2 + p(i)
F_E(nx) F_E(i) = (E(i) + p(i))*u(i)
INTEGER :: i, t_steps, t END DO
! Update density, velocity, and pressure using Euler's method
! Initial conditions for density, velocity, and pressure DO i = 2, nx-1
DO i = 1, nx rho(i) = rho(i) - dt/dx * (F_rho(i) - F_rho(i-1))
IF (i <= nx/2) THEN u(i) = (rho(i)*u(i) - dt/dx * (F_u(i) - F_u(i-1))) / rho(i)
rho(i) = 1.0 ! Density in the left half E(i) = E(i) - dt/dx * (F_E(i) - F_E(i-1))
u(i) = 0.0 ! Velocity p(i) = (1.4 - 1.0)*(E(i) - 0.5*rho(i)*u(i)**2) ! Update
p(i) = 1.0 ! Pressure pressure
ELSE END DO
rho(i) = 0.125 ! Density in the right half ! Output density, velocity, and pressure for visualization
u(i) = 0.0 ! Velocity IF (MOD(t, 100) == 0) THEN
p(i) = 0.1 ! Pressure DO i = 1, nx
END IF PRINT *, i*dx, rho(i), u(i), p(i)
E(i) = p(i)/(1.4 - 1.0) + 0.5*rho(i)*u(i)**2 ! Energy END DO
END DO END IF
END DO
t_steps = INT(t_max / dt) END PROGRAM EulerEquation1D
! Euler's method for time-stepping
PROGRAM OrbitalMechanicsEuler DO i = 1, steps
IMPLICIT NONE ! Compute distance and acceleration due to gravity
REAL, PARAMETER :: G = 6.67430E-11, M = r = SQRT(x**2 + y**2)
1.989E30, dt = 3600.0 ax = -G * M * x / r**3
REAL :: t, r, vx, vy, ax, ay, x, y ay = -G * M * y / r**3
INTEGER :: steps, i
! Update velocity and position
! Initial conditions for Earth's orbit around the Sun vx = vx + ax * dt
t = 0.0 vy = vy + ay * dt
x = 1.496E11 ! Initial position in meters (1 AU) x = x + vx * dt
y = 0.0 ! Initial position in meters y = y + vy * dt
vx = 0.0 ! Initial velocity in m/s t = t + dt
vy = 2.978E4 ! Initial tangential velocity in m/s
steps = 100000 ! Number of time steps ! Output time, position, and velocity
PRINT *, t, x, y, vx, vy
END DO
END PROGRAM OrbitalMechanicsEuler
PROGRAM NewtonInterpolation
IMPLICIT NONE
Newton Interpolation
INTEGER :: n, i, j
REAL :: x_target, result
! Input the target x value for interpolation
REAL, DIMENSION(:), ALLOCATABLE :: x, y, diff_table
PRINT*, "Enter the value of x where you want to
interpolate:"
! Input number of data points
READ*, x_target
PRINT*, "Enter the number of data points:"
READ*, n
! Initialize the first column of the divided difference table
with y values
! Allocate arrays for x and y
diff_table = y
ALLOCATE(x(n), y(n), diff_table(n))
! Construct divided difference table
! Input data points
DO j = 2, n
PRINT*, "Enter the x values:"
DO i = n, j, -1
DO i = 1, n
diff_table(i) = (diff_table(i) - diff_table(i-1)) / (x(i) - x(i-
READ*, x(i)
j+1))
END DO
END DO
END DO
PRINT*, "Enter the y values (corresponding to x values):"
DO i = 1, n
READ*, y(i)
END DO
! Perform the interpolation
result = diff_table(1)
DO i = 2, n
result = result + diff_table(i) * PRODUCT(x_target - x(1:i-
1))
END DO
! Output the interpolated result
PRINT*, "The interpolated value at x =", x_target, " is:",
result
! Deallocate the arrays
DEALLOCATE(x, y, diff_table)
END PROGRAM NewtonInterpolation
PROGRAM ThermodynamicsInterpolation
IMPLICIT NONE

INTEGER :: n, i, j
REAL :: T_target, result
REAL, DIMENSION(:), ALLOCATABLE :: T, P, diff_table ! Input pressure values corresponding to temperatures
PRINT*, "Enter the pressure values (in Pa):"
! Input number of data points DO i = 1, n
PRINT*, "Enter the number of temperature-pressure data READ*, P(i)
points:" END DO
READ*, n
! Input target temperature for interpolation
! Allocate arrays for T and P PRINT*, "Enter the temperature where you want to
ALLOCATE(T(n), P(n), diff_table(n)) interpolate the pressure:"
READ*, T_target
! Input temperature values
PRINT*, "Enter the temperature values (in K):" ! Initialize the first column of divided difference table
DO i = 1, n with P values
READ*, T(i) diff_table = P
END DO
! Compute divided difference table
DO j = 2, n
DO i = n, j, -1
diff_table(i) = (diff_table(i) - diff_table(i-1)) / (T(i) - T(i-
j+1))
END DO
END DO

! Perform the interpolation


result = diff_table(1)
DO i = 2, n
result = result + diff_table(i) * PRODUCT(T_target -
T(1:i-1))
END DO

! Output interpolated pressure value


PRINT*, "The interpolated pressure at T =", T_target, "K
is:", result, " Pa"

! Deallocate arrays
DEALLOCATE(T, P, diff_table)

END PROGRAM ThermodynamicsInterpolation


! Input specific heat values corresponding to
PROGRAM SpecificHeatInterpolation temperatures
IMPLICIT NONE PRINT*, "Enter the specific heat values (in J/(kg*K)):"
DO i = 1, n
INTEGER :: n, i, j READ*, C(i)
REAL :: T_target, result END DO
REAL, DIMENSION(:), ALLOCATABLE :: T, C, diff_table
! Input target temperature for interpolation
! Input number of temperature-specific heat data points PRINT*, "Enter the temperature where you want to
PRINT*, "Enter the number of temperature-specific heat interpolate the specific heat:"
data points:" READ*, T_target
READ*, n
! Initialize the first column of divided difference table
! Allocate arrays for temperature (T) and specific heat (C) with C values
ALLOCATE(T(n), C(n), diff_table(n)) diff_table = C

! Input temperature values ! Compute divided difference table


PRINT*, "Enter the temperature values (in K):" DO j = 2, n
DO i = 1, n DO i = n, j, -1
READ*, T(i) diff_table(i) = (diff_table(i) - diff_table(i-1)) / (T(i) -
END DO T(i-j+1))
END DO
END DO

! Perform the interpolation


result = diff_table(1)
DO i = 2, n
result = result + diff_table(i) * PRODUCT(T_target -
T(1:i-1))
END DO

! Output interpolated specific heat value


PRINT*, "The interpolated specific heat at T =", T_target, "
K is:", result, " J/(kg*K)"

! Deallocate arrays
DEALLOCATE(T, C, diff_table)

END PROGRAM SpecificHeatInterpolation


v = v0 ! set initial velocity

! Open file to store the results


OPEN(UNIT=10, FILE='euler_results.txt’)
! Print the header for output
WRITE(10,*) 'Time', 'Velocity'

! Loop over time steps using Euler's method


DO i = 1, steps
PROGRAM EulerMethod ! Write current time and velocity to file
IMPLICIT NONE WRITE(10,*) t, v

! Define parameters ! Euler's method update


REAL :: t, dt, v, v0, F, m v = v + dt * (F / m) ! update velocity
INTEGER :: steps, i
! Update time
! Initial conditions t = t + dt
t = 0.0 ! initial time END DO
dt = 0.01 ! time step ! Close the output file
v0 = 0.0 ! initial velocity CLOSE(10)
F = 10.0 ! constant force (e.g., 10 N) PRINT *, 'Simulation complete. Results stored in
m = 2.0 ! mass (e.g., 2 kg) euler_results.txt.'
steps = 100 ! number of steps for the Euler method END PROGRAM EulerMethod
! Open file to store results
OPEN(UNIT=10, FILE='sho_results.txt')

WRITE(10,*) 'Time', 'Position', 'Velocity'

DO i = 1, steps
! Write current state to file
PROGRAM SHO_Euler WRITE(10,*) t, x, v
IMPLICIT NONE
! Update using Euler's method
REAL :: x, v, t, dt, omega0 v = v - dt * omega0**2 * x
INTEGER :: steps, i x = x + dt * v

! Parameters ! Update time


omega0 = 1.0 ! natural angular frequency t = t + dt
dt = 0.01 ! time step END DO
steps = 1000 ! number of steps
x = 1.0 ! initial position CLOSE(10)
v = 0.0 ! initial velocity PRINT *, 'SHO simulation complete. Results in
t = 0.0 ! initial time sho_results.txt.'

END PROGRAM SHO_Euler


DO i = 1, steps
PROGRAM Projectile_Euler ! Write current state to file
IMPLICIT NONE WRITE(10,*) t, x, y, vx, vy

REAL :: x, y, vx, vy, t, dt, g, C, m ! Update velocities


INTEGER :: steps, i vx = vx - dt * (C/m) * vx
vy = vy - dt * g - dt * (C/m) * vy
! Parameters
g = 9.81 ! gravitational acceleration (m/s^2) ! Update positions
C = 0.1 ! drag coefficient x = x + dt * vx
m = 1.0 ! mass of the projectile y = y + dt * vy
dt = 0.01 ! time step
steps = 1000 ! number of steps ! Update time
x = 0.0 ! initial x position t = t + dt
y = 0.0 ! initial y position
vx = 10.0 ! initial velocity in x-direction ! Stop if projectile hits the ground
vy = 10.0 ! initial velocity in y-direction IF (y < 0.0) EXIT
t = 0.0 ! initial time END DO

! Open file to store results CLOSE(10)


OPEN(UNIT=10, FILE='projectile_results.txt') PRINT *, 'Projectile simulation complete. Results in
projectile_results.txt.'
WRITE(10,*) 'Time', 'X', 'Y', 'Vx', 'Vy'
END PROGRAM Projectile_Euler
! Open file to store results
OPEN(UNIT=10, FILE='rc_results.txt')

WRITE(10,*) 'Time', 'Voltage_C'

DO i = 1, steps
! Write current state to file
PROGRAM RCCircuit_Euler WRITE(10,*) t, V_C
IMPLICIT NONE
! Update voltage using Euler's method
REAL :: V_C, R, C, t, dt V_C = V_C - dt * (V_C / (R * C))
INTEGER :: steps, i
! Update time
! Parameters t = t + dt
R = 1000.0 ! resistance in ohms END DO
C = 1e-6 ! capacitance in farads
V_C = 5.0 ! initial voltage across the capacitor CLOSE(10)
dt = 0.001 ! time step PRINT *, 'RC circuit simulation complete.
steps = 1000 ! number of steps Results in rc_results.txt.'
t = 0.0 ! initial time
END PROGRAM RCCircuit_Euler
! Open file to store results
OPEN(UNIT=10, FILE='decay_results.txt')

WRITE(10,*) 'Time', 'Atoms'

DO i = 1, steps
! Write current state to file
WRITE(10,*) t, N

PROGRAM RadioactiveDecay_Euler ! Update number of atoms using Euler's method


IMPLICIT NONE N = N - dt * lambda * N

REAL :: N, lambda, t, dt ! Update time


INTEGER :: steps, i t = t + dt
END DO
! Parameters
lambda = 0.01 ! decay constant CLOSE(10)
N = 1000.0 ! initial number of atoms PRINT *, 'Radioactive decay simulation
dt = 0.1 ! time step complete. Results in decay_results.txt.'
steps = 100 ! number of steps
t = 0.0 ! initial time END PROGRAM RadioactiveDecay_Euler
! Open file to store results
OPEN(UNIT=10, FILE='pendulum_results.txt')

WRITE(10,*) 'Time', 'Theta', 'Omega'

DO i = 1, steps
! Write current state to file
WRITE(10,*) t, theta, omega
PROGRAM Pendulum_Euler
IMPLICIT NONE ! Update angular velocity and position
omega = omega - dt * (g / L) * theta
REAL :: theta, omega, t, dt, g, L theta = theta + dt * omega
INTEGER :: steps, i
! Update time
! Parameters t = t + dt
g = 9.81 ! gravitational acceleration (m/s^2) END DO
L = 1.0 ! length of the pendulum (m)
theta = 0.1 ! initial angular displacement (radians) CLOSE(10)
omega = 0.0 ! initial angular velocity (rad/s) PRINT *, 'Pendulum simulation complete. Results in
dt = 0.01 ! time step pendulum_results.txt.'
steps = 1000 ! number of steps
t = 0.0 ! initial time END PROGRAM Pendulum_Euler
! Open file to store results
OPEN(UNIT=10, FILE='coupled_oscillators.txt')
WRITE(10,*) 'Time', 'Position1', 'Position2', 'Velocity1',
'Velocity2'

PROGRAM CoupledOscillators DO i = 1, steps


IMPLICIT NONE ! Write current state to file
WRITE(10,*) t, x1, x2, v1, v2
REAL :: x1, x2, v1, v2, t, dt, k1, k2, m1, m2
INTEGER :: steps, i ! Update velocities and positions using Euler's method
v1 = v1 + dt * (-k1/m1 * x1 + k2/m1 * (x2 - x1))
! Parameters v2 = v2 + dt * (-k2/m2 * (x2 - x1))
m1 = 1.0 ! mass of first block x1 = x1 + dt * v1
m2 = 1.0 ! mass of second block x2 = x2 + dt * v2
k1 = 100.0 ! spring constant for first spring
k2 = 100.0 ! spring constant for second spring ! Update time
dt = 0.01 ! time step t = t + dt
steps = 1000 ! number of steps END DO
x1 = 1.0 ! initial position of first block
x2 = -1.0 ! initial position of second block CLOSE(10)
v1 = 0.0 ! initial velocity of first block PRINT *, 'Coupled oscillators simulation complete. Results
v2 = 0.0 ! initial velocity of second block in coupled_oscillators.txt.'
t = 0.0 ! initial time
END PROGRAM CoupledOscillators
PROGRAM GravitationalTwoBody
IMPLICIT NONE

REAL :: x1, y1, vx1, vy1, x2, y2, vx2, vy2, t, dt, m1, m2, G, r
y2 = 0.0
INTEGER :: steps, i
vx2 = 0.0 ! initial velocity of Moon (m/s)
vy2 = 1022.0 ! tangential velocity of Moon (m/s)
! Parameters
t = 0.0 ! initial time
G = 6.67430E-11 ! Gravitational constant (m^3/kg/s^2)
m1 = 5.972E24 ! mass of Earth (kg)
! Open file to store results
m2 = 7.348E22 ! mass of Moon (kg)
OPEN(UNIT=10, FILE='gravitational_twobody.txt')
dt = 1.0 ! time step (seconds)
WRITE(10,*) 'Time', 'X1', 'Y1', 'X2', 'Y2'
steps = 100000 ! number of steps
DO i = 1, steps
x1 = 0.0 ! initial position of Earth
! Calculate distance between two bodies
y1 = 0.0
r = SQRT((x2 - x1)**2 + (y2 - y1)**2)
vx1 = 0.0 ! initial velocity of Earth
vy1 = 0.0
! Write current state to file
x2 = 3.844E8 ! initial position of Moon (distance to
WRITE(10,*) t, x1, y1, x2, y2
Earth in meters)
! Update velocities using Euler's method
vx1 = vx1 + dt * G * m2 / r**3 * (x2 - x1)
vy1 = vy1 + dt * G * m2 / r**3 * (y2 - y1)
vx2 = vx2 + dt * G * m1 / r**3 * (x1 - x2)
vy2 = vy2 + dt * G * m1 / r**3 * (y1 - y2)

! Update positions
x1 = x1 + dt * vx1
y1 = y1 + dt * vy1
x2 = x2 + dt * vx2
y2 = y2 + dt * vy2

! Update time
t = t + dt
END DO

CLOSE(10)
PRINT *, 'Gravitational two-body simulation complete.
Results in gravitational_twobody.txt.'

END PROGRAM GravitationalTwoBody


DO i = 1, steps
! Boundary conditions: fixed temperature at the ends
PROGRAM HeatDiffusion
T_new(1) = 0.0
IMPLICIT NONE
T_new(N) = 0.0
! Apply Euler's method to update temperature
REAL, DIMENSION(100) :: T, T_new
DO j = 2, N-1
REAL :: dx, dt, alpha, t
T_new(j) = T(j) + alpha * dt / dx**2 * (T(j+1) - 2*T(j)
INTEGER :: i, steps, N
+ T(j-1))
END DO
! Parameters
! Update temperature array
alpha = 0.01 ! thermal diffusivity
T = T_new
N = 100 ! number of grid points
! Write current state to file
dx = 0.1 ! grid spacing
IF (MOD(i,100) == 0) THEN
dt = 0.001 ! time step
DO j = 1, N
steps = 10000 ! number of time steps
WRITE(10,*) j, T(j)
END DO
! Initial condition: temperature spike at the center
END IF
T = 0.0
END DO
T(N/2) = 100.0
CLOSE(10)
PRINT *, 'Heat diffusion simulation complete. Results in
! Open file to store results
heat_diffusion.txt.'
OPEN(UNIT=10, FILE='heat_diffusion.txt')
WRITE(10,*) 'Grid Point', 'Temperature'
END PROGRAM HeatDiffusion
! Open file to store results
OPEN(UNIT=10, FILE='rlc_circuit.txt')
WRITE(10,*) 'Time', 'Charge', 'Current'

DO i = 1, steps
PROGRAM RLCCircuit ! Write current state to file
IMPLICIT NONE WRITE(10,*) t, q, i

REAL :: q, i, t, dt, L, R, C, V, V0 ! Update current and charge using Euler's method


INTEGER :: steps, i i = i + dt * (V0/L - R/L * i - q/(L*C))
q = q + dt * i
! Parameters
L = 0.1 ! inductance (H) ! Update time
R = 1.0 ! resistance (ohms) t = t + dt
C = 1e-6 ! capacitance (F) END DO
V0 = 5.0 ! applied voltage (volts)
dt = 0.001 ! time step CLOSE(10)
steps = 1000 ! number of steps PRINT *, 'RLC circuit simulation complete. Results
q = 0.0 ! initial charge in rlc_circuit.txt.'
i = 0.0 ! initial current
t = 0.0 ! initial time END PROGRAM RLCCircuit
PROGRAM ThermodynamicInterpolation ! Input the temperature at which specific heat needs to be
IMPLICIT NONE interpolated
INTEGER :: n, i, j PRINT *, 'Enter the temperature (T) at which you want to
interpolate Cp: '
REAL :: T, interpolated_Cp
READ *, T
REAL, DIMENSION(100) :: X, Y
REAL :: LagrangePoly ! Lagrange interpolation process
interpolated_Cp = 0.0
! Number of data points DO i = 1, n
PRINT *, 'Enter the number of temperature data points (n): LagrangePoly = 1.0
' DO j = 1, n
READ *, n IF (j /= i) THEN
LagrangePoly = LagrangePoly * (T - X(j)) / (X(i) - X(j))
END IF
! Input temperature (T) and specific heat (Cp) values END DO
PRINT *, 'Enter temperature (T) and corresponding specific interpolated_Cp = interpolated_Cp + LagrangePoly * Y(i)
heat (Cp):' END DO
DO i = 1, n
PRINT *, 'T(', i, '): ' ! Output the interpolated Cp value
READ *, X(i) PRINT *, 'The interpolated specific heat at T = ', T, ' is ',
PRINT *, 'Cp(', i, '): ' interpolated_Cp, ' J/mol·K'
READ *, Y(i)
END PROGRAM ThermodynamicInterpolation
END DO
! Input the bond length for which vibrational frequency needs to be
PROGRAM VibrationalFrequencyInterpolation interpolated
IMPLICIT NONE PRINT *, 'Enter the bond length (r) at which you want to
INTEGER :: n, i, j interpolate ν: '
REAL :: r, interpolated_nu READ *, r
REAL, DIMENSION(100) :: X, Y
REAL :: LagrangePoly ! Lagrange interpolation process
interpolated_nu = 0.0
DO i = 1, n
! Number of data points
LagrangePoly = 1.0
PRINT *, 'Enter the number of bond length data points (n): DO j = 1, n
' IF (j /= i) THEN
READ *, n LagrangePoly = LagrangePoly * (r - X(j)) / (X(i) - X(j))
END IF
! Input bond lengths (r) and vibrational frequencies (ν) END DO
PRINT *, 'Enter bond length (r) and corresponding interpolated_nu = interpolated_nu + LagrangePoly * Y(i)
vibrational frequency (ν):' END DO
DO i = 1, n
! Output the interpolated ν value
PRINT *, 'r(', i, '): ' PRINT *, 'The interpolated vibrational frequency at r = ', r, ' Å is ',
READ *, X(i) interpolated_nu, ' cm⁻¹'
PRINT *, 'ν(', i, '): '
READ *, Y(i) END PROGRAM VibrationalFrequencyInterpolation
END DO
! Input the distance for which gravitational potential needs to be
PROGRAM GravitationalPotentialInterpolation interpolated
IMPLICIT NONE PRINT *, 'Enter the distance (r) at which you want to interpolate V:
INTEGER :: n, i, j '
REAL :: r, interpolated_V READ *, r
REAL, DIMENSION(100) :: X, Y
REAL :: LagrangePoly ! Lagrange interpolation process
interpolated_V = 0.0
DO i = 1, n
! Number of data points
LagrangePoly = 1.0
PRINT *, 'Enter the number of distance data points (n): ' DO j = 1, n
READ *, n IF (j /= i) THEN
LagrangePoly = LagrangePoly * (r - X(j)) / (X(i) - X(j))
! Input distances (r) and gravitational potentials (V) END IF
PRINT *, 'Enter distance (r) in AU and corresponding END DO
gravitational potential (V):' interpolated_V = interpolated_V + LagrangePoly * Y(i)
DO i = 1, n END DO
PRINT *, 'r(', i, '): '
! Output the interpolated V value
READ *, X(i) PRINT *, 'The interpolated gravitational potential at r = ', r, ' AU is
PRINT *, 'V(', i, '): ' ', interpolated_V
READ *, Y(i)
END DO END PROGRAM GravitationalPotentialInterpolation
! Input the position at which the electric field needs to be
PROGRAM ElectricFieldInterpolation interpolated
IMPLICIT NONE PRINT *, 'Enter the position (x) at which you want to interpolate E:
INTEGER :: n, i, j '
REAL :: x, interpolated_E READ *, x
REAL, DIMENSION(100) :: X, Y
! Lagrange interpolation process
REAL :: LagrangePoly
interpolated_E = 0.0
DO i = 1, n
! Number of data points LagrangePoly = 1.0
PRINT *, 'Enter the number of position data points (n): ' DO j = 1, n
READ *, n IF (j /= i) THEN
LagrangePoly = LagrangePoly * (x - X(j)) / (X(i) - X(j))
! Input positions (x) and electric field values (E) END IF
PRINT *, 'Enter position (x) in cm and corresponding END DO
interpolated_E = interpolated_E + LagrangePoly * Y(i)
electric field (E):'
END DO
DO i = 1, n
PRINT *, 'x(', i, '): ' ! Output the interpolated E value
READ *, X(i) PRINT *, 'The interpolated electric field at x = ', x, ' cm is ',
PRINT *, 'E(', i, '): ' interpolated_E, ' N/C'
READ *, Y(i)
END DO END PROGRAM ElectricFieldInterpolation
program bisection_method
implicit none ! Print the results
real(8) :: a, b, tol, root if (converged) then
integer :: max_iter, iter print *, "Root found: ", root
logical :: converged print *, "Number of iterations: ", iter
! Function declaration else
external :: f print *, "Method did not converge in ", max_iter, " iterations."
! Input the interval [a, b], tolerance, and maximum iterations end if
print *, "Enter the interval [a, b]:"
read *, a, b contains
print *, "Enter the tolerance:" ! Function to define the equation f(x) = 0
read *, tol real(8) function f(x)
print *, "Enter the maximum number of iterations:" real(8), intent(in) :: x
read *, max_iter f = x**3 - 4.0*x - 9.0 ! Example: f(x) = x^3 - 4x - 9
! Call the bisection method end function f
call bisection(a, b, tol, max_iter, root, iter, converged)
do while (iter < max_iter)
! Subroutine implementing the bisection method mid = (a + b) / 2.0
subroutine bisection(a, b, tol, max_iter, root, iter, converged) fmid = f(mid)
real(8), intent(in) :: a, b, tol iter = iter + 1
integer, intent(in) :: max_iter if (abs(fmid) < tol .or. abs(b - a) / 2.0 < tol) then
real(8), intent(out) :: root root = mid
integer, intent(out) :: iter converged = .true.
logical, intent(out) :: converged return
real(8) :: fa, fb, mid, fmid end if
fa = f(a) if (fa*fmid < 0.0) then
fb = f(b) b = mid
iter = 0 fb = fmid
converged = .false. else
if (fa*fb > 0.0) then a = mid end if
print *, "The function has the same sign at both endpoints." fa = fmid end do
return root = mid ! If max iterations reached, return
the best estimate
end if
end subroutine bisection
end program bisection_method

You might also like