L2 Fortran
L2 Fortran
Objectives
Program name
Subprogram(s)
IF conditional statement
Topic: Fortran Programming
Output
Sum 73.5999985
Topic: Fortran Programming
Output
Sum 73.5999985
DO Loops
Syntax
Example of DO Loops
do x = 1, 10
m=1
! block 1
n=10
enddo
x=1
do x= m, n*x
m=1
! block 1
n=10
enddo
do x = m, n
! block 1
enddo
m=1
n=10
do x = m, n, 1
! block 1
enddo
Topic: Fortran Programming
Syntax
Usually both CYCLE and EXIT statements are used along with IF condition
Topic: Fortran Programming
do i = 1, 5
if (mod(i, 2) == 0) then
cycle ! Skip even numbers
end if
write (*,*) "Current value:", i
end do
Topic: Fortran Programming
do i = 1, 10
if (i > 5) then
exit ! Exit the loop when i exceeds 5
end if
write (*,*) "Current value:", i
end do
Topic: Fortran Programming
DO WHILE Loops
Syntax
! block statements
END DO
Topic: Fortran Programming
i=0
n=10
do while ( i < n)
! block 1
enddo
n=10
i=20
do while (.not. i < n)
! block 1
enddo
Topic: Fortran Programming
Infinite DO Loops
Syntax
do
DO count = count + 1
! block statements write (*,*) "Loop iteration:",
count
If (logical expression) then if (count >= 5) then
exit exit ! Exit the loop
endif end if
end do
! block statements
END DO
Topic: Fortran Programming
nested DO loops
Syntax
END DO
! block 5 statements
END DO
Topic: Fortran Programming
Output
Sum 5050.00000
Topic: Fortran Programming
Output
sum = 0
do i = 1, 5
sum = sum + i
end do
Output
do i = 1, 3
do j = 1, 2
write (*,*) i, " * ", j, " = ", (i * j)
end do
end do
Topic: Fortran Programming
Output
do i = 3, 2
write (*,*) i
end do
Topic: Fortran Programming
Write a program that computes the distance a ball travels when thrown at a certain
speed (v0) and angle (θ). Given the initial velocity input by the user, calculate the range
for angles ranging from 5 to 85 degrees in increments of 5 degrees.
Range = -(2*v02/g)cosθsinθ
Tips
∙ Don’t worry about declaring variables initially. Identify the main part of the program
and start writing
∙ All real numbers should be in double precision (add d0 in the end), eg. 10.0d0
∙ Always use indentation, leave black spaces to improve readability
∙ Always use ‘parameter’ in case when assigning the values to integer datatype
∙ Use internal functions to convert datatypes, eg. real(x)
∙ Read compiler error messages more carefully
∙ For debugging, use ‘write’ statement at several places in the program and check for
the output
∙
Topic: Fortran Programming