Fortran Tutorials2 (1)
Fortran Tutorials2 (1)
Fortran - Introduction
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
• By default, if not explicitly declared, the variables starting with the letters
I,J,K,L,M&N are assumed to be integer type
• 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
• Output
IX = i
THETA = 3.141593
COS(THETA) = -0.9999999999678646
1.0, 3
Initialization of Variables
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
• 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
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
3
Find the largest of three number
Named Block IF Construct
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
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:
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
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
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
sum = 0
• 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
• 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
! Update time
t = t + dt
! 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
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)'
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.
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.
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
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
! Deallocate arrays
DEALLOCATE(T, P, diff_table)
! Deallocate arrays
DEALLOCATE(T, C, diff_table)
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
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')
DO i = 1, steps
! Write current state to file
WRITE(10,*) t, N
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'
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.'
DO i = 1, steps
PROGRAM RLCCircuit ! Write current state to file
IMPLICIT NONE WRITE(10,*) t, q, i