home *** CD-ROM | disk | FTP | other *** search
/ Shareware Overload / ShartewareOverload.cdr / progm / ctutor1.zip / CHAP03.TXT < prev    next >
Text File  |  1989-11-10  |  17KB  |  410 lines

  1.  
  2.  
  3.  
  4.  
  5.                                                     Chapter 3
  6.                                               PROGRAM CONTROL
  7.  
  8.  
  9. THE WHILE LOOP
  10. ____________________________________________________________
  11.  
  12. The C programming language has several structures for looping
  13. and conditional branching.  We will cover them all in this
  14. chapter and we will begin with the while loop.
  15.  
  16. The while loop continues to loop while some condition is true.
  17. When the condition becomes false, the looping is discontinued. 
  18. It therefore does just what it says it does, the name of the
  19. loop being very descriptive. 
  20.  
  21. Load the program WHILE.C and display it for     =============
  22. an example of a while loop.  We begin with a       WHILE.C
  23. comment and the program entry point main(),     =============
  24. then go on to define an integer variable
  25. count within the body of the program.  The
  26. variable is set to zero and we come to the while loop itself. 
  27. The syntax of a while loop is just as shown here.  The keyword
  28. while is followed by an expression of something in
  29. parentheses, followed by a compound statement bracketed by
  30. braces.  As long as the expression in parenthesis is true, all
  31. statements within the braces will be repeatedly executed.  In
  32. this case, since the variable count is incremented by one
  33. every time the statements are executed, it will eventually
  34. reach 6.  At that time the statement will not be executed, and
  35. the loop will be terminated.  The program control will resume
  36. at the statement following the statements in braces. 
  37.  
  38. We will cover the compare expression, the one in parentheses,
  39. in the next chapter.  Until then, simply accept the
  40. expressions for what you think they should do and you will
  41. probably be correct.
  42.  
  43. Several things must be pointed out regarding the while loop. 
  44. First, if the variable count were initially set to any number
  45. greater than 5, the statements within the loop would not be
  46. executed at all, so it is possible to have a while loop that
  47. never is executed.  Secondly, if the variable were not
  48. incremented in the loop, then in this case, the loop would
  49. never terminate, and the program would never complete. 
  50. Finally, if there is only one statement to be executed within
  51. the loop, it does not need delimiting braces but can stand
  52. alone.
  53.  
  54. Compile and run this program after you have studied it enough
  55. to assure yourself that you understand its operation
  56. completely.  Note that the result of execution is given for
  57. this program, (and will be given for all of the remaining
  58.  
  59.                                                      Page 3-1
  60.  
  61.                                   Chapter 3 - Program Control
  62.  
  63. example programs in this tutorial) so you do not need to
  64. compile and execute every program to see the results.  Be sure
  65. to compile and execute some of the programs however, to gain
  66. experience with your compiler.
  67.  
  68.  
  69. THE DO-WHILE LOOP
  70. ____________________________________________________________
  71.  
  72. A variation of the while loop is illustrated    =============
  73. in the program DOWHILE.C, which you should        DOWHILE.C
  74. load and display.  This program is nearly       =============
  75. identical to the last one except that the
  76. loop begins with the keyword do, followed by
  77. a compound statement in braces, then the keyword while, and
  78. finally an expression in parentheses.  The statements in the
  79. braces are executed repeatedly as long as the expression in
  80. parentheses is true.  When the expression in parentheses
  81. becomes false, execution is terminated, and control passes to
  82. the statements following this statement.
  83.  
  84. Several things must be pointed out regarding the do-while
  85. loop. Since the test is done at the end of the loop, the
  86. statements in the braces will always be executed at least
  87. once.  Secondly, if the variable i were not changed within the
  88. loop, the loop would never terminate, and hence the program
  89. would never terminate.  Finally, just like the while loop, if
  90. only one statement will be executed within the loop, no braces
  91. are required.  Compile and run this program to see if it does
  92. what you think it should do.
  93.  
  94. It should come as no surprise to you that these loops can be
  95. nested.  That is, one loop can be included within the compound
  96. statement of another loop, and the nesting level has no limit.
  97.  
  98.  
  99. THE FOR LOOP
  100. ____________________________________________________________
  101.  
  102. The for loop is really nothing new, it is       =============
  103. simply a new way to describe the while loop.      FORLOOP.C
  104. Load and display the file named FORLOOP.C on    =============
  105. your monitor for an example of a program with
  106. a for loop.  The for loop consists of the
  107. keyword for followed by a rather large expression in
  108. parentheses.  This expression is really composed of three
  109. fields separated by semi-colons.  The first field contains the
  110. expression "index = 0" and is an initializing field.  Any
  111. expressions in this field are executed prior to the first pass
  112. through the loop.  There is essentially no limit as to what
  113. can go here, but good programming practice would require it
  114. to be kept simple.  Several initializing statements can be
  115. placed in this field, separated by commas.
  116.  
  117.                                                      Page 3-2
  118.  
  119.                                   Chapter 3 - Program Control
  120.  
  121. The second field, in this case containing "index < 6", is the
  122. test which is done at the beginning of each loop through the
  123. program.  It can be any expression which will evaluate to a
  124. true or false.  (More will be said about the actual value of
  125. true and false in the next chapter.)
  126.  
  127. The expression contained in the third field is executed each
  128. time the loop is exercised but it is not executed until after
  129. those statements in the main body of the loop are executed. 
  130. This field, like the first, can also be composed of several
  131. operations separated by commas.
  132.  
  133. Following the for() expression is any single or compound
  134. statement which will be executed as the body of the loop.  A
  135. compound statement is any group of valid C statements enclosed
  136. in braces.  In nearly any context in C, a simple statement can
  137. be replaced by a compound statement that will be treated as
  138. if it were a single statement as far as program control goes. 
  139. Compile and run this program.
  140.  
  141. You may be wondering why there are two statements available
  142. that do exactly the same thing because the while and the for
  143. loop do exactly the same thing.  The while is convenient to
  144. use for a loop that you don't have any idea how many times the
  145. loop will be executed, and the for loop is usually used in
  146. those cases when you are doing a fixed number of iterations. 
  147. The for loop is also convenient because it moves all of the
  148. control information for a loop into one place, between the
  149. parentheses, rather than at both ends of the code.  It is your
  150. choice as to which you would rather use.
  151.  
  152.  
  153.  
  154. THE IF STATEMENT
  155. ____________________________________________________________
  156.  
  157. Load and display the file IFELSE.C for an      ==============
  158. example of our first conditional branching        IFELSE.C
  159. statement, the if.  Notice first, that there   ==============
  160. is a for loop with a compound statement as
  161. its executable part containing two if
  162. statements.  This is an example of how statements can be
  163. nested.  It should be clear to you that each of the if
  164. statements will be executed 10 times.
  165.  
  166. Consider the first if statement.  It starts with the keyword
  167. if followed by an expression in parentheses.  If the
  168. expression is evaluated and found to be true, the single
  169. statement following the if is executed, and if false, the
  170. following statement is skipped.  Here too, the single
  171. statement can be replaced by a compound statement composed of
  172. several statements bounded by braces.   The expression "data
  173. == 2" is simply asking if the value of data is equal to 2,
  174. this will be explained in detail in the next chapter.  (Simply
  175.  
  176.                                                      Page 3-3
  177.  
  178.                                   Chapter 3 - Program Control
  179.  
  180. suffice for now that if "data = 2" were used in this context,
  181. it would mean a completely different thing.)
  182.  
  183.  
  184. NOW FOR THE IF-ELSE
  185. ____________________________________________________________
  186.  
  187. The second if is similar to the first with the addition of a
  188. new keyword, the else in line 15.  This simply says that if
  189. the expression in the parentheses evaluates as true, the first
  190. expression is executed, otherwise the expression following the
  191. else is executed.  Thus, one of the two expressions will
  192. always be executed, whereas in the first example the single
  193. expression was either executed or skipped.  Both will find
  194. many uses in your C programming efforts.  Compile and run this
  195. program to see if it does what you expect.
  196.  
  197.  
  198. THE BREAK AND CONTINUE
  199. ____________________________________________________________
  200.  
  201. Load the file named BREAKCON.C for an          ==============
  202. example of two new statements.  Notice that      BREAKCON.C
  203. in the first for loop, there is an if          ==============
  204. statement that calls a break if xx equals
  205. 8.  The break will jump out of the loop you
  206. are in and begin executing statements following the loop,
  207. effectively terminating the loop.  This is a valuable
  208. statement when you need to jump out of a loop depending on the
  209. value of some results calculated in the loop.  In this case,
  210. when xx reaches 8, the loop is terminated and the last value
  211. printed will be the previous value, namely 7.
  212.  
  213. The next for loop starting in line 12, contains a continue
  214. statement which does not cause termination of the loop but
  215. jumps out of the present iteration.  When the value of xx
  216. reaches 8 in this case, the program will jump to the end of
  217. the loop and continue executing the loop, effectively
  218. eliminating the printf() statement during the pass through the
  219. loop when xx is eight.  Compile and run this program.
  220.  
  221.  
  222. THE SWITCH STATEMENT
  223. ____________________________________________________________
  224.  
  225. Load and display the file SWITCH.C for an      ==============
  226. example of the biggest construct yet in the       SWITCH.C
  227. C language, the switch.  The switch is not     ==============
  228. difficult, so don't let it intimidate you. 
  229. It begins with the keyword switch followed by
  230. a variable in parentheses which is the switching variable, in
  231. this case truck.  As many cases as desired are then enclosed
  232. within a pair of braces.  The reserved word case is used to
  233. begin each case, followed by the value of the variable, then
  234. a colon, and the statements to be executed.
  235.  
  236.                                                      Page 3-4
  237.  
  238.                                   Chapter 3 - Program Control
  239.  
  240. In this example, if the variable named truck contains the
  241. value 3 during this pass of the switch statement, the printf()
  242. in line 9 will cause "The value is three" to be displayed, and
  243. the break statement will cause us to jump out of the switch. 
  244.  
  245. Once an entry point is found, statements will be executed
  246. until a break is found or until the program drops through the
  247. bottom of the switch braces.  If the variable has the value
  248. 5, the statements will begin executing at line 13 where "case
  249. 5 :" is found, but the first statements found are where the
  250. case 8 statements are.  These are executed and the break
  251. statement in line 17 will direct the execution out the bottom
  252. of the switch.  The various case values can be in any order
  253. and if a value is not found, the default portion of the switch
  254. will be executed.
  255.  
  256.  
  257. It should be clear that any of the above constructs can be
  258. nested within each other or placed in succession, depending
  259. on the needs of the particular programming project at hand. 
  260. Note that the switch is not used as frequently as the loop and
  261. the if statements, in fact the switch is used infrequently. 
  262. Be sure to compile and run SWITCH.C and examine the results.
  263.  
  264.  
  265.  
  266. THE EVIL GOTO STATEMENT
  267. ____________________________________________________________
  268.  
  269. Load and display the file GOTOEX.C for an      ==============
  270. example of a file with some goto statements       GOTOEX.C
  271. in it.  To use a goto statement, you simply    ==============
  272. use the reserved word goto followed by the
  273. symbolic name to which you wish to jump.  The
  274. name is then placed anywhere in the program followed by a
  275. colon.  You can jump nearly anywhere within a function, but
  276. you are not permitted to jump into a loop, although you are
  277. allowed to jump out of a loop.
  278.  
  279. This particular program is really a mess but it is a good
  280. example of why software writers are trying to eliminate the
  281. use of the goto statement as much as possible.  The only place
  282. in this program where it is reasonable to use the goto is the
  283. one in line 18 where the program jumps out of the three nested
  284. loops in one jump.  In this case it would be rather messy to
  285. set up a variable and jump successively out of all three loops
  286. but one goto statement gets you out of all three in a very
  287. concise manner.
  288.  
  289. Some persons say the goto statement should never be used under
  290. any circumstances, but this is rather narrow minded thinking. 
  291. If there is a place where a goto will clearly do a neater
  292. control flow than some other construct, feel free to use it. 
  293.  
  294.                                                      Page 3-5
  295.  
  296.                                   Chapter 3 - Program Control
  297.  
  298. It should not be abused however, as it is in the rest of the
  299. program on your monitor.
  300.  
  301. Entire books are written on "gotoless" programming, better
  302. known as Structured Programming.  These will be left to your
  303. study.  One point of reference is the Visual Calculator
  304. described in Chapter 14 of this tutorial.  This program is
  305. contained in four separately compiled files and is a rather
  306. large complex program.  If you spend some time studying the
  307. source code, you will find that there is not a single goto
  308. statement anywhere in it.
  309.  
  310. Compile and run GOTOEX.C and study its output.  It would be
  311. a good exercise to rewrite it and see how much more readable
  312. it is when the statements are listed in order.
  313.  
  314.  
  315. FINALLY, A MEANINGFUL PROGRAM
  316. ____________________________________________________________
  317.  
  318. Load the file named TEMPCONV.C for an example  ==============
  319. of a useful, even though somewhat limited        TEMPCONV.C
  320. program.  This is a program that generates a   ==============
  321. list of centigrade and fahrenheit
  322. temperatures and prints a message out at the
  323. freezing point of water and another at the boiling point of
  324. water. 
  325.  
  326. Of particular importance is the formatting.  The header is
  327. simply several lines of comments describing what the program
  328. does in a manner that catches the readers attention and is
  329. still pleasing to the eye. You will eventually develop your
  330. own formatting style, but this is a good way to start.  Also
  331. if you observe the for loop, you will notice that all of the
  332. contents of the compound statement are indented 3 spaces to
  333. the right of the for keyword, and the closing brace is lined
  334. up under the "f" in for.  This makes debugging a bit easier
  335. because the construction becomes very obvious.  You will also
  336. notice that the printf() statements that are in the if
  337. statements within the big for loop are indented three
  338. additional spaces because they are part of another construct. 
  339.  
  340. This is the first program in which we used more than one
  341. variable.  The three variables are simply defined on three
  342. different lines and are used in the same manner as a single
  343. variable was used in previous programs.  By defining them on
  344. different lines, we have an opportunity to define each with
  345. a comment.
  346.  
  347. Be sure to compile and execute this program.
  348.  
  349.  
  350.  
  351.  
  352.  
  353.                                                      Page 3-6
  354.  
  355.                                   Chapter 3 - Program Control
  356.  
  357. ANOTHER POOR PROGRAMMING EXAMPLE
  358. ____________________________________________________________
  359.  
  360. Recalling UGLYFORM.C from the last chapter,    ==============
  361. you saw a very poorly formatted program.  If     DUMBCONV.C
  362. you load and display DUMBCONV.C you will have  ==============
  363. an example of poor formatting which is much
  364. closer to what you will find in practice. 
  365. This is the same program as TEMPCONV.C with the comments
  366. removed and the variable names changed to remove the
  367. descriptive aspect of the names.  Although this program does
  368. exactly the same as the last one, it is much more difficult
  369. to read and understand.  You should begin to develop good
  370. programming practices now.
  371.  
  372.  
  373. PROGRAMMING EXERCISES
  374. ____________________________________________________________
  375.  
  376. 1.   Write a program that writes your name on the monitor ten
  377.      times.  Write this program three times, once with each
  378.      looping method.
  379.  
  380. 2.   Write a program that counts from one to ten, prints the
  381.      values on a separate line for each, and includes a
  382.      message of your choice when the count is 3 and a
  383.      different message when the count is 7.
  384.  
  385.  
  386.  
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.  
  401.  
  402.  
  403.  
  404.  
  405.  
  406.  
  407.  
  408.  
  409.                                                      Page 3-7
  410.