• No results found

12 Making decisions (1)

Chapter 12 Making Decisions (1)

One special case of the IF statement may be useful. From time to time there may only be one statement to execute in a BLOCK IF:–

IF(MONTH.EQ.2)THEN NDAYS=28 ENDIF

In these circumstances, it is possible to compress the statements to a single logical if:–

IF(MONTH.EQ.2)NDAYS=28

This has exactly the same effect. Whichever form you use is a matter of taste – though the general form has the advantage of flexibility.

Note that some symbols available on the keyboard e.g. > >= < <= <> =

are not acceptable as a shorthand way of denoting the relational operators. Use of logical expressions and logical variables (something not mentioned so far) are covered again in a later chapter on additional data types.

The ‘IF expression THEN statements ENDIF’ is called a BLOCK IF con- struct. There is a simple extension to this provided by the ELSE statement. Consider the following example:–

IF (BALNCE.GE.0.0) THEN .

. draw money out of the bank .

. ELSE

.

. borrow money from a friend .

ENDIF .

. Buy a round of drinks .

In this instance, one or other of the blocks will be executed. Then execution will continue with the statements after the ENDIF statement (in this case buy a

round).

There is yet another extension to the BLOCK IF which allows ELSEIF state - ment. Consider the following example:–

IF (TODAY.EQ.MONDAY) THEN .

ELSEIF (TODAY.EQ.TUSDAY) THEN .

ELSEIF (TODAY.EQ.WEDDAY) THEN .

ELSEIF (TODAY.EQ.THRDAY) THEN .

ELSEIF (TODAY.EQ.FRIDAY) THEN .

ELSEIF (TODAY.EQ.SATDAY) THEN .

ELSEIF (TODAY.EQ.SUNDAY) THEN .

ELSE

there has been an error. The variable TODAY has taken on an illegal value.

ENDIF

Note that, as soon as one of the logical expressions is true, the rest of the test is skipped, and execution continues with the statements after the ENDIF. This implies that a construction like:–

IF(I.LT.2)THEN . . ELSEIF(I.LT.1)THEN . . ELSE . ENDIF

is inappropriate. If I is less than 2, the latter condition will never be tested. The ELSE statement has been used here to aid in trapping errors or exceptions. This is recommended practice. A very common error in programming is to assume that the data is in certain well-specified ranges. The program then fails when the data goes outside this range. It makes no sense to have a day other than Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday.

Examples

• This program is straightforward, with a simple structure. The roots of the quadratic are either real, equal and real, or complex depending on the magni- tude of the term B ** 2 – 4 * A * C. The program tests for this term being greater than and less than zero, it assumes that the only other case is equality to zero (from the mechanics of a computer, floating point equality is rare, but, we are safe in this instance).

PROGRAM QROOTS

REAL A,B,C,TERM,A2,ROOT1,ROOT2 C

C A B AND C ARE THE COEFFICIENTS OF THE TERMS C A*X**2+B*X+C

C FIND THE ROOTS OF THE QUADRATIC, ROOT1 AND ROOT2 C

PRINT*,’ GIVE THE COEFFICIENTS A, B AND C’ READ*,A,B,C

TERM = B*B – 4.*A*C A2 = A*2.

C IF TERM < 0, ROOTS ARE COMPLEX C IF TERM = 0, ROOTS ARE EQUAL

C IF TERM > 0, ROOTS ARE REAL AND DIFFERENT IF(TERM.LT.0.0)THEN

PRINT*,’ ROOTS ARE COMPLEX’ ELSEIF(TERM.GT.0.0)THEN

TERM = TERM**0.5 ROOT1 = (–B+TERM)/A2 ROOT2 = (–B–TERM)/A2

PRINT*,’ ROOTS ARE ’,ROOT1,’ AND ’,ROOT2 ELSE

ROOT1 = –B/A2

PRINT*,’ ROOTS ARE EQUAL, AT ’,ROOT1 ENDIF

END

This next example is also straightforward. It demonstrates that, even if the

conditions on the IF statement are involved, the overall structure is easy to determine. The comments and the names given to variables should make the program self-explanatory. Note the use of integer division to identify leap years.

PROGRAM DATE

INTEGER YEAR,N,MONTH,DAY,T C

C CALCULATES DAY AND MONTH FROM YEAR AND DAY-WITHIN-YEAR C T IS AN OFFSET TO ACCOUNT FOR LEAP YEARS

C

PRINT*,’ YEAR, FOLLOWED BY DAY WITHIN YEAR’

