Problem Solving and Program Design in C Chap
Problem Solving and Program Design in C Chap. 7 Arrays Chow-Sing Lin
CSIE@NUTN Declaring and Referencing Arrays • Arrays – A collection of data items of the same type • Array elements – An array is a collections of two or more adjacent memory cells • To set up an array in memory – We must declare both the name of the array and the number of cells associated with it Dr. Chow-Sing Lin Arrays - CH 8 2
CSIE@NUTN Declaring and Referencing Arrays (Cont. ) • The declaration double x[8]; – Instructs the compiler to associate eight memory cells with name x – These memory cells will be adjacent to each other in memory – Each element of array x may contain a single type double value • A total of eight such numbers may be stored and referenced using the array name x Dr. Chow-Sing Lin Arrays - CH 8 3
CSIE@NUTN Declaring and Referencing Arrays (Cont. ) • Subscripted variable – A variable followed by a subscript in brackets, designating an array element x[0] – Read as x sub zero – x[1] the next element double x[8] – x[7] the last element Dr. Chow-Sing Lin Arrays - CH 8 4
CSIE@NUTN Declaring and Referencing Arrays (Cont. ) • Array subscript – The integer enclosed in brackets • Value in the range from zero to one less than the number of memory cells in the array (0. . n-1) – A value of expression enclosed in brackets after the array name • Specifying which array element to access Dr. Chow-Sing Lin Arrays - CH 8 5
CSIE@NUTN Declaring and Referencing Arrays (Cont. ) • Example 7. 1 – Let x be the array shown in Figure. 8. 1 – x[1] is the second array element – X[7] is the last element Dr. Chow-Sing Lin Arrays - CH 8 6
CSIE@NUTN Declaring and Referencing Arrays (Cont. ) x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7] 16. 0 12. 0 28. 0 26. 0 2. 5 12. 0 14. 0 -54. 5 Statement Explanation printf (“%. 1 f”, x[0]); Displays the value of x[0], which is 16. 0 x[3] = 25. 0; Stores the value 25. 0 in x[3] sum = x[0] + x[1]; Stores the sum of x[0] and x[1], which is 28. 0 in the variable sum += x[2]; Adds x[2] to sum. The new sum is 34. 0 x[3] += 1. 0; Adds 1. 0 to x[3]. The new x[3] is 26. 0 x[2] = x[0] + x[1]; Stores the sum of x[0] and x[1] in x[2]. The new x[2] is 28. 0 Dr. Chow-Sing Lin Arrays - CH 8 7
CSIE@NUTN Declaring and Referencing Arrays (Cont. ) • Array declaration SYNTAX Element-type aname [size]; /* uninitialized */ element-type aname [size] = {initialization list}; /*initialized */ Example #define A_SIZE 5 ‧‧‧ double a[A_SIZE]; char vowels [ ] = {‘A’, ‘E’, ‘I’, ‘O’, ‘U’}; Dr. Chow-Sing Lin Arrays - CH 8 8
CSIE@NUTN Example • We declare two arrays for a student records program int double id [NUM_STUDENTS]; gpa [NUM_STUDENTS]; • We assume that NUM_STUDENTS has already appeared in a #define directive #define NUM_STUDENTS 50 Dr. Chow-Sing Lin Arrays - CH 8 9
CSIE@NUTN Example (Cont. ) • The array id and gpa each have 50 elements • Each element of array id can be used to store an integer value • Each element of array gpa can be used to store a value of type double • If you use these declarations in a problem to assess the range and distribution of grade point average – Store the first student’s id in id[0] – Store the same student’s gpa in gpa[0] Dr. Chow-Sing Lin Arrays - CH 8 10
CSIE@NUTN Example (Cont. ) • Parallel arrays – Two or more arrays with the same number of elements used for storing related information about a collection of data objects Dr. Chow-Sing Lin Arrays - CH 8 11
CSIE@NUTN Arrays Initialization • We can initialize a simple variable when we declare it : int sum = 0; • We can also initialize an array in its declaration • We can omit the size of an array that is being fully initialized – Since the size can be deduced from the initialization list Dr. Chow-Sing Lin Arrays - CH 8 12
CSIE@NUTN Arrays Initialization (Cont. ) • We initialize a 25 -element array with the prime numbers less than 100 int prime _lt_100[ ] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; Dr. Chow-Sing Lin Arrays - CH 8 13
CSIE@NUTN Exercises • Declare one array for storing the square roots of the integers from 0 through 10 and a second array for storing the cubes of the same integer. Answers double sq_root [11]; int cube [11]; Dr. Chow-Sing Lin Arrays - CH 8 14
CSIE@NUTN Array Subscripts • Use any expression of type int as an array subscript • Create a valid reference – The value of subscript must lie between 0 and one less than the declared size of the array SYNTAX aname [subscript] Example b [i + 1] Dr. Chow-Sing Lin Arrays - CH 8 15
CSIE@NUTN Example 7. 4 Statement Explanation i = 5; printf (“%d %. 1 f”, 4, x[4]); Displays 4 and 2. 5 (value of x[4]) printf (“%d %. 1 f”, i, x[i]); Displays 5 and 12. 0 (value of x[5]) printf (“%. 1 f”, x[i] + 1); Displays 13. 0 (value of x[5] plus 1) printf (“%. 1 f”, x[i] + i); Displays 17. 0 (value of x[5] plus 5) printf (“%. 1 f”, x[i + 1]); Displays 14. 0 (value of x[6]) printf (“%. 1 f”, x[i + i]); Invalid. Attempt to display x[10] printf (“%. 1 f”, x[2*i]); Invalid. Attempt to display x[10] Dr. Chow-Sing Lin Arrays - CH 8 16
CSIE@NUTN Example 7. 4 (Cont. ) Statement Explanation printf (“%. 1 f”, x[2 * i - 3]); Displays -54. 5 (value of x[7]) printf (“%. 1 f”, x[(int)x[4]]); Displays 6. 0 (value of x[2]) printf (“%. 1 f”, x[i++]); Displays 12. 0 (value of x[5]); then assigns 6 to i printf (“%. 1 f”, x[--i]); Displays 5(6 – 1) to i and then displays 12. 0 (value of x[5]) x[i – 1] = x[i]; Assigns 12. 0 (value of x[5]) to x[4] x[i] = x[i + 1]; Assigns 14. 0 (value of x[6]) to x[5] Dr. Chow-Singx[i] Lin – 1 = x[i] Illegal assignment statement Arrays - CH 8 17
CSIE@NUTN Exercises for Section 72 • Show the contents of array x after executing the valid statements in Table 7. 2 Before : After : Dr. Chow-Sing Lin x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7] 16. 0 12. 0 6. 0 8. 0 12. 0 14. 0 -54. 5 Arrays - CH 8 18
CSIE@NUTN Using for Loops for Sequential Access • Use an indexed for loop – Counting loop • Loop control variable runs from zero to one less than the array size • Using the loop counter as an array index (subscript) gives access to each array element in turn Dr. Chow-Sing Lin Arrays - CH 8 19
CSIE@NUTN Example 7. 5 • The array square will be used to store the squares of the integers 0 through 10 – square[0] is 0, square[10] is 100 – We assume that the name SIZE has been defined to be 11 int square[SIZE], i; – The for loop for (i = 0; i< SIZE; ++i) square[i] = i * i; – Initializes this array x[0] 0 Dr. Chow-Sing Lin x[1] x[2] x[3] 1 4 9 x[4] x[5] x[6] x[7] X[8] X[9] X[10] 16 25 36 49 64 81 100 Arrays - CH 8 20
CSIE@NUTN Statistical Computations Using Arrays • One common use of arrays is for storage of a collection of related data values • Once the values are stored, perform some simple statistical computations • Figure 8. 3 (Book Page 411) Program to Print a Table of Differences Dr. Chow-Sing Lin Arrays - CH 8 21
Statistical Computations Using Arrays (Cont. ) CSIE@NUTN ① Dr. Chow-Sing Lin Arrays - CH 8 22
CSIE@NUTN ② ③ Dr. Chow-Sing Lin Arrays - CH 8 23
Statistical Computations Using Arrays (Cont. ) CSIE@NUTN • First loop – Stores one input value into each element of array x • The first item is placed in x[0] • The next in x[1], and so on – The call to scanf is repeated for each value of i from 0 to 7 • Second loop – Accumulates (in sum) the sum of all value stored in the array – Accumulates (in sum_sqr) the sum of the squares of all element values Dr. Chow-Sing Lin Arrays - CH 8 24
Statistical Computations Using Arrays (Cont. ) CSIE@NUTN • Second loop (Cont. ) – This loop implements the formulas • Third loop – Displays a table – Each line of the table displays • • Dr. Chow-Sing Lin an array subscript an array element the different between that element x[i] - mean Arrays - CH 8 25
Statistical Computations Using Arrays (Cont. ) CSIE@NUTN • Partial trace of computing for loop Statement i x[i] sum = 0; sum 0. 0 sum_sqr = 0; for (i = 0; sum_sqr Initializes sum 0. 0 0 Effect 16. 0 Initializes sum_sqr Initializes i to 0 i < MAX_ITEM; Which is less than 8 ‧‧‧ sum += x[i]; 16. 0 Adds x[0] to sum_sqr += x[i] * x[i]; Dr. Chow-Sing Lin 256. 0 Arrays - CH 8 Adds 256. 0 to sum_sqr 26
Statistical Computations Using Arrays (Cont. ) Statement increment and test i i x[i] 1 12. 0 sum += x[i]; sum 28. 0 sum += x[i]; 6. 0 Adds 144. 0 to sum_sqr 2 < 8 is true 34. 0 sum_sqr += x[i] * x[i]; Dr. Chow-Sing Lin Adds x[1] to sum 400. 0 2 Effect 1 < 8 is true sum_sqr += x[i] * x[i]; increment and test i sum_sqr CSIE@NUTN Adds x[2] to sum 436. 0 Arrays - CH 8 Adds 36. 0 to sum_sqr 27
Statistical Computations Using Arrays (Cont. ) CSIE@NUTN • Standard deviation – Data is a measure of the spread of the data values around the mean – A small standard deviation indicates that the data values are all relatively close to the average value Dr. Chow-Sing Lin Arrays - CH 8 28
Statistical Computations Using Arrays (Cont. ) CSIE@NUTN • Standard deviation (Cont. ) – For MAX_ITEM data items • If we assume that x is an array • Lowest subscript is 0 • The standard deviation formula : Standard deviation • st_dev = sqrt (sum_sqr / MAX_ITEM mean * mean); Dr. Chow-Sing Lin Arrays - CH 8 29
CSIE@NUTN Using Array Elements as Function Arguments • Use array element x[i] as an input argument to function printf • When i is 3, the value of x[3] or 8. 0 is passed to printf and displayed Dr. Chow-Sing Lin Arrays - CH 8 30
CSIE@NUTN Using Array Elements as Function Arguments (Cont. ) • The call scanf(“%lf”, &x[i]); – Use array element x[i] as an output argument of scanf – When i is 4 • The address of array element x[4] is passed to scanf • scanf stores the next value scanned (2. 5) in element x[4] Dr. Chow-Sing Lin Arrays - CH 8 31
CSIE@NUTN Example 7. 6 • The function prototype below shows one type double input parameter (arg_1) and two type double * output parameters (arg 2_p and arg 3_p) void do_it (double arg_1, double *arg 2_p, double *arg 3_p); • If p, q, and r are declared as type double variables in the calling module do_it (p, &q, &r); – Passes the value of p to function do_it – Returns the function results to variables q and r Dr. Chow-Sing Lin Arrays - CH 8 32
CSIE@NUTN Example 8. 9 (Cont. ) • If x is declared as an array of type double elements in the calling module do_it (x[0], &x[1], &x[2]); • Array element x[0] is an input argument • Array element x[1] and x[2] are output arguments • In function do_it, use statement to return value to the calling module *arg 2_p = … *arg 3_p = … Dr. Chow-Sing Lin Arrays - CH 8 33
CSIE@NUTN Dr. Chow-Sing Lin Arrays - CH 8 34
CSIE@NUTN Exercises for Section 7. 4 • Write a statement that assigns to see_len the length of a line segment from xiyi to xi+1 yi+1 using the formula Answers seg_len = sqrt(pow(x[i + 1] – x[i], 2) + pow(y[I + 1] – y[i], 2)); Dr. Chow-Sing Lin Arrays - CH 8 35
CSIE@NUTN Array Arguments • Besides passing individual array elements to functions, we can write functions that have arrays as arguments. • Formal array parameter – Use array name , representing the address of initial array address, as formal parameter. – In the function body • Use subscripts with the formal parameter to access the array’s elements – The function manipulates the original array • An assignment to one of the array elements changes the contents of the original array. Dr. Chow-Sing Lin Arrays - CH 8 36
CSIE@NUTN Example 7. 7 • Figure shows a function that stores the same value (in_value) in all elements of the array corresponding to its formal array parameter list Argument declaration does not indicate how many elements are in lists Stores in_value in element i of its actual array argument Dr. Chow-Sing Lin Arrays - CH 8 37
CSIE@NUTN Argument Correspondence for Array Parameters • To call function fill_array – You must specify • The actual array argument • The number of array elements • The value to be stored in the array – If y is array with ten type int elements • The function call fill_array(y, 10, num); • Stores the value of num in the ten elements of array y Dr. Chow-Sing Lin Arrays - CH 8 38
CSIE@NUTN Argument Correspondence for Array Parameters (Cont. ) • To call function fill_array (Cont. ) – If x is a five-element array of type int values – The statement fill_array(x, 5, 1); • Cause function fill_array to store 1 in all elements of array x Dr. Chow-Sing Lin Arrays - CH 8 39
CSIE@NUTN Argument Correspondence for Array Parameters (Cont. ) • Data areas before return from fill_array (x, 5, 1); Dr. Chow-Sing Lin Arrays - CH 8 40
CSIE@NUTN Argument Correspondence for Array Parameters (Cont. ) • C stores the address of the type int variable x[0] in list – In fact, the following call is exactly like the call above. fill_array(&x[0], 5, 1); • For readability – When you call a function that processes the list the array represents, use the name of an array (with no subscript) Dr. Chow-Sing Lin Arrays - CH 8 41
CSIE@NUTN Argument Correspondence for Array Parameters (Cont. ) • Use of *list instead of list[ ] in a formal parameter list – In the declaration for function fill_array • We can use either parameter declaration : int list[ ] int *list Dr. Chow-Sing Lin Arrays - CH 8 42
CSIE@NUTN Arrays as Input Arguments • Array is only an input to the function and that the function does not intend to modify the array • This qualifier, const, allows the compiler to mark as an error any attempt to change an array element within the function Dr. Chow-Sing Lin Arrays - CH 8 43
CSIE@NUTN Arrays as Input Arguments (Cont. ) • Array input Parameter SYNTAX const element-type array-name[ ] or const element-type *array-name Dr. Chow-Sing Lin Example int get_min_sub (const double data[], /*input-array of numbers */ int data_size) /*input-number of elements */ { int i, small_sub; /*subscript of smallest value so far */ small_sub = 0; /*Assume first element is smallest */ for (i = 1; i < data_size; ++i ) if (data[i] < data[small_sub]) small_sub = i; return (small_sub); Arrays - CH 8 44 }
CSIE@NUTN Example 7. 8 • Function get_max in Figure can be called to find the largest value in an array An array input parameter Dr. Chow-Sing Lin Arrays - CH 8 45
CSIE@NUTN Example 7. 5 (Cont. ) • If x is a five-element array of type int values x_large = get_max(x, 5); – The statement causes function get_max to search array x for its largest element – Value is returned and stored in x_large Dr. Chow-Sing Lin Arrays - CH 8 46
CSIE@NUTN Returning an Array Result • Use an output parameter to send the result array back to the calling module • A function returning an array result depends on its caller to provide an array variable into which the result can be stored Dr. Chow-Sing Lin Arrays - CH 8 47
CSIE@NUTN Example 7. 9 • Function add_arrays adds two arrays Strictly input parameter Dr. Chow-Sing Lin Arrays - CH 8 48
CSIE@NUTN Example 7. 9 (Cont. ) • The sum of arrays ar 1 and ar 2 is defined as arsum such that arsum[i] is equal to ar 1[i] + ar 2[i] for each subscript i • The last parameter, n, specifies how many corresponding elements are summed • The formal parameter list declaration const double ar 1[ ], const double ar 2[ ], double arsum[ ], int n Dr. Chow-Sing Lin Arrays - CH 8 49
CSIE@NUTN Example 7. 9 (Cont. ) • If a calling function has declared three fiveele 3 ment arrays x, y, and x_plus_y with data – The call add_arrays(x, y, x_plus_y, 5); Dr. Chow-Sing Lin Arrays - CH 8 50
CSIE@NUTN Example 7. 9 (Cont. ) Dr. Chow-Sing Lin Arrays - CH 8 51
CSIE@NUTN Example 7. 9 (Cont. ) • After execution of the function – x_plus_y[0] will contain the sum of x[0] and y[0], or 3. 5 – x_plus_y[1] will contain the sum of x[1] and y[1], or 6. 7 • Input argument arrays x and y will be unchanged • Output argument arrays x_plus_y will have new contens x_plus_y after call to add_arrays 3. 5 Dr. Chow-Sing Lin 6. 7 4. 7 Arrays - CH 8 9. 1 12. 2 52
CSIE@NUTN Partially Filled Arrays • A program will need to process many lists of similar data – Lists may not all be the same length! • In order to reuse an array for processing more than one data set – Declares an array large enough to hold the largest data set anticipated Dr. Chow-Sing Lin Arrays - CH 8 53
CSIE@NUTN Example 7. 10 • Function fill_to_sentinel is to fill a type double array with data, until the designated sentinel value is encountered in the input data Dr. Chow-Sing Lin Arrays - CH 8 54
CSIE@NUTN Example 7. 10 (Cont. ) • Use an array that may be only partially filled (such as db 1_arr) – We must deal with two array sizes • Array’s declared size – Input parameter dbl_max • Size counting only the elements in use – Output parameter dbl_sizep Dr. Chow-Sing Lin Arrays - CH 8 55
CSIE@NUTN Fig 7. 11 Dr. Chow-Sing Lin Arrays - CH 8 56
CSIE@NUTN Fig 7. 12 Output argument Address-of operator & is applied Dr. Chow-Sing Lin Arrays - CH 8 57
CSIE@NUTN Stacks • A stack is a data structure in which only the top element can be accessed • Popping the stack – Remove the top element of a stack • Pushing it onto the stack – Insert a new element at the top of stack How do we access the symbol “+” ? Dr. Chow-Sing Lin C + + 2 2 Arrays - CH 8 C 2 + C 58
Stacks (Cont. ) Dr. Chow-Sing Lin Arrays - CH 8 CSIE@NUTN 59
CSIE@NUTN Stacks (Cont. ) char s[STACK_SIZE]; int s_top = -1; /* a stack of characters */ /* stack s is empty */ • Array s stores a stack of up to STACK_SIZE characters • s_top stores the subscript of the element at the top of the stack – Giving s_top an initial value of -1, ensures the first item pushed onto the stack will be stored in the stack element s[0] Dr. Chow-Sing Lin Arrays - CH 8 60
CSIE@NUTN Stacks (Cont. ) push (s, ‘ 2’, &s_top, STACK_SIZE); push (s, ‘+’, &s_top, STACK_SIZE); push (s, ‘c’, &s_top, STACK_SIZE); • The last character pushed (C) is at the top of the stack, array element s[2] Dr. Chow-Sing Lin Arrays - CH 8 61
CSIE@NUTN Searching and Sorting an Array • Searching an array to determine the location of a particular value • Sorting an array to rearrange the array elements in numerical order Dr. Chow-Sing Lin Arrays - CH 8 62
CSIE@NUTN Array Search • Linear search – In order to search an array • We need to know the array element value we are seeking • Search target – Perform the search • Examining in turn each array element using a loop • Testing whether the element matches the target – When the target value is found, search loop should be exited Dr. Chow-Sing Lin Arrays - CH 8 63
CSIE@NUTN Array Search (Cont. ) • Algorithm 1. Assume the target has not been found. 2. Start with the initial array element. 3. repeat while the target is not found and there are more array elements. 4. if the current element matches the target 5. Set a flag to indicate that the target has been found. 6. Advance to the next array element. 7. if the target was found 8. Return the target index as the search result. else 9. Return -1 as search result. Dr. Chow-Sing Lin Arrays - CH 8 64
CSIE@NUTN Figure 7. 14 Function That Searches for a Target Value in an Array Dr. Chow-Sing Lin Arrays - CH 8 65
CSIE@NUTN Sorting an Array • Selection sort – To perform a selection sort of an array with n elements • Subscripts 0 through n-1 – We locate the smallest element in the array – Switch the smallest element with the element at subscript 0 • Placing the smallest element in the first position Dr. Chow-Sing Lin Arrays - CH 8 66
CSIE@NUTN Sorting an Array (Cont. ) • Selection sort (Cont. ) – We locate the smallest element remaining in subarray with subscript 1 through n-1 and switch it with the element at subscript 1 • Placing the second smallest element in the second position – And so on …………. Dr. Chow-Sing Lin Arrays - CH 8 67
CSIE@NUTN Sorting an Array (Cont. ) • Algorithm for Selection Sort 1. for each value of fill from 0 to n-2 2. Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n-1]. 3 if fill is not the position of the smallest element (index_of_min) 4. Exchange the smallest element with the one at position fill. Dr. Chow-Sing Lin Arrays - CH 8 68
Figure 8. 16 Trace of Selection Sort Dr. Chow-Sing Lin Arrays - CH 8 CSIE@NUTN 69
Figure 7. 16 Function select_sort Dr. Chow-Sing Lin Arrays - CH 8 CSIE@NUTN 70
CSIE@NUTN Enumerated Types • Enumerated type – Allows associate a numeric code with each category by creating an enumerated type that has its own list of meaningful values – A data type whose list of values is specified by the programmer in a type declaration • typedef Dr. Chow-Sing Lin Simple Data Types - CH 7 71
CSIE@NUTN Enumerated Types (Cont. ) • For example, the enumerated type expense_t has eight possible values : typedef enum { entertainment, rent, utilities, food, clothing, automobile, insurance, miscellaneous } expense_t; Dr. Chow-Sing Lin Simple Data Types - CH 7 72
CSIE@NUTN Enumerated Types (Cont. ) • Declaration of variable expense_kind : expense_t expense_kind; – Defining type expense_t as shown cause the enumeration constant • entertainment to be represented as 0 • constant rent to be represented as integer 1 • utilities as 2, and so on Dr. Chow-Sing Lin Simple Data Types - CH 7 73
CSIE@NUTN Enumerated Types (Cont. ) • For types day_t, the following relations are true SYNTAX typedef enum {identifier_list} enum_type ; Example typedef enum {sunday, monday, tuesday, wednesday, thursday, friday, saturday} day_t ; Dr. Chow-Sing Lin Simple Data Types - CH 7 – sunday < monday – wednesday != friday – tuesday >= sunday 74
CSIE@NUTN Enumerated Types Example • Scans an integer representing an expense code and calls a function that uses a switch statement to display the code meaning Dr. Chow-Sing Lin Simple Data Types - CH 7 75
CSIE@NUTN Dr. Chow-Sing Lin Simple Data Types - CH 7 76
CSIE@NUTN • Enumeration constants must be identifiers – Cannot be numeric, character, or string literals • Type definitions immediately after any #define and #include directives – So it can be accessed through all part of your program. • The reserved word typedef can be used to name many varieties of user-defined types. Dr. Chow-Sing Lin Simple Data Types - CH 7 77
CSIE@NUTN Example 7. 12 • If today tomorrow are type day_t variables • The following if statement assigns the value of tomorrow based on the value of today if (today == saturday) tomorrow = sunday; else tommorrow = (day_t) (today + 1) • Because the days of a week are cyclical – tomorrow should be set to Sunday when today is Saturday Dr. Chow-Sing Lin Simple Data Types - CH 7 78
CSIE@NUTN Example 7. 12 (Cont. ) • The last value(saturday) in type day_t is treated separately – Because adding 1 to its integer representation yields a result not associated with a valid day_t value • C provides no range checking to verify that the value stored in an enumerated type variable is valid – today = saturday + 3 ; no runtime error although it is clearly invalid. Dr. Chow-Sing Lin Simple Data Types - CH 7 79
CSIE@NUTN Exercises for Section 7. 7 • Evaluate each of the following expressions – assuming before each operation that the value of variable today (type day_t) is thursday Answer typedef enum {monday, tuesday, wednessday, thursday, friday, saturday, sunday} dat_t ; (int) monday 0 today < tuesday 0 (False) (day_t) (today – 1) wednesday Dr. Chow-Sing Lin Simple Data Types - CH 7 80
CSIE@NUTN Multidimensional Arrays • An array with two or more dimensions SYNTAX element-type aname[size 1] [size 2] … [sizen]; element-type aname[ ] [size 2] … [sizen] /* storage allocation */ /* parameter in prototype */ Example double table[NROWS]; /* storage allocation */ void process_matrix (int in[] [4], int out[] [4], int nrows) /* input parameter */ /* output parameter */ /* input – number of rows */ The size of the first dimension (the number of rows) is the only size that can be omitted!! Dr. Chow-Sing Lin Arrays - CH 8 81
CSIE@NUTN Multidimensional Arrays (Cont. ) • The array declaration char tictac[3] [3]; – Allocates storage for a two-dimensional array (tictac) • Three rows and three columns – This array has nine elements • Each of which must be referenced – row subscript (0, 1, or 2) – Column subscript (0, 1, or 2) – Each array element contains a character value Dr. Chow-Sing Lin Arrays - CH 8 82
CSIE@NUTN Multidimensional Arrays (Cont. ) tictac [1][2] Dr. Chow-Sing Lin Arrays - CH 8 83
CSIE@NUTN Example 7. 14 • The array table double table[7][5][6] ; • Consists of three dimensions – The first subscript • Values from 0 to 6 – The second subscript • Values from 0 to 4 – The third subscript • Values from 0 to 5 Dr. Chow-Sing Lin Arrays - CH 8 84
CSIE@NUTN Example 7. 14 (Cont. ) • A total of 7 X 5 X 6, or 210, type double values may be stored in the array table • In order to access a single number, table[2][3][4], all three subscripts must be specified in each reference to array table Dr. Chow-Sing Lin Arrays - CH 8 85
CSIE@NUTN Initialization Multidimensional Arrays • Just like initialize one-dimensional arrays • The value are usually grouped by rows – Instead of listing all table values in one list • For example – Declare a tic-tac-toe board and initialize its contents to blanks char tictac[3][3] = { {‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘}}; Dr. Chow-Sing Lin Arrays - CH 8 86
CSIE@NUTN Figure 7. 21 Function to Check Whether Tic-tac-toe Board Is Filled Dr. Chow-Sing Lin Arrays - CH 8 87
CSIE@NUTN Array with Several Dimensions • The array enroll declared here int enroll [MAXCRS][5][4]; course campus year Dr. Chow-Sing Lin Arrays - CH 8 88
CSIE@NUTN Array with Several Dimensions (Cont. ) • Array enroll is composed of a total of 2000 (100 X 5 X 4) elements • When you are dealing with multidimensional arrays, a potential pitfall exists. – If several multidimensional arrays are declared in the same program, memory space can be used up rapidly. – Be aware of amount of memory space required by each large array in a program. Dr. Chow-Sing Lin Arrays - CH 8 89
CSIE@NUTN Example 7. 16 • Find and display the total number of students in each course for (course = 0 ; course<MASCRS; ++course) { crs_sum=0; for (campus=0; campus<5; ++campus) { for (cls_rank = 0; cls_rank < 4; ++cls_rank) { crs_sum += enroll[course][campus][cls_rank]; } } printf(“Number of students in course %d is %dn”, course, crs_sum); } Dr. Chow-Sing Lin Arrays - CH 8 90
CSIE@NUTN Array Processing Illustrated • Sequential access – Process the table rows or columns in sequence – Starting with the first and ending with the last • Random access – Access to element i + 1 of an array does not necessarily occur right after access to element i Dr. Chow-Sing Lin Arrays - CH 8 91
CSIE@NUTN Case Study – Summary of Hospital Revenue • Read Book Page 439 ~ 446 Dr. Chow-Sing Lin Arrays - CH 8 92
CSIE@NUTN Case Study (Cont. ) • Read Book Page 439 ~ 446 Dr. Chow-Sing Lin Arrays - CH 8 93
Figure 7. 24 Hospital Revenue Summary Main Function
Figure 7. 25 Function scan_table and Helper Function initialize
Figure 7. 25 Function scan_table and Helper Function initialize (cont’d)
Figure 7. 25 Function scan_table and Helper Function initialize (cont’d)
Figure 7. 26 Function display_table and Helper Functions display_quarter and whole_thousands
Figure 7. 26 Function display_table and Helper Functions display_quarter and whole_thousands (cont’d) 1 -99
CSIE@NUTN Common Programming Errors • Subscript-range error – When the subscript value used is outside the range specified by the array declaration • An out-of-range reference occurs – For the array celsius, int celsius[100]; • When celsius is used with a subscript – value less than 0 or greater than 99 a subscript-range error occurs Dr. Chow-Sing Lin Arrays - CH 8 100
CSIE@NUTN Common Programming Errors (Cont. ) • Subscript-range error – If the value of i is 150 • A reference to the subscripted variable celsius[i] may cause message access violation at line no. 28 • In ANSI C, the prevention of subscript-range errors is entirely the responsibility of the programmer. – Subscript-range errors are not syntax errors – They are not detected until program execution Dr. Chow-Sing Lin Arrays - CH 8 101
CSIE@NUTN Common Programming Errors (Cont. ) • Do remember to use the & on an array element that is being passed as an output argument • Use, int z[], to declare array parameters, instead of int *z, for declaring array input and output parameters in function prototype. Dr. Chow-Sing Lin Arrays - CH 8 102
- Slides: 102