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

  1.  
  2.  
  3.  
  4.  
  5.                                                     Chapter 7
  6.                                            STRINGS AND ARRAYS
  7.  
  8. WHAT IS A STRING?
  9. ____________________________________________________________
  10.  
  11. A string is a group of characters, usually letters of the
  12. alphabet.  In order to format your printout in such a way that
  13. it looks nice, has meaningful names and titles, and is
  14. aesthetically pleasing to you and the people using the output
  15. of your program, you need the ability to output text data. 
  16. Actually you have already been using strings, because the
  17. second program in this tutorial, way back in Chapter 2, output
  18. a message that was handled internally as a string.  A complete
  19. definition of a string is a series of char type data
  20. terminated by a NULL character. 
  21.  
  22. When C is going to use a string of data in some way, either
  23. to compare it with another string, output it, copy it to
  24. another string, or whatever, the functions are set up to do
  25. what they are called to do until a NULL, which is a zero, is
  26. detected.  Such a string is often called an ASCIIZ string. 
  27. We will use a few ASCIIZ strings in this chapter.
  28.  
  29.  
  30. WHAT IS AN ARRAY?
  31. ____________________________________________________________
  32.  
  33. An array is a series of homogeneous pieces of data that are
  34. all identical in type, but the type can be quite complex as
  35. we will see when we get to the chapter of this tutorial
  36. discussing structures.  A string is simply a special case of
  37. an array, a series of char type data. 
  38.  
  39. The best way to see these principles is by    ===============
  40. use of an example, so load the program           CHRSTRG.C
  41. CHRSTRG.C and display it on your monitor.     ===============
  42. The first thing new is in line 6 which
  43. defines a char type of data entity.  The
  44. square brackets define an array subscript in C, and in the
  45. case of the data definition statement, the 5 in the brackets
  46. defines 5 data fields of type char all defined as part of the
  47. variable.  In the C language, all subscripts start at 0 and
  48. increase by 1 each step up to the maximum which in this case
  49. is 4.  We therefore have 5 char type variables named, name[0],
  50. name[1], name[2], name[3], and name[4].  You must keep in mind
  51. that in C, the subscripts actually go from 0 to one less than
  52. the number defined in the definition statement.  This is due
  53. to the original definition of C and these limits cannot be
  54. changed or redefined by the programmer.
  55.  
  56.  
  57.  
  58.  
  59.                                                      Page 7-1
  60.  
  61.                                Chapter 7 - Strings and Arrays
  62.  
  63. HOW DO WE USE THE STRING?
  64. ____________________________________________________________
  65.  
  66. The variable name is therefore a string which can hold up to
  67. 5 characters, but since we need room for the NULL terminating
  68. character, there are actually only four useful characters. 
  69. To load something useful into the string, we have 5
  70. statements, each of which assigns one alphabetical character
  71. to one of the string characters.  Finally, the last place in
  72. the string is filled with the numeral 0 as the end indicator
  73. and the string is complete.  (A define would allow us to use
  74. NULL instead of a zero, and this would add greatly to the
  75. clarity of the program. It would be very obvious that this was
  76. a NULL and not simply a zero for some other purpose.)  Now
  77. that we have the string, we will print it out with some other
  78. string data in the output statement, line 14.
  79.  
  80. The %s is the output definition to output a string and the
  81. system will output characters starting with the first one in
  82. the string name until it comes to the NULL character, and it
  83. will quit.  Notice that in the printf() statement, only the
  84. variable name which happens to be name needs to be given, with
  85. no subscript since we are interested in starting at the
  86. beginning.  (There is actually another reason that only the
  87. variable name is given without brackets.  The discussion of
  88. that topic will be given in the next chapter.)
  89.  
  90.  
  91. OUTPUTTING PART OF A STRING
  92. ____________________________________________________________
  93.  
  94. The printf() in line 15 illustrates that we can output any
  95. single character of the string by using the %c and naming the
  96. particular character of the variable name we want by including
  97. the subscript.  The last printf() illustrates how we can
  98. output part of the string by stating the starting point by
  99. using a subscript.  The & specifies the address of name[1]. 
  100. We will study this in the next chapter but I thought you would
  101. benefit from a little glimpse ahead, so don't worry about this
  102. construct yet.
  103.  
  104. This example may make you feel that strings are rather
  105. cumbersome to use since you have to set up each character one
  106. at a time.  The next example program will illustrate that
  107. strings are very easy to use.  Be sure to compile and run this
  108. program.
  109.  
  110.  
  111. SOME STRING FUNCTIONS
  112. ____________________________________________________________
  113.  
  114. Load the example program STRINGS.C for an example of some ways
  115. to use strings.  First we define four strings.  Next we come
  116. to a new function that you will find very useful, the strcpy()
  117.  
  118.                                                      Page 7-2
  119.  
  120.                                Chapter 7 - Strings and Arrays
  121.  
  122. function, or string copy.  It copies from one
  123. string to another until it comes to the NULL    =============
  124. character in the source string.  Remember         STRINGS.C
  125. that the NULL is actually a zero and is added   =============
  126. to the character string by the system.  It is
  127. easy to remember which one gets copied to which if you think
  128. of them like an assignment statement.  Thus if you were to
  129. say, for example, x = 23;, the data is copied from the right
  130. entity to the left one.  In the strcpy() function, the data
  131. is also copied from the right entity to the left, so that
  132. after execution of the first statement, the string variable
  133. name1 will contain the string "Rosalinda", but without the
  134. double quotes, they are the compiler's way of knowing that you
  135. are defining a string.
  136.  
  137. Likewise, the string "Zeke" is copied into name2 in line 11,
  138. then the title string is copied into the string named title. 
  139. The title and both names are then printed out.  Note that it
  140. is not necessary for the defined string to be exactly the same
  141. size as the string it will be called upon to store, only that
  142. it is at least as long as the string plus one more character
  143. for the NULL. 
  144.  
  145.  
  146. ALPHABETICAL SORTING OF STRINGS
  147. ____________________________________________________________
  148.  
  149. The next function we will look at is the strcmp() or the
  150. string compare function illustrated in line 18.  It will
  151. return a 1 if the first string is larger than the second, zero
  152. if they are the same length and have the same characters, and
  153. -1 if the first string is smaller than the second.  One of the
  154. strings, depending on the result of the compare is copied into
  155. the string variable mixed, and the largest name alphabetically
  156. is printed out.  It should come as no surprise to you that
  157. Zeke wins because it is alphabetically larger, length doesn't
  158. matter, only the alphabet.  It might be wise to mention that
  159. the result would also depend on whether the letters were upper
  160. or lower case.  There are functions available with your C
  161. compiler to change the case of a string to all upper or all
  162. lower case if you desire.  These will be used in an example
  163. program later in this tutorial.
  164.  
  165.  
  166.  
  167. COMBINING STRINGS
  168. ____________________________________________________________
  169.  
  170. Lines 25 through 28 illustrate another new feature, the
  171. strcat(), or string concatenation function.  This function
  172. simply adds the characters from one string onto the end of
  173. another string taking care to adjust the NULL so everything
  174. is still all right.  In this case, name1 is copied into mixed,
  175. then two blanks are concatenated to mixed, and finally name2
  176.  
  177.                                                      Page 7-3
  178.  
  179.                                Chapter 7 - Strings and Arrays
  180.  
  181. is concatenated to the combination.  The result is printed out
  182. with both names in the one string variable mixed.
  183.  
  184. Strings are not difficult and are extremely useful.  You
  185. should spend some time getting familiar with them before
  186. proceeding on to the next topic.
  187.  
  188. Compile and run this program and observe the results for
  189. compliance with this definition.
  190.  
  191.  
  192. AN ARRAY OF INTEGERS
  193. ____________________________________________________________
  194.  
  195. Load the file INTARRAY.C and display it on     ==============
  196. your monitor for an example of an array of       INTARRAY.C
  197. integers.  Notice that the array is defined    ==============
  198. in much the same way we defined an array of
  199. char in order to do the string manipulations
  200. in the last example program.  We have 12 integer variables to
  201. work with not counting the one named index.  The names of the
  202. variables are values[0], values[1], ... , and values[11].  In
  203. lines 9 and 10 we have a loop to assign nonsense, but well
  204. defined, data to each of the 12 variables, then print all 12
  205. out in lines 12 and 13.  Note carefully that each element of
  206. the array is simply an int type variable capable of storing
  207. an integer value.  The only difference between the variables
  208. index and values[2], for example, is in the way you address
  209. them.  You should have no trouble following this program, but
  210. be sure you understand it.  Compile and run it to see if it
  211. does what you expect it to do.
  212.  
  213.  
  214. AN ARRAY OF FLOATING POINT DATA
  215. ____________________________________________________________
  216.  
  217. Load and display the program named BIGARRAY.C  ==============
  218. for an example of a program with an array of     BIGARRAY.C
  219. float type data.  This program has an extra    ==============
  220. feature to illustrate how strings can be
  221. initialized.  Line 4 of the program
  222. illustrates how to initialize a string of characters.  Notice
  223. that the square brackets are empty leaving it up to the
  224. compiler to count the characters and allocate enough space for
  225. our string including the terminating NULL.  Another string is
  226. initialized in line 11 of the body of the program but it must
  227. be declared static here.  This prevents it from being
  228. allocated as an automatic variable and allows it to retain the
  229. string once the program is started.  There is nothing else new
  230. here, the variables are assigned nonsense data and the results
  231. of all the nonsense are printed out along with a header.  This
  232. program should also be easy for you to follow, so study it
  233. until you are sure of what it is doing before going on to the
  234. next topic.
  235.  
  236.                                                      Page 7-4
  237.  
  238.                                Chapter 7 - Strings and Arrays
  239.  
  240.  
  241. GETTING DATA BACK FROM A FUNCTION
  242. ____________________________________________________________
  243.  
  244. Back in chapter 5 when we studied functions,   ==============
  245. I hinted to you that there was a way to get      PASSBACK.C
  246. data back from a function by using an array,   ==============
  247. and that is true.  Examine the program
  248. PASSBACK.C for an example of doing that.  In
  249. this program, we define an array of 20 variables named matrix
  250. in line 8, then assign some nonsense data to the variables,
  251. and print out the first five.  In line 16 we call the function
  252. dosome() taking along the entire array by putting the name of
  253. the array in the parentheses.
  254.  
  255. The function dosome() beginning in line 22 has a name in its
  256. parentheses also but it prefers to call the array list.  The
  257. function needs to be told that it is really getting an array
  258. passed to it and that the array is of type int.  Line 22 does
  259. that by defining list as an integer type variable and
  260. including the square brackets to indicate an array.  It is not
  261. necessary to tell the function how many elements are in the
  262. array, but you could if you so desired.  Generally a function
  263. works with an array until some end-of-data marker is found,
  264. such as a NULL for a string, or some other previously defined
  265. data or pattern.  Many times, another piece of data is passed
  266. to the function with a count of how many elements to work
  267. with.  In our present illustration, we will use a fixed number
  268. of elements to keep it simple.
  269.  
  270. So far nothing is different from the previous functions we
  271. have called except that we have passed more data points to the
  272. function this time than we ever have before, having passed 20
  273. integer values.  We print out the first 5 again in lines 26
  274. and 27 to see if they did indeed get passed here.  In lines
  275. 29 and 30 we add ten to each of the elements and print out the
  276. new values.  Finally we return to the main program and print
  277. out the same 5 data points.  We find that we have indeed
  278. modified the data stored in the calling program from within
  279. the function, and when we returned to the main program, we
  280. brought the changes back.  Compile and run this program to
  281. verify this conclusion.
  282.  
  283.  
  284. ARRAYS PASS DATA BOTH WAYS
  285. ____________________________________________________________
  286.  
  287. We stated during our study of functions that when we passed
  288. data to a function, the system made a copy to use in the
  289. function which was thrown away when we returned.  This is not
  290. the case with arrays.  The actual array is passed to the
  291. function and the function can modify it any way it wishes to. 
  292. The result of the modifications will be available back in the
  293. calling program.  This may seem strange to you that arrays are
  294.  
  295.                                                      Page 7-5
  296.  
  297.                                Chapter 7 - Strings and Arrays
  298.  
  299. handled differently from single point data, but they are.  It
  300. really does make sense, but you will have to wait until we get
  301. to pointers to understand it. 
  302.  
  303.  
  304.  
  305. A HINT AT A FUTURE LESSON
  306. ____________________________________________________________
  307.  
  308. Another way of getting data back from a function to the
  309. calling program is by using pointers which we will cover in
  310. the next chapter.  When we get there we will find that an
  311. array is in reality a pointer to a list of values.  Don't let
  312. that worry you now, it will make sense when we get there.  In
  313. the meantime concentrate on arrays and understand the basics
  314. of them because when we get to the study of structures we will
  315. be able to define some pretty elaborate arrays.
  316.  
  317.  
  318.  
  319. MULTI-DIMENSIONAL ARRAYS
  320. ____________________________________________________________
  321.  
  322. Load and display the file named MULTIARY.C     ==============
  323. for an example of a program with doubly          MULTIARY.C
  324. dimensioned arrays.  The variable big is an    ==============
  325. 8 by 8 array that contains 8 times 8 or 64
  326. elements total.  The first element is
  327. big[0][0], and the last is big[7][7].  Another array named
  328. large is also defined which is not square to illustrate that
  329. the array need not be square.  Both are filled up with data,
  330. one representing a multiplication table and the other being
  331. formed into an addition table.
  332.  
  333. To illustrate that individual elements can be modified at
  334. will, one of the elements of big is assigned the value from
  335. one of the elements of large after being multiplied by 22 in
  336. line 17.  Next big[2][2] is assigned the arbitrary value of
  337. 5, and this value is used for the subscripts of the assignment
  338. statement in line 19.  The assignment statement in line 19 is
  339. in reality big[5][5] = 177; because each of the subscripts
  340. contain the value 5.  This is only done to illustrate that any
  341. valid expression can be used for a subscript.  It must only
  342. meet two conditions, it must be an integer (although a char
  343. will work just as well), and it must be within the range of
  344. the subscript it is being used for.
  345.  
  346. The entire matrix variable big is printed out in a square form
  347. in lines 21 through 25 so you can check the values to see if
  348. they did get set the way you expected them to.
  349.  
  350.  
  351.  
  352.  
  353.  
  354.                                                      Page 7-6
  355.  
  356.                                Chapter 7 - Strings and Arrays
  357.  
  358. PROGRAMMING EXERCISES
  359. ____________________________________________________________
  360.  
  361. 1.   Write a program with three short strings, about 6
  362.      characters each, and use strcpy to copy the string
  363.      literals "one", "two", and "three" into them. Concatenate
  364.      the three strings into one string and print the result
  365.      out 10 times.
  366.  
  367. 2.   Define two integer arrays, each 10 elements long, called
  368.      array1 and array2. Using a loop, put some kind of
  369.      nonsense data in each and add them term for term into
  370.      another 10 element array named arrays.  Finally, print
  371.      all results in a table with an index number.
  372.  
  373.        1    2 + 10 = 12
  374.        2    4 + 20 = 24
  375.        3    6 + 30 = 36   etc.
  376.  
  377.      Hint; The print statement will be similar to;
  378.         printf("%4d %4d + %4d = %4d\n",index,array1[index],
  379.                 array2[index],arrays[index]);
  380.  
  381.  
  382.  
  383.  
  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.  
  410.  
  411.                                                      Page 7-7
  412.