Lecture IV More complicated Fortran programming

Download Report

Transcript Lecture IV More complicated Fortran programming

REVIEW of Lecture 4

Relational operators:
<, <=, >, >=, ==, /=
 return result of .TRUE. or .FALSE
 lower precedence than all arithmetic operators
2 + 7 >= 3 * 3  .TRUE.

There is no associativity
a < b < c  illegal

7/16/2015
Note that == means “is equal to” but = means
“assign the value on the right”
comp208 Computers in Engineering
1
REVIEW of lecture 4 (cont.)
Logical Operators
.NOT.
High
.AND.
.OR.
.EQV., .NEQV.
Low
They all associate from left to right, except .NOT.
INTEGER :: age=34, old=92, young=16
age==56 .or. .not.(old/=92)
7/16/2015
comp208 Computers in Engineering
2
REVIEW of Lecture 4 (cont.)

Simplest form
IF (logical expression) single statement

Simpler form
IF (logical expression) THEN
block of statements
END IF

IF-THEN-ELSE-ENDIF statement
IF (logical-expression) THEN
first statement block, s_1
ELSE
second statement block, s_2
END IF
7/16/2015
comp208 Computers in Engineering
3
REVIEW of Lecture 4 (cont.)

Complex form
IF (logical expression 1) THEN
block 1
ELSEIF (logical expression 2) THEN
block 2
...
ELSEIF (logical expression N) THEN
block N-1
[ELSE
block N]
ENDIF
7/16/2015
comp208 Computers in Engineering
4
Area of a Triangle
Heron’s formula gives the area of a triangle in terms of the
lengths of its sides.
To use it, we must make sure that the sides form a triangle.
There are two necessary and sufficient conditions:
1.
2.
All side lengths must be positive
The sum of any two sides must be greater than the third
If these conditions are met, the formula is:
Area = SQRT(s*(s-a)*(s-b)*(s-c)),
where a, b and c are the lengths of the sides
and s is half the perimeter.
7/16/2015
comp208 Computers in Engineering
5
Area of a Triangle
! -----------------------------------------------------! Compute the area of a triangle using Heron's formula
! -----------------------------------------------------PROGRAM HeronFormula
IMPLICIT NONE
REAL
:: a, b, c
! three sides
REAL
:: s
! half of perimeter
REAL
:: Area
! triangle area
LOGICAL :: Cond_1, Cond_2
! two logical conditions
READ(*,*)
a, b, c
Cond_1 = (a > 0.) .AND. (b > 0.) .AND. (c > 0.0)
Cond_2 = (a+b > c) .AND. (a+c > b) .AND. (b+c > a)]
IF (Cond_1 .AND. Cond_2) THEN
s
= (a + b + c) / 2.0
Area = SQRT(s*(s-a)*(s-b)*(s-c))
WRITE(*,*) "Triangle area = ", Area
ELSE
WRITE(*,*) "ERROR: this is not a triangle!“
END IF
END PROGRAM HeronFormula
7/16/2015
comp208 Computers in Engineering
6
Lecture IV More
complicated Fortran
programming
Yi Lin
Sept 13, 2005
7/16/2015
comp208 Computers in Engineering
7
IF statement example

Prints a season associated with a given
month in terms of value. If the value of the
integer month is not in the range 1-12, print
“not a month!”





7/16/2015
1, 2, 3: Winter
4, 5: Spring
6, 7, 8: Summer
9, 10: Fall
11, 12: Winter
comp208 Computers in Engineering
8
IF statement example (cont.)
INTEGER::month
READ(*,*) month !input an integer from keyboard
IF (month ==4 .OR. month==5) THEN
WRITE(*,*) “Spring”
ELSEIF (month >=6 .AND. month <=8) THEN
WRITE(*,*) “Summer”
ELSEIF (month==9 .OR. Month==10) THEN
WRITE(*,*) “FALL”
ELSEIF (month==11 .OR. month==12 .OR. (month>=1 .AND. month<=3)) THEN
WRITE(*,*) “WINTER”
ELSE
WRITE(*,*) “Not a month!”
ENDIF
7/16/2015
comp208 Computers in Engineering
9
SELECT CASE statement


