Lesson Topics | |
Logical Expressions | Go To |
If ... Then ... Else | Character Variables |
Stop | Do Loops |
Labels | |
View Demos | Download Demos |
# 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 | # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 |
Main Fortran Page |
We look at more of the commonly used features and commands of Fortran.
Relation/Connective | Meaning |
.lt. | less than |
.gt. | greater than |
.le. | less than or equal to |
.ge. | greater than or equal to |
.eq. | equals |
.ne. | not equal to |
.and. | and |
.or. | or |
.not. | not |
.xor. | "exclusive" or (i.e., only one is true) |
.eqv. | equivalent (i.e., same truth values) |
.neqv. | not equivalent |
1) | if (x .gt. 0) print *, "x is positive" | |
2) | if (x .ge. y .and. x .ge. z) go to 40 | |
3) | if (x .ge. 0) then | |
y = sqrt(x) | ||
print *, y, " squared = ", x | ||
end if | ||
4) | if (x .ge. 0) then | |
y = sqrt(x) | ||
print *, y, " squared = ", x | ||
else | ||
print *, "x has no square root" | ||
end if | ||
5) | if (x .gt. 0) then | |
print *, "x is positive" | ||
y = sqrt(x) | ||
else if (x .lt. 0) then | ||
print *, "x is negative" | ||
go to 60 | ||
else if (x .eq. 0) then | ||
print *, "x is zero" | ||
y = 0 | ||
end if |
if (n .lt. 0) then | |
print *, "Error - your age cannot be negative!" | |
stop | |
end if . |
Do not confuse stop and end. Use end only as the very last statement in the program, and use stop only to terminate the program before this last statement. Violating these rules will fatally confuse the compiler - it regards an end statement as the program's physical end.
if (x .lt. 0) go to 10 | |
print *, "The square root of x is ", sqrt(x) | |
stop | |
10 | print *, "x is negative and has no square root" |
indicates that "name" is a character variable holding no more than 20 symbols, while "ans" is a character variable holding only one symbol.
A string in Fortran may be enclosed in either double quotes, as in "hello", or in single quotes, as in 'goodbye'.
sum = 0 | | | sum = 0 | |||
do i = 1, 10 | | | do 5 i = 1, 10 | |||
sum = sum + i ** 2 | | | sum = sum + i ** 2 | |||
end do | | | 5 | continue | ||
print *, "The sum is", sum | | | print *, "The sum is", sum |
The end do and continue statements serve only to identify the end of the loop. The limits of the loop may be variables as well as numbers (e.g.: do i = m, n). As in Basic you may indicate a step size, which can be positive or negative. For example, the statement
specifies that the loop variable i run over the odd numbers 1, 3, 5, 7, 9.
Loops can be nested, and nested loops can end on the same continue statement (but not on the same end do statement). Here are two instances of nested loops assigning the entries of a 10 x 10 matrix:
do i = 1, 10 | | | do 5 i = 1, 10 | |
do j = 1, 10 | | | do 5 j = 1, 10 | |
a(i,j) = i + j | | | a(i,j) = i + j | |
end do | | | 5 | continue |
end do | | |