home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 15 / CDACTUAL15.iso / cdactual / program / pascal / PAS_TUT.ZIP / CHAP04.TXT < prev    next >
Encoding:
Text File  |  1991-02-04  |  16.1 KB  |  354 lines

  1.  
  2.  
  3.  
  4.                                                         Chapter 4
  5.                                        LOOPS & CONTROL STRUCTURES
  6.  
  7.  
  8. Every program we have examined to this point has been a simple one
  9. pass through with no statements being repeated.  As in all other
  10. languages, Pascal has extensive capabilities to do looping and
  11. conditional branching.  We will look at these now.
  12.  
  13.  
  14. THE FOR LOOP
  15. _________________________________________________________________
  16.  
  17. We will start with what may be the easiest       ================
  18. structure to understand, the for loop.  This is    LOOPDEMO.PAS
  19. used to repeat a single Pascal statement any     ================
  20. number of times we desire.  Load LOOPDEMO.PAS
  21. and we will discuss the loops presented there. 
  22.  
  23. The example illustrated in lines 13 and 14, is the simplest loop
  24. and does nothing more than execute a Writeln 7 times.  We have
  25. three new reserved words, for, to, and do which are used as shown. 
  26. Any simple variable of type integer, byte, or char can be used for
  27. the loop index but due to the requirement that everything must be
  28. defined prior to use in Pascal, the loop index must be defined in
  29. a var statement.  Following the reserved word do is any single
  30. Pascal statement that will be repeated the specified number of
  31. times.  Note that the loop is an incrementing loop but substitution
  32. of downto for to will make it a decrementing loop as is illustrated
  33. in the last example in this program.  It should be pointed out that
  34. the loop control variable can only be incremented or decremented
  35. by 1 each time through the loop in Pascal.
  36.  
  37.  
  38. A COMPOUND PASCAL STATEMENT
  39. _________________________________________________________________
  40.  
  41. The example given in lines 18 through 22 contains our first
  42. compound Pascal statement.  It was mentioned in Chapter 1 that the
  43. begin end pair of reserved words could be used to mark the limits
  44. of a compound statement.  In this case, the single compound
  45. statement starting with the begin at the end of line 18 and
  46. extending through and including the end statement in line 22 is the
  47. single Pascal statement that will be executed 10 times.  A second
  48. variable Total has been introduced to simply add another operation
  49. to the loop.  Any valid Pascal operation can be performed within
  50. the begin end pair, including another for loop, resulting in nested
  51. loops to whatever depth you desire. 
  52.  
  53. The third example shows how the char type variable could be used
  54. in a for loop.  Pascal requires that the loop index, the starting
  55. point, and the ending point all be of the same type or it will
  56. generate an error message during compilation.  In addition, they
  57.  
  58.                                                          Page 4-1
  59.  
  60.                          Chapter 4 - Loops and Control Structures
  61.  
  62. must be variables of type integer, byte, or char.  The starting
  63. point and ending point can be constants or expressions of arbitrary
  64. complexity.
  65.  
  66. The fourth example is a decrementing loop as mentioned earlier. 
  67. It uses the reserved word downto, and should be self explanatory.
  68.  
  69.  
  70.  
  71. THE IF STATEMENT
  72. _________________________________________________________________
  73.  
  74. Pascal has two conditional branching               ==============
  75. capabilities, the if and the case statements.        IFDEMO.PAS
  76. We will look at the simplest of the two now, the   ==============
  77. if statement.  Load IFDEMO.PAS for an onscreen
  78. look at the if then pair of reserved words first
  79. illustrated in lines 11 and 12.  Any condition that can be reduced
  80. to a boolean answer is put between the if then pair of words.  If
  81. the resulting expression resolves to TRUE, then the single Pascal
  82. statement following the reserved word then is executed, and if it
  83. resolves to FALSE, then the single statement is skipped over.  Of
  84. course, you can probably guess that the single statement can be
  85. replaced with a compound statement bracketed with a begin end pair
  86. and you are correct.  Study example 1 and you will see that the
  87. line will always be printed in this particular fragment because
  88. Three is equal to One + Two.  It is very difficult to come up with
  89. a good example without combining some of the other control
  90. structures but we will do so in the next example program.
  91.  
  92. The second example in lines 14 through 19, is similar to the first
  93. but has the single statement replaced with a compound statement and
  94. should be simple for you to understand.
  95.  
  96. The third example in lines 21 through 24, contains a new reserved
  97. word, else.  When the if condition is FALSE, the single statement
  98. following the word then is skipped and if a semicolon is
  99. encountered, the if clause is totally complete.  If instead of a
  100. semicolon, the reserved word else is encountered, then the single
  101. Pascal statement following else is executed.  One and only one of
  102. the two statements will be executed every time this if statement
  103. is encountered in the program.  Examination of the third example
  104. should clear this up in your mind.
  105.  
  106. Notice that the Pascal compiler is looking for either a semicolon
  107. to end the if, or the reserved word else to continue the logic. 
  108. It is therefore not legal to use a semicolon immediately preceding
  109. the reserved word else.  You will get a compiler error if you
  110. include the semicolon.  This is a common error, but easy to fix,
  111. so you will get used to writing it correctly.
  112.  
  113.  
  114.  
  115.  
  116.  
  117.                                                          Page 4-2
  118.  
  119.                          Chapter 4 - Loops and Control Structures
  120.  
  121. THE IF-THEN-ELSE BLOCK
  122. _________________________________________________________________
  123.  
  124. Put on your thinking cap because the next principle is difficult
  125. to grasp at first but will suddenly clear up and be one of the most
  126. useful facts of Pascal programming.  Since the entire if then else
  127. block of code is itself a single Pascal statement by definition,
  128. it can be used anywhere that an executable statement is legal
  129. without begin end separators.  This is shown in the fourth example
  130. of the IFDEMO.PAS Pascal example program.  Lines 27 through 30
  131. comprise a single Pascal statement, and lines 32 through 35
  132. comprise another.  The if statement begun in line 26 therefore has
  133. a single statement in each of its branches, and it is a single
  134. Pascal statement itself beginning in line 26 and ending in line 35. 
  135. Reread this paragraph until you understand it completely, because
  136. it is a very important concept.
  137.  
  138. The if then else construct is one of the most used, most useful,
  139. and therefore most important aspects of Pascal.  For this reason
  140. you should become very familiar with it.
  141.  
  142. Try changing some of the conditions in the example program to see
  143. if you can get it to print when you expect it to for your own
  144. practice.  When you are ready, we will go on to a program with
  145. loops and conditional statements combined and working together.
  146.  
  147.  
  148. LOOPS AND IFS TOGETHER
  149. _________________________________________________________________
  150.  
  151. Load LOOPIF.PAS and study it for a few minutes.    ==============
  152. It contains most of what you have studied so far     LOOPIF.PAS
  153. and should be understandable to you at this        ==============
  154. point.  It contains a loop (lines 7 through 17)
  155. with two if statements within it (lines 8 & 9
  156. and lines 10 through 16), and another loop (lines 11 through 15)
  157. within one of the if statements.
  158.  
  159. You should make careful note of the formatting used here.  The
  160. begin is at the end of the line which starts the control and the
  161. end is lined up under the control word such that it is very clear
  162. which control word it is associated with.  All statements within
  163. each control structure are indented three spaces which greatly adds
  164. to the readability.  You will develop your own clear method of
  165. formatting your code in time but until then it is suggested that
  166. you follow this example which is written in a manner which is
  167. acceptable within the general Pascal programming community.
  168.  
  169. An easily made error should be pointed out at this time.  If an
  170. extraneous semicolon were put at the end of the if statement in
  171. line 8, the code following the statement would always be executed
  172. because the null statement (the nothing statement between the then
  173. and the semicolon) would be the conditional statement.  The
  174. compiler would not generate an error and you would get no warning. 
  175.  
  176.                                                          Page 4-3
  177.  
  178.                          Chapter 4 - Loops and Control Structures
  179.  
  180. Add a semicolon at the end of line 8 to see the error.  Of course,
  181. you will need to compile and execute the program to see line 9
  182. print for all 10 values of Count.
  183.  
  184.  
  185. FINALLY, A MEANINGFUL PROGRAM
  186. _________________________________________________________________
  187.  
  188. Load TEMPCONV.PAS and study its structure.       ================
  189. Notice the header block that defines the program   TEMPCONV.PAS
  190. and gives a very brief explanation of what the   ================
  191. program does.  This program should pose no
  192. problem to you in understanding what it does
  193. since it is so clearly documented.  If you study the style of
  194. indenting used here, you will learn to appreciate the clarity
  195. afforded by the indentation.  Compile and run this program and you
  196. will have a list of Centigrade to Fahrenheit temperature
  197. conversions with a few added notes.  
  198.  
  199. Load, examine, and run DUMBCONV.PAS for a good   ================
  200. example of poor variable naming.  The structure    DUMBCONV.PAS
  201. of the program is identical to the last program  ================
  202. and when you run it, you will see that it is
  203. identical in output, but compared to the last
  204. program, it is difficult to understand what it does by studying the
  205. listing.  We studied UGLYFORM.PAS in chapter 2 of this tutorial and
  206. it illustrated really stupid formatting that nobody would ever use. 
  207. The poor choice of variable names and lack of comments in the
  208. present program is nearly as unreadable, but many programmers are
  209. content to write code similar to this example.  You should be
  210. conscious of good formatting style and naming conventions from the
  211. start and your programs will be clear, easy to understand, and will
  212. run efficiently.  This program, like the last should be easily
  213. understood by you, so we will go on to our next Pascal control
  214. structure.
  215.  
  216.  
  217. THE REPEAT UNTIL LOOP
  218. _________________________________________________________________
  219.  
  220. The next two Pascal constructs are very similar because they are
  221. both indefinite loops (indefinite because they are not executed a
  222. fixed number of times).  One of the loops is evaluated at the top
  223. and the other at the bottom.  It will probably be easier to start
  224. with the repeat until construct which is the loop that is evaluated
  225. at the bottom.
  226.  
  227. Examine the file named REPEATLP.PAS to see  an   ================
  228. example of a repeat loop.  Two more reserved       REPEATLP.PAS
  229. words are defined here, namely repeat and until. ================
  230. This rather simple construct simply repeats all
  231. statements between the two reserved words until
  232. the boolean expression following the until is found to be TRUE. 
  233. This is the only expression in Pascal that operates on a range of
  234.  
  235.                                                          Page 4-4
  236.  
  237.                          Chapter 4 - Loops and Control Structures
  238.  
  239. statements rather than a single statement and begin end delimiters
  240. are not required.  
  241.  
  242. A word of caution is in order here.  Since the loop is executed
  243. until some condition becomes TRUE, it is possible that the
  244. condition will never be TRUE and the loop will never terminate. 
  245. It is up to you, the programmer, to insure that the loop will
  246. eventually terminate.  Compile and execute REPEATLP.PAS to observe
  247. the output.
  248.  
  249.  
  250. THE WHILE LOOP
  251. _________________________________________________________________
  252.  
  253. The file WHILELP.PAS contains an example of       ===============
  254. another new construct, the while loop.  This        WHILELP.PAS
  255. uses the while do reserved words and will         ===============
  256. execute one Pascal statement (or one compound
  257. statement bounded with begin and end)
  258. continuously until the boolean expression between the two words
  259. becomes FALSE. 
  260. This loop is also indeterminate and could, like the repeat until
  261. loop, never terminate.  You should therefore exercise care in using
  262. it. 
  263.  
  264. There are two basic differences in the last two loops.  The repeat
  265. until loop is evaluated at the bottom of the loop and must
  266. therefore always go through the loop at least one time.  The while
  267. loop is evaluated at the top and may not go through even once. 
  268. This gives you flexibility when choosing the loop to do the job at
  269. hand.  Compile, run, and examine the output from the example
  270. program WHILELP.PAS.
  271.  
  272.  
  273. THE CASE STATEMENT
  274. _________________________________________________________________
  275.  
  276. The final control structure introduces one more reserved word,
  277. case.  The case construct actually should be included with the if
  278. statement since it is a conditional execution statement, but we
  279. saved it for last because it is rather unusual and will probably
  280. be used less than the others we have discussed in this chapter.
  281.  
  282. The case statement is used to select one of many ================
  283. possible simple Pascal statements to execute       CASEDEMO.PAS
  284. based on the value of a simple variable.  Load   ================
  285. the file CASEDEMO.PAS and observe the program
  286. for an example of a case statement.  The
  287. variable between the case and of reserved words in line 9 is the
  288. variable used to make the selection and is called the case
  289. selector.  Following that, the various selections are listed as a
  290. possible value or range, followed by a colon, a single Pascal
  291. statement, and a semicolon for each selector.  Following the list
  292. of selections, an else can be added to cover the possibility that
  293.  
  294.                                                          Page 4-5
  295.  
  296.                          Chapter 4 - Loops and Control Structures
  297.  
  298. none of the selections were executed.  Finally, an end statement
  299. is used to terminate the case construct.  Note that this is one of
  300. the few places in Pascal that an end is used without a
  301. corresponding begin.
  302.  
  303. The example file uses Count for the case selector, prints the
  304. numbers one through five in text form, and declares that numbers
  305. outside this range are not in the allowable list.  The program
  306. should be self explanatory beyond that point.  Be sure to compile
  307. and run this example program.
  308.  
  309. Load and display the sample program BIGCASE.PAS   ===============
  310. for another example of a case statement with a      BIGCASE.PAS
  311. few more added features.  This program uses the   ===============
  312. identical structure as the previous program but
  313. in line 11 a range is used as the selector so
  314. that if the value of Count is 7, 8, or 9 this selection will be
  315. made.  In line 12, three different listed values will cause
  316. selection of this part of the code.  Of greater importance are the
  317. compound statements used in some of the selections.  If the
  318. variable Count has the value of 2, 4, or 6, a compound statement
  319. will be executed and if the value is 3, a for loop is executed. 
  320. If the value is 1, an if statement is executed which will cause a
  321. compound statement to be executed.  In this case the if statement
  322. will always be executed because TRUE will always be true, but any
  323. Boolean expression could be used in the expression.  Be sure to
  324. compile and run this program, then study the output until you
  325. understand the result thoroughly.
  326.  
  327. This brings us to the end of chapter 4 and you now have enough
  328. information to write essentially any program desired in Pascal. 
  329. You would find however, that you would have a few difficulties if
  330. you attempted to try to write a very big program without the topics
  331. coming up in the next few chapters.  The additional topics will
  332. greatly add to the flexibility of Pascal and will greatly ease
  333. programming with it.
  334.  
  335.  
  336. PROGRAMMING EXERCISES
  337. _________________________________________________________________
  338.  
  339. 1.   Write a program that lists the numbers from 1 to 12 and writes
  340.      a special message beside the number representing your month
  341.      of birth.
  342.  
  343. 2.   Write a program that lists all of the numbers from 1 to 12
  344.      except for the numbers 2 and 9.
  345.  
  346.  
  347.  
  348.  
  349.  
  350.  
  351.  
  352.  
  353.                                                          Page 4-6
  354.