1 / 101

A First Book of ANSI C Fourth Edition

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays. Objectives. One-Dimensional Arrays Array Initialization Arrays as Function Arguments Case Study: Computing Averages and Standard Deviations Two-Dimensional Arrays Common Programming and Compiler Errors. Chapter 8 Arrays.

katen
Download Presentation

A First Book of ANSI C Fourth Edition

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A First Book of ANSI CFourth Edition Chapter 8 Arrays

  2. Objectives • One-Dimensional Arrays • Array Initialization • Arrays as Function Arguments • Case Study: Computing Averages and Standard Deviations • Two-Dimensional Arrays • Common Programming and Compiler Errors A First Book of ANSI C, Fourth Edition

  3. Chapter 8 Arrays • The variables used so far have all had a common characteristic : each variable can only be used to store a single value at a time . • These types of variables are called scalar variables . A First Book of ANSI C, Fourth Edition

  4. A scalar variable is a single variable whose stored value is an atomic type . • This means that the value cannot be further subdivided or separated into a legitimate data type • Frequently we may have a set of values , all of the same data type , that form a logical group . A First Book of ANSI C, Fourth Edition

  5. A simple list consisting of individual items of the same scalar data type is called a single-dimensional array . • In this chapter we describe how single-dimensional arrays are declared , initialized , stored inside a computer , and used . • We will explore the use of single-dimensional arrays with example programs and present the procedures for declaring and using multidimensional arrays . A First Book of ANSI C, Fourth Edition

  6. 8.1 One Dimensional Arrays • A single-dimensional array , which is also referred to as a one-dimensional array , is a list of values of the same data type . • To declare that grades is to be used to store five individual integer values requires the declaration statement int grades[5] ; A First Book of ANSI C, Fourth Edition

  7. Further examples of array declarations are • char code[4] ; /* an array of four character codes */ • double prices[6] ;/* an array of six double precision prices */ • float amount [100] ;/*an array of 100 floating point amounts */ A First Book of ANSI C, Fourth Edition

  8. Each array has sufficient memory reserved for it to hold the number of data items given in the declaration statement . • Thus , the array named code has storage reserved for four characters ,the prices array has storage reserved for six double precision numbers , and the array named amount has storage reserved for 100 floating point numbers . A First Book of ANSI C, Fourth Edition

  9. Each item in a list is officially called an element or component of the array . • Because each item in the list is stored sequentially , any single item can be accessed by giving the name of the array and the position of the item in the array . A First Book of ANSI C, Fourth Edition

  10. The element’s position is called its subscript or index value . • The first element has a subscript of 0 , the second element has subscript of 1 , and so on . • The subscript gives the number of elements to move over , starting from the beginning of the array , to locate the desired element . • In C , the array name and subscript are combined by listing the subscript in square brackets after the array name . A First Book of ANSI C, Fourth Edition

  11. Introduction (continued) A First Book of ANSI C, Fourth Edition

  12. Subscripted variables can be used anywhere that scalar variables are valid . • Examples using the elements of the grades array are • grades [0] = 98 ; • grades [1] = grades [0] – 11 • grades [2] = 2 * ( grades [0] – 6 ); • grades [3] = 79 ; • grades [4] = (grades [2] + grades [3] – 3 ) / 2 ; • total = grades [0] + grades [1] + grades [2] + grades [3] + grades [4] ; A First Book of ANSI C, Fourth Edition

  13. The subscript contained within square brackets need not be an integer . • Any expression that evaluates to an integer may be used as a subscript . • For example , assuming that i and j are integer variables , the following subscripted variables are valid : • grades [i] • grades [2*i] • grades [j-i] A First Book of ANSI C, Fourth Edition

  14. One extremely important advantage of using integer expressions as subscripts is that it allows sequencing through an array using a for loop . • This makes statements such as total = grades[1]+ grades[2]+ grades[3]+ grades[4]+ grades[5] ; unnecessary . A First Book of ANSI C, Fourth Edition

  15. The subscript value in each of the subscripted variables in this statement can be replaced by the counter in a for loop to access each element in the array sequentially . • For example , the code • total = 0 ; /* initialize total to zero */ • for (i = 0 ; i <= 4 ; ++i ) • total = total + grades [i] ;/* add in a grade */ • sequentially retrieves each array element and adds the element to the total . A First Book of ANSI C, Fourth Edition

  16. Here the variable i is used both as the counter in the for loop and as a subscript . • As i increases by one each time through the for loop , the next element in the array is referenced . • The procedure for adding the array elements within the for loop is the same procedure we have used many times before . A First Book of ANSI C, Fourth Edition

  17. When an element with a higher value is located , that element becomes the new maximum . • maximum = price[0] ; • for (i = 1 ; i <= 999 ; ++i) • if (price[i] > maximum) • maximum = price[i] ; A First Book of ANSI C, Fourth Edition

  18. Input and Output of Array Values • Individual array elements can be assigned values using individual assignment statements or , interactively , using the scanf( ) function . A First Book of ANSI C, Fourth Edition

  19. Examples of individual data entry statements are • price[5] = 10.69 ; • scanf (“%d %lf”, &grades[0] , &price[2] ) • scanf (“%c”, &code[0] ); • scanf (“%d %d %d”, &grades[0], &grades[1], &grades[2]); A First Book of ANSI C, Fourth Edition

  20. Alternatively , a for statement can be used to cycle through the array for interactive data input . • For example , the code • for (i = 0 ; i <= 4 ; ++i ) • { • printf (“Enter a grade : ”); • scanf (“%d”, &grade[i] ); • } • prompts the user for five grades . • The first grade entered is stored in grades[0] , the second in grades[1] , and so on until all five grades are entered . A First Book of ANSI C, Fourth Edition

  21. One caution should be mentioned about storing data in an array . • C does not check the value of the index being used . • If an array has been declared as consisting of 10 elements , for example , and you use an index of 12 , which is outside the bounds of the array , C will not notify you of the error when the program is compiled . A First Book of ANSI C, Fourth Edition

  22. During output , individual array elements can be displayed using the printf( ) function or complete sections of the array can be displayed by including a printf( ) function call within a for loop . • Examples of this are • printf (“%lf ,” price[6] ); • printf (“The value of element %d is %d”, i , grades[i] ); • for ( n = 5 ; n <= 20 ; ++n ) • printf (“%d %lf”, n , price[n] ); A First Book of ANSI C, Fourth Edition

  23. The first call to printf( ) displays the value of the double precision subscripted variable price[6] . • The second call to printf( ) displays the value of i and the value of grades[i] . • Before this statement can be executed , i needs to have an assigned value . • Finally , the last example includes printf( ) within a for loop . • Both the value of the index and the value of the elements from 5 to 20 are displayed . A First Book of ANSI C, Fourth Edition

  24. Program 8.1 illustrates these input and output techniques using an array named grades that is defined to store five integer numbers . • Included in the program are two for loops . • The first for loop is used to cycle through each array element and allows the user to input individual array values . • After five values have been entered , the second for loop is used to display the stored values . A First Book of ANSI C, Fourth Edition

  25. Program 8.1 • #include <stdio.h> • int main ( ) • { • int i , grades[5] ; • for (i = 0 ; i <= 4 ; ++i) /* Enter five grades */ • { • printf (“Enter a grade :”) ; • scanf (“%d”, &grades[i] ) ; • } • for ( i = 0 ; i <= 4 ; ++i ) /* Print five grades */ • printf (“\ngrades %d is %d” , i , grades[i] ); • return 0 ; • } A First Book of ANSI C, Fourth Edition

  26. In reviewing the output produced by Program 8.1 , pay particular attention to the difference between the subscript value displayed and the numerical value stored in the corresponding array element . • The subscript value refers to the location of the element in the array , whereas the subscripted variable refers to the value stored in the designed location . A First Book of ANSI C, Fourth Edition

  27. Input and Output of Array Values (continued) Sample output: Enter a grade: 85 Enter a grade: 90 Enter a grade: 78 Enter a grade: 75 Enter a grade: 92 grades 0 is 85 grades 1 is 90 grades 2 is 78 grades 3 is 75 grades 4 is 92 A First Book of ANSI C, Fourth Edition

  28. Program 8.2 • #include <stdio.h> • int main( ) • { • int i , grades[5] , total = 0 ; • for (i = 0 ; i <= 4 ; ++i ) /* Enter five grades */ • { • printf (“Enter a grade : ”) ; • scanf (“%d”, &grades[i] ) ; • } A First Book of ANSI C, Fourth Edition

  29. printf (“\nThe total of the grades ”) ; • for (i = 0 ; i <= 4 ; ++i) /* Display and total the grades */ • { • printf (“%d ”, grades[i] ); • total += grades[i] ; • } • printf (“ is %d ”, total ); • return 0 ; • } A First Book of ANSI C, Fourth Edition

  30. Following is a sample run using Program 7. 2 : • Enter a grade : 85 • Enter a grade : 90 • Enter a grade : 78 • Enter a grade : 75 • Enter a grade : 92 • The total of the grades 85 90 78 75 92 is 420 A First Book of ANSI C, Fourth Edition

  31. Notice that in Program 8.2 , unlike Program 8.1 , only the numerical value stored in each array element is displayed and not their subscript values . • Although the second for loop was used to accumulate the total of each element , the accumulation could also have been accomplished in the first loop by placing the statement total += grades[i] ; after the scanf( ) call used to enter a value .. A First Book of ANSI C, Fourth Edition

  32. Also notice that the printf( ) call used to display the total made outside of the second for loop so that the total is displayed only once , after all values have been added to the total . • If this printf( ) call is placed inside the for loop five totals are displayed , with only the last displayed total containing the sun of all of the array values A First Book of ANSI C, Fourth Edition

  33. Input and Output of Array Values (continued) Statement is outside of the second for loop; total is displayed only once, after all values have been added A First Book of ANSI C, Fourth Edition

  34. 8.2 Array Initialization • Arrays , like scalar variables , can be declared either inside or outside a function . • Arrays declared inside a function are local arrays , and arrays declared outside a function are global arrays . A First Book of ANSI C, Fourth Edition

  35. Array Initialization (continued) 1 #define SIZE1 20 2 #define SIZE2 25 3 #define SIZE3 15 4 5 int gallons[SIZE1]; /* a global array */ 6 static int dist[SIZE2]; /* a static global array */ 7 8 int main() 9 { 10 int miles[SIZE3]; /* an auto local array */ 11 static int course[SIZE3]; /* static local array */ 12 . 13 . 14 return 0; 15 } A First Book of ANSI C, Fourth Edition

  36. For example , consider the following section of code : • int gallons[20] ; /* a global array */ • static double dist[25] ; /* a static global array */ • void mpg (int) ; /* function prototype */ • int main ( ) • { • int i ; • for ( i = 1 ; i <= 10 ; ++i ) • mpg (i) ; … • return 0 ; • } A First Book of ANSI C, Fourth Edition

  37. void mpg (int carNum) • { • int miles[15] ; /* an automatic local array */ • static double course[15] ; /* a static local array */ … • return ; • } A First Book of ANSI C, Fourth Edition

  38. As indicated in the code , both the dist and gallons arrays are globally declared arrays , miles is an automatic local array , and course is a static local array . • As with scalar variables , all global arrays and local static arrays are created once , at compilation time , and retain their values until main( ) finishes executing . • auto arrays are created and destroyed each time the function they are local to is called . • Thus , the dist , gallons , and course arrays are created once , and the miles array is created and destroyed ten times . A First Book of ANSI C, Fourth Edition

  39. Array elements can be initialized within their declaration statements in the same manner as scalar variables , except that the initializing elements must be included in braces . • Examples of such initializations for automatic , static , and global arrays are • int grades[5] = { 98, 87, 92, 79, 85 }; • char codes[6] = { ‘s’,‘a’,‘m’,‘p’,‘l’,‘e’}; • double width[7] = { 10.96, 6.43, 2.58, .86, 5.89, 7.56, 8.22} ; • static int temp[4] = {10 , 20 , 30 , 40 } ; • static float temp[4] = { 98.6, 97.2, 99.0, 101.5} ; A First Book of ANSI C, Fourth Edition

  40. Initializers are applied in the order they are written , with the first value used to initialize element 0 , the second value used to initialize element 1 , and so on , until all values have been used . A First Book of ANSI C, Fourth Edition

  41. Because white space is ignored in C , initializations may be continued across multiple lines . • For example , the declaration • int gallons[20]={19,16,14,19,20,18, /* initializing • values */ • 12,10,22,15,18,17, /* may extend across */ • 16,14,23,19,15,18, /* multiple lines */ 21,5 } • uses four lines to initialize all of the array elements . A First Book of ANSI C, Fourth Edition

  42. If the number of initializers is less than the declared number of elements listed in square brackets the initializers are applied starting with array element 0 . • Thus , in the declaration • float length[7] = { 7.8 , 6.4 , 4.9 , 11.2 } ; • only length[0] , length[1] , length[2] and length[3] are initialized with the listed values . • The other array elements will be initialized to zero . A First Book of ANSI C, Fourth Edition

  43. Unfortunately , there is no method to either indicate repetition of an initialization value or initialize later array elements without first specifying values for earlier elements . • If no specific initializers are given in the declaration statement , all numerical array elements are set to zero . A First Book of ANSI C, Fourth Edition

  44. A unique feature of initializers is that the size of an array may be omitted when initializing values are included in the declaration statement . • For example , the declaration • int gallons[ ] = { 16, 12, 10, 14, 11 } ; • reserves enough storage room for five elements . • Similarly , the following two declarations are equivalent : • char codes[6] = { ‘s’,‘a’,‘m’,‘p’,‘l’,‘e’}; • char codes[ ] = { ‘s’,‘a’,‘m’,‘p’,‘l’,‘e’} A First Book of ANSI C, Fourth Edition

  45. Both of these declarations set aside six character locations for an array named codes . • An interesting and useful simplification can also be used when initializing character arrays . • For example , the declaration • char codes[ ] = “sample”; /* no braces or commas */ • uses the string “sample” to initialize the codes array . A First Book of ANSI C, Fourth Edition

  46. Recall that a string is any sequence of characters enclosed in double quotes . • This last declaration creates an array named codes having seven elements and fills the array with the seven characters illustrated in Figure 8.6 . • The first six characters , as expected , consist of the letters s, a, m, p, l, and e. • The last character , which is the escape sequence \0 , is called the null character . A First Book of ANSI C, Fourth Edition

  47. The null character is automatically appended to all strings by the C compiler . A First Book of ANSI C, Fourth Edition

  48. Array Initialization (continued) A First Book of ANSI C, Fourth Edition

  49. Array Initialization (continued) A First Book of ANSI C, Fourth Edition

  50. 8.3 Arrays as Function Arguments • Individual array elements are passed to a function by simply including them as subscripted variables in the function call argument list . • For example , the function call findMin (grades[2] , grades[6] ) ; passes the values of the elements grades[2] and grades[6] to the function findMin ( ) . A First Book of ANSI C, Fourth Edition

More Related