The SELECT CASE construct provides an alternative to a
series of repeated IF ... THEN ... ELSE IF statements.
Syntax:
SELECT CASE( expression )
CASE( value 1)
block 1
...
CASE (value i)
block I
…
[CASE DEFAULT
block default]
END SELECT
7/16/2015
comp208 Computers in Engineering
10
SELECT CASE statement

Semantics




7/16/2015
Firstly evaluate expression. The result of expression may
be of type character, logical or integer. Value must be of the
same type as the result of expression
If the value of the expression is value I, execute block I.
If the value of the expression does not match any of values
listed, evaluate block default.
After one of block has been executed, continue to execute
statements following END SELECT
comp208 Computers in Engineering
11
SELECT CASE statement
INTEGER::month
READ(*,*) month !input an integer from keyboard
SELECT CASE(month)
CASE (1)
WRITE(*,*) “WINTER”
CASE (2)
WRITE(*,*) “WINTER”
CASE (3)
WRITE(*,*) “WINTER”
CASE (4)
WRITE(*,*) “Spring”
CASE (5)
WRITE(*,*) “Spring”
CASE (6)
WRITE(*,*) “Summer”
CASE (7)
WRITE(*,*) “Summer”
CASE (8)
WRITE(*,*) “Summer”
CASE (9)
WRITE(*,*) “FALL”
CASE (10)
WRITE(*,*) “FALL”
CASE (11)
WRITE(*,*) “WINTER”
CASE (12)
WRITE(*,*) “WINTER”
CASE DEFAULT
WRITE(*,*) “Not a month!”
END SELECT
7/16/2015
comp208 Computers in Engineering
12
SELECT CASE statement
To
avoid redundancy, use
CASE (value1, value2, …, valuei)
Block of statements
Instead
of
CASE (value1)
Block of statements, S
CASE (value2)
Block of statements, S
….
CASE (valuei)
Block of statements, S
7/16/2015
They are the same statements
comp208 Computers in Engineering
13
SELECT CASE statement

More aggressively, if value1, value2, …, and
valuei are a consecutive sequence of integer,
e.g., 1, 2, 3, 4. Use this:
CASE (value1:valuei)
Block of statements

In which, value1 is the minimum and valuei is
the maximum value.
7/16/2015
comp208 Computers in Engineering
14
SELECT CASE statement
example
Can be INTEGER, CHARACTER, LOGICAL
No REAL
INTEGER::month
READ(*,*) month !input an integer from keyboard
SELECT CASE(month)
(value1, value2)
CASE (4,5)
WRITE(*,*) “Spring”
CASE (6:8)
(min:max) i.e., 6, 7, 8
WRITE(*,*) “Summer”
CASE (9,10)
WRITE(*,*) “FALL”
(value1, value2,
CASE (11, 12, 1:3) THEN
WRITE(*,*) “WINTER”
CASE DEFALUT
WRITE(*,*) “Not a month!”
END SELECT
7/16/2015
comp208 Computers in Engineering
min:max)
15
Repetition, DO statement


A count controlled loop uses a control clause to repeat a block of
statements a predefined number of times:
Syntax:
DO count = start, stop [,step]
block of statements
END DO

The control clause is made up of the following:





7/16/2015
count is an integer variable and is used as the 'control'.
start is an integer value (or expression) indicating the initial value of count.
stop is an integer value (or expression) indicating the final value of count.
step is an integer value (or expression) indicating the increment value of
count. The step is optional and has a default value of 1 if omitted.
Count variable is not allowed to change within the loop
comp208 Computers in Engineering
16
DO statement
Semantics
1.
2.
3.
1.
2.
3.
4.
5.
7/16/2015
First assign the variable, count, an integer value as
start
Compare variables count and stop.
If start does not exceed stop,
execute the statements in the block.
After finishing statements, count = count + step (if
step is not specified, it is 1 by default) .
Go back to step 2.
Else, continue to execute statements following END
DO
End IF
comp208 Computers in Engineering
17
DO statement examples
Example 1:
DO i=1, 10, 1
WRITE(*,*) i !write numbers 1, 2, …, 10
END DO
Example 2:
DO i=1, 10 ! Default step = 1
WRITE(*,*) i !write numbers 1, 2, …, 10
END DO
7/16/2015
comp208 Computers in Engineering
18
DO statement examples (cont.)
Example 3:
DO i=1, 10, 2 ! i increased by 2 for each step
WRITE(*,*) i !write numbers 1,3,5,7,9
END DO