READ*,YEAR,N

C CHECKING FOR ORDINARY LEAP YEARS IF(((YEAR/4)*4).EQ.YEAR)THEN

T=1 ELSE

T=0 ENDIF

C CHECKING FOR LEAP YEARS AT CENTURIES IF (((YEAR/400)*400.EQ.YEAR) + .OR.((YEAR/100)*100.EQ.YEAR))THEN T=T ELSE T=0 ENDIF

C ACCOUNTING FOR FEBRUARY IF(N.GT.(59+T))THEN DAY=N+2-T ELSE DAY=N ENDIF MONTH=(DAY+91)*100/3055 DAY=(DAY+91)-(MONTH*3055)/100 MONTH=MONTH-2

PRINT*,’ CALENDAR DATE IS ’,DAY,MONTH,YEAR END

Summary

• Decisions are a key part of problem solving, and of Fortran.

• Decisions are made on the basis of an IF statement, where some condition is evaluated as either true or false, and then a particular course of action is fol - lowed.

• The IF construct can be expanded quite elegantly into the IF-THEN-ELSE- ENDIF type of structure (the Block If), where the alternatives are grouped in a kind of parenthetical structure.

• Besides the ELSE, another statement, the ELSEIF may be used.

Problems

The physical world has many examples where processes require some threshold to be overcome before they begin operation: critical mass in nuclear reactions, a given slope to be exceeded before friction is overcome, and so on. Unfortu - nately, most of these sorts of calculations become rather complex and not really appropriate here. The following problem trys to restrict the range of calculation, whilst illustrating the possibilities of decision making.

1. If a cubic equation is expressed as z3 + a2z2 + a1z + a0 = 0 and we let q = a1/3 –(a2 a2 )/ 9 and r = (a1a2-3a0)/6-(a2a2a2)/27

we can determine the nature of the roots as follows: q3 + r2 > 0; one real root and a pair of complex; q3 + r2 = 0; all roots real, and at least two equal; q3 + r2 < 0; all roots real;

Incorporate this into a suitable program, to determine the nature of the roots of a cubic from suitable input.

2. The form of breaking waves on beaches is a continuum, but for convenience we commonly recognise three major types: surging, plunging and spilling. These may be classified empirically by reference to the wave period, T (sec - onds), the breaker wave height, Hb (metres), and the beach slope, m. These

three variables are combined into a single parameter, B, where B = Hb/(gmT2)

g is the gravitational constant (981 cm sec–2). If B is less than .003, the break - ers are surging; if B is greater than 0.068, they are spilling, and between these values, plunging breakers are observed.

(i) On the east coast of New Zealand, the normal pattern of waves is swell waves, with wave heights of 1 to 2 metres, and wave periods of 10 to 15 seconds. During storms, the wave period is generally shorter, say 6 to 8 sec - onds, and the wave heights higher, 3 to 5 metres. The beach slope may be taken as about 0.1. What changes occur in breaker characteristics as a storm builds up?

(ii) Similarly, many beaches have a concave profile. The lower beach generally has a very low slope, say less than 1 degree (m=0.018), but towards the high tide mark, the slope increases dramatically, to say 10 degrees or more (m=0.18). What changes in wave type will be observed as the tide comes in? 3. Personal taxation is usually structured in the following way:–

no taxation on the first m0 units of income;

taxation at t1% on the next m1 units;

taxation at t2% on the next m2 units;

taxation at t3% on anything above.

For some reason, this is termed progressive taxation. Write a generalised pro - gram to determine net income after tax deductions. Write out the gross income, the deductions and the net income. You will have to make some realistic esti - mates of the tax thresholds mi and the taxation levels ti. You could use this sort

of model to find out how sensitive revenue from taxation was in relation to cosmetic changes in thresholds and tax rates.

4. The specific heat capacity of water is 2009 J kg–1 K–1; the specific latent heat of fusion (ice/water) is 335 kJ kg–1, and the specific latent heat of vapori - zation (water/steam) is 2500 kJ kg–1. Assume that the specific heat capacity of ice and steam are identical to that of water. Write a program which will read in two temperatures, and will calculate the energy required to raise (or lower) ice, water or steam at the first temperature, to ice, water or steam at the second. Take the freezing point of water as 273 K, and its boiling point as 373 K. For those happier with Celsius, 0o C is 273 K, while 100o c is 373 K. One calorie is 4.1868 J, and for the truly atavistic, 1 BTU is 1055 J (approximately).

13