home *** CD-ROM | disk | FTP | other *** search
/ Chip 1995 March / CHIP3.mdf / programm / prog1 / chap05.txt < prev    next >
Encoding:
Text File  |  1991-07-01  |  24.7 KB  |  588 lines

  1.  
  2.  
  3.  
  4.                                                         Chapter 5
  5.                                                CONTROL STRUCTURES
  6.  
  7.  
  8.  
  9. THE SIMPLEST LOOP IN ADA
  10. _________________________________________________________________
  11.  
  12. We will start with the simplest loop in Ada, the ================
  13. infinite loop which is illustrated in lines 13     LOOPDEMO.ADA
  14. through 19 of the program named LOOPDEMO.ADA.    ================
  15. The variable named Index is initialized to the
  16. value of 1 prior to entering the loop, and the
  17. loop itself is given in lines 14 through 19.  The loop begins with
  18. the reserved word loop and ends with the two reserved words end
  19. loop.  Any number of executable statements are placed between these
  20. two delimiters and the loop is repeated continuously until
  21. something causes the program to jump out of the loop.  In this
  22. case, the variable Index is incremented each time through the loop,
  23. and when it reaches a value of 5, the exit statement is executed
  24. which causes control to jump out of the loop and begin executing
  25. instructions immediately following the end of the loop.  The words
  26. exit and when are two more reserved words.
  27.  
  28. The expression following the exit when reserved words must evaluate
  29. to a BOOLEAN result and when the result is TRUE, the loop is
  30. exited, but as long as the result is FALSE, the loop execution will
  31. continue.  Note that the exit statement can be placed anywhere in
  32. the loop and as many conditional exits as needed can be placed
  33. within the loop.
  34.  
  35. The statements illustrated in lines 21 through 27 are an
  36. alternative form of loop exit which uses the if statement which we
  37. have not yet studied.  The if form of exit is such a common form
  38. of usage that it had to be included here as one of the simplest
  39. types of loops.  Note that the if exit can be placed anywhere in
  40. the loop and as many as needed can be used within the loop.  The
  41. if statement will be fully explained later in this chapter.
  42.  
  43.  
  44.  
  45. THE exit STATEMENT
  46. _________________________________________________________________
  47.  
  48. There is a subtle difference between the exit in line 18 and the
  49. exit in line 26.  The exit in line 18 is conditional because it is
  50. only executed if the condition evaluates to TRUE.  The exit in line
  51. 26 however, is unconditional since the exit will be taken anytime
  52. control reaches the word exit.  Keep in mind that an exit is used
  53. only to exit a loop, it is not used for any other construct in Ada.
  54.  
  55.  
  56.  
  57.  
  58.                                                          Page 5-1
  59.  
  60.                                    Chapter 5 - Control Structures
  61.  
  62. THE while LOOP
  63. _________________________________________________________________
  64.  
  65. The while loop is identical to the simple loop except for the
  66. addition of a test prior to the reserved word loop.  The test is
  67. done at the beginning of the loop so it is slightly less general
  68. than the simple loop, but it also requires a BOOLEAN expression as
  69. part of the construct.  This loop is illustrated in lines 30 to 34
  70. of the present program.  In line 30, "while Count < 5" is called
  71. the iteration clause.
  72.  
  73.  
  74. THE for LOOP
  75. _________________________________________________________________
  76.  
  77. The loops studied so far in this example program use an
  78. indeterminate number of passes since they calculate their own
  79. limits as they progress through the loop.  It is important to point
  80. out that the BOOLEAN expressions are evaluated on every pass
  81. through the loop.  The for loop, however, has its limits evaluated
  82. one time and the number of passes through the loop is completely
  83. defined before the first pass through the loop is begun.
  84.  
  85. The for loop is illustrated in lines 36 to 39 where the control
  86. consists of a few words prior to the reserved word loop.  In this
  87. case the loop control is the variable Index and the range of the
  88. variable is 1 through 4.  The loop will be executed four times,
  89. each time with a larger number for the variable Index, since the
  90. loop index is always incremented by one.  There is no provision
  91. for an increment of any other value in Ada.  The reserved words for
  92. and in are used in the manner shown for all for loops.  They serve
  93. to bracket the loop index, in this case named Index, and the range
  94. of the index, in this case 1 through 4 inclusive.
  95.  
  96. Because the type INTEGER is so commonly used for the loop index,
  97. if the type is not specifically stated, it will be defaulted to the
  98. type INTEGER.  This is to make it easier to code the majority of
  99. loops.
  100.  
  101. Note that the loop parameters do not need to be of type INTEGER,
  102. but the loop index and both range limits must be of the same type.
  103. Note also that the value of the loop iterator is not available
  104. after loop termination.  The loop iterator ceases to exist
  105. completely when the loop is completed.  (There is good reason for
  106. this as we will see when we complete our study of the next example
  107. program.)
  108.  
  109.  
  110. THE BACKWARDS for LOOP
  111. _________________________________________________________________
  112.  
  113. There is a slight variation to the for loop as illustrated in lines
  114. 41 through 44, where the loop index is decremented on each pass
  115. through the logic.  The word reverse is another reserved word and
  116.  
  117.                                                          Page 5-2
  118.  
  119.                                    Chapter 5 - Control Structures
  120.  
  121. serves to indicate the backward counting nature of this loop.  Note
  122. that the range is expressed in ascending order, but the actual
  123. execution begins at 8 and decrements by 1 on each pass until it
  124. reaches 5, where it quits after the pass through the loop with
  125. Count set to 5.
  126.  
  127.  
  128. THE EMPTY LOOP
  129. _________________________________________________________________
  130.  
  131. Continuing in the program named LOOPDEMO.ADA, the loop in lines 46
  132. to 48 is given to illustrate that it is possible to write a loop
  133. that does absolutely nothing.  It may seem like a silly thing to
  134. do, but there are cases, when using tasking, that it is necessary
  135. to do nothing in a loop.  It is of more importance at this point
  136. to illustrate that Ada is so picky, you are not allowed to write
  137. an empty loop, but are required to inform the compiler that you
  138. really did mean for the loop to be empty by including the reserved
  139. word null within the loop.
  140.  
  141. One other point must be made before we leave this program.
  142. Everything from line 14 through line 19 comprises a single Ada
  143. statement, by definition.  It is definitely a complex statement,
  144. but for purposes of discussion, it is one Ada statement.  Likewise,
  145. lines 22 through 27 constitute a single Ada statement, as do lines
  146. 30 through 34.  This is an important concept to understand because
  147. of the block nature of Ada and we will have more to say about it
  148. later.
  149.  
  150. Be sure to compile and execute this program and be sure you
  151. understand exactly what each loop does.
  152.  
  153.  
  154. SLIGHTLY MORE COMPLEX for STATEMENTS
  155. _________________________________________________________________
  156.  
  157. Examine the program named MORELOOP.ADA for a     ================
  158. few examples of more complex but much more         MORELOOP.ADA
  159. versatile for loops.  The loops illustrate a few ================
  160. of the flexibilities designed into Ada to allow
  161. for more efficient programming.  The first
  162. example has two new concepts, the first being that the loop
  163. variable, Index, is not declared in the definition part of the
  164. program, and secondly the range is defined by a type rather than
  165. variable or constant limits.
  166.  
  167. Considering the first point, the loop index in a for loop does not
  168. require explicit declaration, but will be implicitly declared by
  169. the program, used during the duration of the loop, and discarded
  170. when the loop terminates.  The final value of the loop index is not
  171. available for use after the loop terminates, and this is true
  172. regardless of whether the index is explicitly or implicitly
  173. declared. (We will see shortly that it is always implicitly
  174. declared by the Ada system.)  The Ada language designers gave
  175.  
  176.                                                          Page 5-3
  177.  
  178.                                    Chapter 5 - Control Structures
  179.  
  180. compiler writers freedom on how and when the loop index is
  181. incremented rather than dictating what the final value would be.
  182. It is a simple rule to remember that you can not depend on having
  183. the final value of the loop index when you terminate the loop.  If
  184. you need the final value, you must copy it into some other
  185. variable.
  186.  
  187.  
  188.  
  189. THE LOOP INDEX AND LIMITS MUST AGREE IN TYPE
  190. _________________________________________________________________
  191.  
  192. The second point brought out above is the fact that the loop range
  193. is given as a type.  The type given, MY_TYPE, has a defined range
  194. of 10..13, so it should be no real problem seeing what the loop
  195. index range is.  Moreover, since the type of the individual values
  196. of MY_TYPE are of the type universal_integer, the implicit loop
  197. index, named Index, will also be of type universal_integer.  Ada
  198. will pick the correct types for you.
  199.  
  200. A final point about the first loop in this program must be made.
  201. The loop index in this for loop, as well as in any for loop, will
  202. be treated as a constant within the loop, so you cannot assign a
  203. new value to it.  The looping mechanism itself will be the only way
  204. that the loop index can be changed in value.
  205.  
  206.  
  207.  
  208. OUR FIRST ATTRIBUTES IN USE
  209. _________________________________________________________________
  210.  
  211. In chapter 3, we took a brief look at attributes, but didn't really
  212. look at uses for them.  In the loop in lines 30 through 34, we have
  213. the range once again defined as the limits of the type named
  214. MY_TYPE but this time we explicitly name the first and last values
  215. of the type by using the attributes.  The method depicted in line
  216. 24 is more concise, but both methods lead to the same result.  If
  217. you wanted to loop from the first element to some midpoint, for
  218. example, the second method gives you a way to use one of the
  219. endpoints of the range.
  220.  
  221. A point that should be mentioned again is the fact that the
  222. contents of lines 24 through 28 constitute a single Ada statement,
  223. as do the contents of lines 30 through 34 inclusive.
  224.  
  225.  
  226.  
  227. CALCULATED LOOP RANGE LIMITS
  228. _________________________________________________________________
  229.  
  230. The loop in lines 36 through 40 has range limits that are not
  231. static but that are calculated when the loop is entered.  In this
  232. case, the calculations are all based on constants, but they could
  233. be based on variables of any arbitrary degree of complexity.  If
  234.  
  235.                                                          Page 5-4
  236.  
  237.                                    Chapter 5 - Control Structures
  238.  
  239. they are based on one or more variables, there is a subtle point
  240. that you must understand.  If one or more of the variables are
  241. changed within the loop, the range does not change accordingly,
  242. because the loop range limits are calculated only once, and it
  243. occurs when the loop is entered.
  244.  
  245. It should be clear that the loop range is 2 through 5 for this
  246. particular loop.
  247.  
  248.  
  249. A DOUBLY NESTED for LOOP
  250. _________________________________________________________________
  251.  
  252. Lines 42 through 52 contain two nested for loops with an addition
  253. to the outer loop.  The identifier Named_Loop is a loop name which
  254. applies to the outer loop.  Notice that the name also follows the
  255. corresponding end loop for that loop, resulting in a named loop.
  256. In lines 45 and 46 we have a conditional statement that says if the
  257. product of the Height and the Width are equal to 12, we are to exit
  258. the loop that is named Named_Loop.  Without the name given we would
  259. only exit the loop currently in effect, the inner one defined by
  260. the loop index Width, but since we mention the name, we exit the
  261. loop with the given name, and exit both loops.  By adding a name
  262. to a loop, you can exit out of as many nested levels as you desire
  263. with a single exit statement.
  264.  
  265. Once again, according to the definition of Ada, lines 42 through
  266. 52 constitute a single statement, and lines 44 through 51 also
  267. constitute a single Ada statement, although it is embedded within
  268. the outer statement.  To continue, each of lines 48, 49, and 50
  269. constitute a single Ada statement, and each of these are embedded
  270. within both of the outer statements.  Recall that each Ada
  271. statement is supposed to terminate with a semicolon, then go back
  272. and reread this paragraph with that in mind.
  273.  
  274.  
  275. A CLOSE LOOK AT THE LOOP INDEX
  276. _________________________________________________________________
  277.  
  278. In line 54, we assign the value of 157 to the variable named
  279. Special_Index and use that variable name for the loop index for the
  280. following loop.  After the loop is terminated, we display the value
  281. of the variable to see what the final value is, and when we run the
  282. program we find that the value did not change from that assigned,
  283. namely 157.  This would suggest that even if we think we are
  284. explicitly defining the loop index variable, the system is actually
  285. making up an entirely new variable, using it, and throwing it away
  286. after the loop is terminated.  Ada defines a loop variable as an
  287. automatic variable which is generated when needed and discarded
  288. when it is no longer needed.  More will be said about automatic
  289. variables later.  The important point to grasp from this is that
  290. Ada actually implicitly declares all loop variables for us.
  291.  
  292.  
  293.  
  294.                                                          Page 5-5
  295.  
  296.                                    Chapter 5 - Control Structures
  297.  
  298. LOOPS ARE IMPORTANT
  299. _________________________________________________________________
  300.  
  301. You will have many opportunities to use all three forms of the
  302. loops discussed here, so it would pay you to study these loops
  303. until you are sure of what they are doing.
  304.  
  305. Note the similarity of the three loops, and the fact that each is
  306. a complete Ada statement terminated with a semicolon.  When we
  307. study the next two controls, you will see that they are very
  308. similar, and fit the same pattern.
  309.  
  310.                                  loop <...> end loop;
  311.      while <BOOLEAN expression>  loop <...> end loop;
  312.      for <loop index> in <range> loop <...> end loop;
  313.  
  314. Compile and execute this program taking care to observe the value
  315. of the variable named Special_Index when the loop is complete.
  316.  
  317.  
  318.  
  319. NOW FOR CONDITIONAL STATEMENTS
  320. _________________________________________________________________
  321.  
  322. We will spend some time now examining the        ================
  323. program named IFDEMO.ADA and studying the           IFDEMO.ADA
  324. conditional statements.  Notice here, that we    ================
  325. don't even try to define any variables, but we
  326. will let the system generate them for us as
  327. implicit loop indices.  The Ada statement contained in lines 11
  328. through 21 is a for loop which we are now familiar with so we will
  329. use it to study how the if statement works.  Notice that we display
  330. the value of Index, then use it in the first if statement in lines
  331. 14 through 16.  This statement says that if the value stored in
  332. Index is less than 4, then execute the statements between the
  333. reserved words then and end if.  In this case, we display the
  334. message in line 15 on the monitor.  If the value stored in Index
  335. is not less than 4, we ignore the statement between the reserved
  336. words and go directly to line 17, where we encounter another if
  337. statement.  This one displays a different line on the monitor if
  338. the value stored in Index is greater than 5.  This is the simplest
  339. kind of if statement, and you will find it to be extremely useful,
  340. in fact, you used it in the previous two example programs.
  341.  
  342. Moving ahead to the next loop, the one in lines 24 through 32, we
  343. find a more elaborate conditional, the if then else statement.  In
  344. this case, if the value of Index is less than 15, one message is
  345. displayed and if not, a different message is displayed.  In the
  346. prior loop, we used an if statement where a message may or may not
  347. have been displayed, but in this one, we use an if statement where
  348. one of the messages will be displayed every time.  This, of course,
  349. is very similar to other programming languages.
  350.  
  351.  
  352.  
  353.                                                          Page 5-6
  354.  
  355.                                    Chapter 5 - Control Structures
  356.  
  357. NOW FOR THE MULTIWAY if STATEMENT
  358. _________________________________________________________________
  359.  
  360. The loop in the statement contained in lines 35 through 47 is a bit
  361. more involved since there are several possibilities for selection
  362. of the line to be displayed.  The word elsif is another reserved
  363. word.  In this case, one and only one of the statements will be
  364. executed during each pass through the loop.  The reserved word else
  365. is optional, and if it were not there, it would be possible that
  366. none of the conditions would be met and therefore none of the
  367. messages would be output.  As many statements as desired can be
  368. placed between each of the reserved words such that a selection
  369. could cause a large number of statements to be executed
  370. sequentially.
  371.  
  372. The last statement, given in lines 54 through 70, gives an
  373. illustration of nesting of loop and if statements.  It should cause
  374. you no difficulty to understand the nesting and when you compile
  375. and run this program, you should have a good understanding of the
  376. output.
  377.  
  378.  
  379. THE MULTIWAY CONDITIONAL CONSTRUCT
  380. _________________________________________________________________
  381.  
  382. Examine the program named CASEDEMO.ADA for an    ================
  383. example of a program with a case statement, the    CASEDEMO.ADA
  384. multiway conditional statement in Ada.  Lines 11 ================
  385. through 23 comprise a loop with a case statement
  386. contained in it.  Lines 15 through 21 contain
  387. the actual case statement.  The variable How_Many is the case
  388. selector variable and each time we pass through the loop, we enter
  389. the case statement with a different value stored in the variable
  390. How_Many.  When How_Many has the value of 4 through 6, we select
  391. the first path, and that path only, when it has the value of 7 or
  392. 9, we select the second path, etc.  The vertical bar is the or
  393. operator here, and means if we have either of these cases, do this
  394. list of statements.  The case statement is composed of the reserved
  395. words case, is, when, and end case in the manner shown.  All cases
  396. must be accounted for in some way since it is an error to enter the
  397. case with a value of the case selector variable for which there is
  398. not something defined for it to do.
  399.  
  400.  
  401.  
  402. WHAT IS THE => OPERATOR?
  403. _________________________________________________________________
  404.  
  405. The "=>" operator is used in many places in an Ada program which
  406. we will see as we progress through this tutorial.  It can be
  407. loosely defined as a "do this" operator, because in most places it
  408. can be read as "do this".  For example in line 16, the line can be
  409. read "when How_Many is 4 through 6 do this Put statement".
  410.  
  411.  
  412.                                                          Page 5-7
  413.  
  414.                                    Chapter 5 - Control Structures
  415.  
  416. A special case is provided which is the others case.  It is
  417. optional, but if it is included, it must be the last one listed.
  418. This is illustrated in the other example in this program, the
  419. example in lines 30 through 40.  This program is an illustration
  420. of more complex operations in each of the case branches, and it is
  421. expected that you should have no difficulty discerning the
  422. operation of each of the cases.  This is one of the places where
  423. a null statement can be very useful as in line 38 where we really
  424. want to do nothing and can explicitly tell the compiler so.  Be
  425. sure to compile and execute this program after you are sure you
  426. understand it.  The case statement occurs rather infrequently in
  427. programming, but you will use it, so you should understand it
  428. thoroughly.
  429.  
  430. This would be a good time to repeat a list which was given earlier
  431. in this chapter with the if and case statements added to illustrate
  432. the symmetry of the control structures and how well thought out
  433. they really are.
  434.  
  435.                                  loop <...> end loop;
  436.      while <BOOLEAN expression>  loop <...> end loop;
  437.      for <loop index> in <range> loop <...> end loop;
  438.      if   <condition>            then <...> end if;
  439.      case <selector>             is   <...> end case;
  440.  
  441.  
  442.  
  443. THE EVIL GOTO STATEMENT
  444. _________________________________________________________________
  445.  
  446. The program named GOTODEMO.ADA illustrates use   ================
  447. of the goto statement, a statement that has        GOTODEMO.ADA
  448. fallen into ill repute among software engineers  ================
  449. in recent years.  This is because the goto can
  450. be used very abusively, leading to nearly
  451. unreadable spaghetti code.  There may be instances when use of the
  452. goto statement will result in very clear code, and when those cases
  453. arise, it should be used.  It has been proven that it is possible
  454. to write any logic without resorting to the goto statement by using
  455. only iteration (looping), conditional branching, and sequential
  456. statements and every effort should be made to rely on only these
  457. three elements.
  458.  
  459. When Ada was being developed, the developers considered leaving the
  460. goto statement completely out of the language, but it was included
  461. for a very nebulous reason.  It was felt that after Ada became a
  462. popular language, there would be a need to translate existing
  463. programs from older languages, such as FORTRAN, into Ada using
  464. automatic translators.  Such a job would be impossible without the
  465. goto statement, so it was included in the Ada language.  Modula-2
  466. is an example of a language structured very much like Ada, but
  467. without a goto statement defined as part of the language.
  468.  
  469.  
  470.  
  471.                                                          Page 5-8
  472.  
  473.                                    Chapter 5 - Control Structures
  474.  
  475. The goto is available as a part of the Ada language and is
  476. illustrated in the present example program.  It should be no
  477. surprise to you that goto is another reserved word.  The rather
  478. messy looking double "<<" and ">>" enclose the label to which you
  479. wish to jump and the rest should be easy for you to discern.  Be
  480. sure to compile and run this program.
  481.  
  482.  
  483.  
  484. FINALLY, A USEFUL PROGRAM
  485. _________________________________________________________________
  486.  
  487. Examine the program named TEMPCONV.ADA for an    ================
  488. example of a program that really does do           TEMPCONV.ADA
  489. something useful, it generates a table of        ================
  490. Centigrade to Fahrenheit temperature
  491. conversions, and it outputs a special message at
  492. the freezing point of water and another at the boiling point of
  493. water.  Notice the program definition in the header that defines
  494. exactly what it does.  You should have no trouble understanding
  495. every detail of this program, except of course for the rather
  496. cryptic code in lines 8, 9, 13, and 14.  Although we have had a
  497. brief introduction to these, we will cover the details of them
  498. later in this tutorial.
  499.  
  500.  
  501.  
  502. POOR CHOICE OF VARIABLE NAMES
  503. _________________________________________________________________
  504.  
  505. Compile and run TEMPCONV.ADA, then examine the   ================
  506. program named DUMBCONV.ADA for an example that     DUMBCONV.ADA
  507. uses some poor choices of variable names and     ================
  508. omits the comments.  This program is the same
  509. program that you just studied because it does
  510. exactly the same thing, but I am sure you will find it a little
  511. harder to follow since the names are not very useful in helping
  512. you understand what it is doing.  In the beginning of this
  513. tutorial, we studied a program named UGLYFORM.ADA which was
  514. absolutely ridiculous in style.  No serious programmer would write
  515. such a program as that, but many programmers seem to be happy using
  516. a style similar to the present example.
  517.  
  518. You should begin, even at this early point in your Ada programming
  519. development, to develop good formatting skills.  Remember that Ada
  520. was designed to be written once and read many times, so the extra
  521. time spent keying in long, meaningful identifiers will be worth it
  522. to your colleagues when they find a need to study your code.
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.  
  530.                                                          Page 5-9
  531.  
  532.                                    Chapter 5 - Control Structures
  533.  
  534. PROGRAMMING EXERCISES
  535. _________________________________________________________________
  536.  
  537. 1.   Write a program with looping and conditional statements that
  538.      will output the year and your age during each year from the
  539.      time you were born until you were 21.  Include a special note
  540.      the year you started school and another note the year you
  541.      graduated from High School.  Example output follows;
  542.  
  543.         In 1938, I was 0 years old.
  544.         In 1939, I was 1 years old.
  545.              ...
  546.              ...
  547.         In 1943, I was 5 years old, and started School.
  548.              ...
  549.              etc.
  550.  
  551. 2.   Rewrite exercise 1 using a case statement.
  552.  
  553.  
  554.  
  555.  
  556.  
  557.  
  558.  
  559.  
  560.  
  561.  
  562.  
  563.  
  564.  
  565.  
  566.  
  567.  
  568.  
  569.  
  570.  
  571.  
  572.  
  573.  
  574.  
  575.  
  576.  
  577.  
  578.  
  579.  
  580.  
  581.  
  582.  
  583.  
  584.  
  585.  
  586.  
  587.  
  588.                                                         Page 5-10