At the last step,



7/16/2015
i=9, write to the screen “9”
i=i+step=9+2=11
11 > 10, terminate the loop
comp208 Computers in Engineering
19
DO statement examples (cont.)

Step is negative. “Exceed” means “smaller than”.
Example 4:
DO j=10,2,-2 ! j decreased by 2
WRITE(*,*) j !write even numbers 10,8,6,4,2
END DO
7/16/2015
comp208 Computers in Engineering
20
DO statement examples (cont.)

What if start > stop and step is positive? Or
What if start < stop and step is negative?
Example 4:
DO j=1, 10, -1 ! Start < stop and Step = -1
WRITE(*,*) j
END DO

Do nothing
7/16/2015
comp208 Computers in Engineering
21
DO statement example
start

Given two integer A
and B, calculate the
sum of integers from
A to B inclusively.

Sum=0, i=A
.TRUE.
(i.e., B >= X >=A)
i>B
.FALSE.
Sum=sum+i
End
7/16/2015
comp208 Computers in Engineering
i=i+1
22
Accumulation example
Program Accumulation
IMPLICIT NONE
INTEGER::A,B,i, sum=0
write(*,*) "Input A, B:"
READ(*,*) A,B
DO i=A,B,1
sum=sum+i
END DO
write(*,*) "sum[A,B]=",sum
END program
7/16/2015
comp208 Computers in Engineering
23
DO statement, CONTINUE

CONTINUE

The execution of the current step will be
stopped and continue to the next loop
DO i=1,10
if(i==8) CONTINUE
next step
! Step 8 stopped here and & go to
WRITE(*,*) i !write numbers 1 to 10 except 8
END DO
7/16/2015
comp208 Computers in Engineering
24
Accumulation example
revisited
Program Accumulation
IMPLICIT NONE
INTEGER::A,B,i,sum=0
write(*,*) "Input A, B:"
READ(*,*) A,B
Calculate the sum of integers
between A and B, and
dividable by 2 and 3.
DO i=A,B,1
if(MOD(i,2)!=0 .OR. MOD(i,3)!=0) CONTINUE;
sum=sum+i
END DO
write(*,*) "sum[A, B]=",sum
END program
7/16/2015
comp208 Computers in Engineering
25
DO statement, EXIT

EXIT

The loop will be terminated and exit.
DO i=1,10
if(i == 8) EXIT !Loop terminated when i==8
WRITE(*,*) i !write numbers 1 to 7 only
END DO
7/16/2015
comp208 Computers in Engineering
26
Infinite DO loop

In the absence of a control clause the block of
statements is repeated indefinitely.
DO
block
END DO

The block of statements will be repeated forever, or
at least until somebody stops the program. In order
to terminate this type of loop the programmer must
explicitly transfer control to a statement outside the
loop.
7/16/2015
comp208 Computers in Engineering
27
Infinite DO loop example
INTEGER::I=0
DO
IF(I>10) EXIT ! Loop terminated at I==11
WRITE(*,*) I ! WRITE number 1 to 10
I=I+1
! I increased by 1 at each step
END DO
Without IF(i>10) EXIT, the program will not be able to stop.
7/16/2015
comp208 Computers in Engineering
28
Examples in previous
midterms and/or finals
PROGRAM P4
IMPLICIT NONE
INTEGER :: I ,K
K=1
DO I = 12, 0, -1
WRITE (*,*) “Inside DO loop”
K = K +1
END DO
How many times will the
above program print
“Inside DO loop”?
a) 0
b) 1
c) 12
d) 13
e) None of the above
END PROGRAM P4
7/16/2015
comp208 Computers in Engineering
29
Example in previous exams
What does the following program output
when presented with the following input
1. 4 5
2. 5 5
3. 10 20
Select the best answer:
PROGRAM QUESTION2
IMPLICIT NONE
INTEGER:: A,X,Y,N
a=0
READ (*,*) X,Y
DO N = 1,5,2
1)
IF (X==Y) THEN
A=X
A=A+A+X
ELSEIF(X<Y) THEN
A = 3*X + A
ELSE
A=X
END IF
Y=Y-X
END DO
WRITE (*,*) A,X,Y
END PROGRAM QUESTION2
7/16/2015
4
4
4
-7
10
10
2) 4
4
5
7
10
10
3) 4
4
5
5
10
10
4) 5
5
9
9
10
10
5) None of the above
comp208 Computers in Engineering
-7
4
-10
7
-11
10
-7
-10
-10
-9
-9
-10
30
Character processing



Character constants
 E.g. “Hello world!”
Declaration
 CHARACTER::varName
! One single character
 CHARACTER(len=int):: varName ! String with length=int
 E.g., CHARACTER::c=“A” ! C=“A”
 E.g., CHARACTER(len=5):: str1=“Hello world!”
 E.g., CHARACTER(len=20)::str2=“Hello world!”
 E.g., CHARACTER(20)::str3=“Hello world!”
If length too short  the rightmost characters are truncated


E.g., str1 = “Hello”
if length too long  the rightmost characters are filled with spaces.

7/16/2015
E.g., str2= “Hello world!#########”
comp208 Computers in Engineering
31
Character processing (cont.)

Concatenation “//”
CHARACTER (len=24) :: name
CHARACTER (len=6) :: surname
surname = “Fredman”
name = “Prof.#”// “Nathan#”//surname
Name=“Prof.#Nathan#Friedman###”
# represents white space here.
7/16/2015
comp208 Computers in Engineering
32
Character comparison
Dictionary index

Certain rules are applied when comparing
characters or strings (is “A” greater than “B”?)




7/16/2015
String comparison requires strings of the same length.
When comparing strings of different lengths, the shorter
is padded with blanks (right side).
The comparison is from left to right.
Comparison is character by character.
The comparison ends either when a difference is found
or the end of the string is reached.
comp208 Computers in Engineering
33
Character comparison (cont.)

Character comparison follows a collating
sequence, typically:
0 < 1 < 2 < ... < 9
A < B < ... < Z
a < b < ... < z
ANSI standard:
blank < numerals < upper case < lower case.
7/16/2015
comp208 Computers in Engineering
34
Character comparison (cont.)

Example 1:



test = “abz” > “aBc”
test=.TRUE. Comparison stops at the second character “b”
> “B”. It doesn’t matter the order of the pair of the third
characters.
Example 2




7/16/2015
test = “Alexis” > “Alex”
The right string becomes “Alex##” (# : white space)
The first four characters are the same...
character “i” is greater than blank, test=.TRUE.
comp208 Computers in Engineering
35
Character intrinsic functions





LEN(string) returns the length of a character string
INDEX(string,sustring) finds the location of a
substring in another string, returns 0 if not found
TRIM(string) returns the string with the trailing
blanks removed.
CHAR(int) converts an integer into a character
ICHAR(c) converts a character into an integer
7/16/2015
comp208 Computers in Engineering
36
Character intrinsic functions
(cont.)

Examples
CHARACTER(len=12) :: surname, firstname
INTEGER :: length, pos
...
length = LEN(surname) ! len=12
firstname = “Walter”
pos = INDEX(firstname, “al”) ! pos=2
firstname = “Fred”
pos = INDEX(firstname, “al”) ! pos=0
length = LEN(TRIM(firstname)) ! len=4
7/16/2015
comp208 Computers in Engineering
37
Character intrinsic functions
(cont.)


It is possible to convert character to integer or vice
versus. However, the conversion between
characters and integers is machine dependent.
Example:
INTEGER :: i
CHARACTER :: ch=“a”
...
i=ICHAR(CHAR(i))
ch=CHAR(ICHAR(ch))
7/16/2015
! i=? In WinXP
comp208 Computers in Engineering
38
SELECT CASE example

Given a grade in terms of “A,B,C,D,F”, output the corresponding
marks in terms of 100%
CHARACTER::grade
READ(*,*) grade
SELECT CASE(grade)
CASE (“A”)
WRITE(*,*) “90-100”
CASE (“B”)
WRITE(*,*) “80-90”
CASE (“C”)
WRITE(*,*) “70-80”
CASE (“D”)
WRITE(*,*) “60-70”
CASE (“F”)
WRITE(*,*) “<60”
CASE DEFAULT
WRITE(*,*) “unrecognized grade!”
END SELECT
7/16/2015
comp208 Computers in Engineering
39