Download presentation
Presentation is loading. Please wait.
Published byJonas Fitzgerald Modified over 8 years ago
1
Problem Solving and Program Design in C Chap. 7 Arrays Chow-Sing Lin
2
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 Lin2Arrays - CH8
3
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 Lin3Arrays - CH8
4
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 LinArrays - CH84
5
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 LinArrays - CH85
6
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 LinArrays - CH86
7
CSIE@NUTN Declaring and Referencing Arrays (Cont.) Dr. Chow-Sing LinArrays - CH87 StatementExplanation printf (“%.1f”, 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 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 16.012.028.026.02.512.014.0-54.5 x[0]x[1]x[2]x[3]x[4]x[5]x[6]x[7]
8
CSIE@NUTN Declaring and Referencing Arrays (Cont.) Array declaration Dr. Chow-Sing LinArrays - CH88 Element-type aname [size];/* uninitialized */ element-type aname [size] = {initialization list};/*initialized */ SYNTAX #define A_SIZE 5 ‧‧‧ double a[A_SIZE]; char vowels [ ] = {‘A’, ‘E’, ‘I’, ‘O’, ‘U’}; Example
9
CSIE@NUTN Example We declare two arrays for a student records program We assume that NUM_STUDENTS has already appeared in a #define directive Dr. Chow-Sing LinArrays - CH89 intid [NUM_STUDENTS]; doublegpa [NUM_STUDENTS]; #defineNUM_STUDENTS 50
10
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 LinArrays - CH810
11
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 LinArrays - CH811
12
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 LinArrays - CH812
13
CSIE@NUTN Arrays Initialization (Cont.) We initialize a 25-element array with the prime numbers less than 100 Dr. Chow-Sing LinArrays - CH813 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};
14
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. Dr. Chow-Sing LinArrays - CH814 doublesq_root [11]; intcube [11]; Answers
15
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 Dr. Chow-Sing LinArrays - CH815 aname [subscript] SYNTAX b [i + 1] Example
16
CSIE@NUTN Example 7.4 Dr. Chow-Sing LinArrays - CH816 StatementExplanation i = 5; printf (“%d %.1f”, 4, x[4]);Displays 4 and 2.5 (value of x[4]) printf (“%d %.1f”, i, x[i]);Displays 5 and 12.0 (value of x[5]) printf (“%.1f”, x[i] + 1);Displays 13.0 (value of x[5] plus 1) printf (“%.1f”, x[i] + i);Displays 17.0 (value of x[5] plus 5) printf (“%.1f”, x[i + 1]);Displays 14.0 (value of x[6]) printf (“%.1f”, x[i + i]);Invalid. Attempt to display x[10] printf (“%.1f”, x[2*i]);Invalid. Attempt to display x[10]
17
CSIE@NUTN Example 7.4 (Cont.) Dr. Chow-Sing LinArrays - CH817 StatementExplanation printf (“%.1f”, x[2 * i - 3]);Displays -54.5 (value of x[7]) printf (“%.1f”, x[(int)x[4]]);Displays 6.0 (value of x[2]) printf (“%.1f”, x[i++]);Displays 12.0 (value of x[5]); then assigns 6 to i printf (“%.1f”, 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] x[i] – 1 = x[i]Illegal assignment statement
18
CSIE@NUTN Exercises for Section 72 Show the contents of array x after executing the valid statements in Table 7.2 Dr. Chow-Sing LinArrays - CH818 Before : After : 16.012.06.08.012.014.0 -54.5 x[0]x[1]x[2]x[3]x[4]x[5]x[6]x[7]
19
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 LinArrays - CH819
20
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 Dr. Chow-Sing LinArrays - CH820 0149162536496481100 x[0]x[1]x[2]x[3]x[4]x[5]x[6]x[7]X[8]X[9]X[10]
21
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 LinArrays - CH821
22
CSIE@NUTN Statistical Computations Using Arrays (Cont.) Dr. Chow-Sing LinArrays - CH822 ①
23
CSIE@NUTN Dr. Chow-Sing LinArrays - CH823 ② ③
24
CSIE@NUTN Statistical Computations Using Arrays (Cont.) 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 LinArrays - CH824
25
CSIE@NUTN Statistical Computations Using Arrays (Cont.) Second loop (Cont.) – This loop implements the formulas Third loop – Displays a table – Each line of the table displays an array subscript an array element the different between that element x[i] - mean Dr. Chow-Sing LinArrays - CH825
26
CSIE@NUTN Statistical Computations Using Arrays (Cont.) Partial trace of computing for loop Dr. Chow-Sing LinArrays - CH826 Statementix[i]sumsum_sqrEffect sum = 0;0.0Initializes sum sum_sqr = 0;0.0Initializes sum_sqr for (i = 0;016.0Initializes i to 0 i < MAX_ITEM;Which is less than 8 ‧‧‧ sum += x[i];16.0Adds x[0] to sum sum_sqr += x[i] * x[i];256.0Adds 256.0 to sum_sqr
27
CSIE@NUTN Statistical Computations Using Arrays (Cont.) Dr. Chow-Sing LinArrays - CH827 Statementix[i]sumsum_sqrEffect increment and test i112.01 < 8 is true sum += x[i];28.0Adds x[1] to sum sum_sqr += x[i] * x[i];400.0Adds 144.0 to sum_sqr increment and test i26.02 < 8 is true sum += x[i];34.0Adds x[2] to sum sum_sqr += x[i] * x[i];436.0Adds 36.0 to sum_sqr
28
CSIE@NUTN Statistical Computations Using Arrays (Cont.) 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 LinArrays - CH828
29
CSIE@NUTN Statistical Computations Using Arrays (Cont.) Standard deviation (Cont.) – For MAX_ITEM data items If we assume that x is an array Lowest subscript is 0 The standard deviation formula : st_dev = sqrt (sum_sqr / MAX_ITEM mean * mean); Dr. Chow-Sing LinArrays - CH829 Standard deviation
30
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 LinArrays - CH830
31
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 LinArrays - CH831
32
CSIE@NUTN Example 7.6 The function prototype below shows one type double input parameter (arg_1) and two type double * output parameters (arg2_p and arg3_p) If p, q, and r are declared as type double variables in the calling module – Passes the value of p to function do_it – Returns the function results to variables q and r Dr. Chow-Sing LinArrays - CH832 void do_it (double arg_1, double *arg2_p, double *arg3_p); do_it (p, &q, &r);
33
CSIE@NUTN Example 8.9 (Cont.) If x is declared as an array of type double elements in the calling module 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 Dr. Chow-Sing LinArrays - CH833 do_it (x[0], &x[1], &x[2]); *arg2_p = … *arg3_p = …
34
CSIE@NUTN Dr. Chow-Sing LinArrays - CH834
35
CSIE@NUTN Exercises for Section 7.4 Write a statement that assigns to see_len the length of a line segment from x i y i to x i+1 y i+1 using the formula Dr. Chow-Sing LinArrays - CH835 seg_len = sqrt(pow(x[i + 1] – x[i], 2) + pow(y[I + 1] – y[i], 2)); Answers
36
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 LinArrays - CH836
37
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 Dr. Chow-Sing LinArrays - CH837 Stores in_value in element i of its actual array argument Argument declaration does not indicate how many elements are in lists
38
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 Stores the value of num in the ten elements of array y Dr. Chow-Sing LinArrays - CH838 fill_array(y, 10, num);
39
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 Cause function fill_array to store 1 in all elements of array x Dr. Chow-Sing LinArrays - CH839 fill_array(x, 5, 1);
40
CSIE@NUTN Argument Correspondence for Array Parameters (Cont.) Data areas before return from fill_array (x, 5, 1); Dr. Chow-Sing LinArrays - CH840
41
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. 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 LinArrays - CH841 fill_array(&x[0], 5, 1);
42
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 : Dr. Chow-Sing LinArrays - CH842 int list[ ] int *list
43
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 LinArrays - CH843
44
CSIE@NUTN Arrays as Input Arguments (Cont.) Array input Parameter Dr. Chow-Sing LinArrays - CH844 const element-type array-name[ ] or const element-type *array-name SYNTAX int get_min_sub (const double data[], /*input-array of numbers */ intdata_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); } Example
45
CSIE@NUTN Example 7.8 Function get_max in Figure can be called to find the largest value in an array Dr. Chow-Sing LinArrays - CH845 An array input parameter
46
CSIE@NUTN Example 7.5 (Cont.) If x is a five-element array of type int values – 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 LinArrays - CH846 x_large = get_max(x, 5);
47
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 LinArrays - CH847
48
CSIE@NUTN Example 7.9 Function add_arrays adds two arrays Dr. Chow-Sing LinArrays - CH848 Strictly input parameter
49
CSIE@NUTN Example 7.9 (Cont.) The sum of arrays ar1 and ar2 is defined as arsum such that arsum[i] is equal to ar1[i] + ar2[i] for each subscript i The last parameter, n, specifies how many corresponding elements are summed The formal parameter list declaration Dr. Chow-Sing LinArrays - CH849 const double ar1[ ], const double ar2[ ], double arsum[ ], int n
50
CSIE@NUTN Example 7.9 (Cont.) If a calling function has declared three five- ele3ment arrays x, y, and x_plus_y with data – The call add_arrays(x, y, x_plus_y, 5); Dr. Chow-Sing LinArrays - CH850
51
CSIE@NUTN Example 7.9 (Cont.) Dr. Chow-Sing LinArrays - CH851
52
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 Dr. Chow-Sing Lin Arrays - CH852 3.56.74.79.112.2 x_plus_y after call to add_arrays
53
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 LinArrays - CH853
54
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 LinArrays - CH854
55
CSIE@NUTN Example 7.10 (Cont.) Use an array that may be only partially filled (such as db1_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 LinArrays - CH855
56
CSIE@NUTN Fig 7.11 Dr. Chow-Sing LinArrays - CH856
57
CSIE@NUTN Fig 7.12 Dr. Chow-Sing LinArrays - CH857 Output argument Address-of operator & is applied
58
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 Dr. Chow-Sing LinArrays - CH858 C C + + 2 2 How do we access the symbol “+” ? C C + + 2 2 C C + + 2 2
59
CSIE@NUTN Stacks (Cont.) Dr. Chow-Sing LinArrays - CH859
60
CSIE@NUTN Stacks (Cont.) 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 LinArrays - CH860 char s[STACK_SIZE];/* a stack of characters */ int s_top = -1; /* stack s is empty */
61
CSIE@NUTN Stacks (Cont.) The last character pushed (C) is at the top of the stack, array element s[2] Dr. Chow-Sing LinArrays - CH861 push (s, ‘2’, &s_top, STACK_SIZE); push (s, ‘+’, &s_top, STACK_SIZE); push (s, ‘c’, &s_top, STACK_SIZE);
62
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 LinArrays - CH862
63
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 LinArrays - CH863
64
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 LinArrays - CH864
65
CSIE@NUTN Dr. Chow-Sing LinArrays - CH865 Figure 7.14 Function That Searches for a Target Value in an Array
66
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 LinArrays - CH866
67
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 LinArrays - CH867
68
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 LinArrays - CH868
69
CSIE@NUTN Dr. Chow-Sing LinArrays - CH869 Figure 8.16 Trace of Selection Sort
70
CSIE@NUTN Dr. Chow-Sing LinArrays - CH870 Figure 7.16 Function select_sort
71
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 LinSimple Data Types - CH771
72
CSIE@NUTN Enumerated Types (Cont.) For example, the enumerated type expense_t has eight possible values : Dr. Chow-Sing LinSimple Data Types - CH772 typedef enum { entertainment, rent, utilities, food, clothing, automobile, insurance, miscellaneous } expense_t;
73
CSIE@NUTN Enumerated Types (Cont.) Declaration of variable 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 LinSimple Data Types - CH773 expense_t expense_kind;
74
CSIE@NUTN Enumerated Types (Cont.) For types day_t, the following relations are true – sunday < monday – wednesday != friday – tuesday >= sunday Dr. Chow-Sing LinSimple Data Types - CH774 typedef enum {identifier_list} enum_type ; SYNTAX typedef enum {sunday, monday, tuesday, wednesday, thursday, friday, saturday} day_t ; Example
75
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 LinSimple Data Types - CH775
76
CSIE@NUTN Dr. Chow-Sing LinSimple Data Types - CH776
77
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 LinSimple Data Types - CH777
78
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 Because the days of a week are cyclical – tomorrow should be set to Sunday when today is Saturday Dr. Chow-Sing LinSimple Data Types - CH778 if (today == saturday) tomorrow = sunday; else tommorrow = (day_t) (today + 1)
79
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 LinSimple Data Types - CH779
80
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 Dr. Chow-Sing LinSimple Data Types - CH780 typedef enum {monday, tuesday, wednessday, thursday, friday, saturday, sunday} dat_t ; Answer (int) monday0 today < tuesday0 (False) (day_t) (today – 1)wednesday
81
CSIE@NUTN Multidimensional Arrays An array with two or more dimensions Dr. Chow-Sing LinArrays - CH881 element-type aname[size 1 ] [size 2 ] … [size n ];/* storage allocation */ element-type aname[ ] [size 2 ] … [size n ]/* parameter in prototype */ SYNTAX double table[NROWS] [NROWS];/* storage allocation */ void process_matrix (int in[] [4],/* input parameter */ int out[] [4],/* output parameter */ int nrows)/* input – number of rows */ Example The size of the first dimension (the number of rows) is the only size that can be omitted!!
82
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 LinArrays - CH882
83
CSIE@NUTN Multidimensional Arrays (Cont.) Dr. Chow-Sing LinArrays - CH883 tictac [1][2]
84
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 LinArrays - CH884
85
CSIE@NUTN Example 7.14 (Cont.) A total of 7X5X6, 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 LinArrays - CH885
86
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 Dr. Chow-Sing LinArrays - CH886 char tictac[3][3] = { {‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}};
87
CSIE@NUTN Figure 7.21 Function to Check Whether Tic-tac-toe Board Is Filled Dr. Chow-Sing LinArrays - CH887
88
CSIE@NUTN Array with Several Dimensions The array enroll declared here Dr. Chow-Sing LinArrays - CH888 int enroll [MAXCRS][5][4]; course campus year
89
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 LinArrays - CH889
90
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 %d\n”, course, crs_sum); } Dr. Chow-Sing LinArrays - CH890
91
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 LinArrays - CH891
92
CSIE@NUTN Case Study – Summary of Hospital Revenue Read Book Page 439 ~ 446 Dr. Chow-Sing LinArrays - CH892
93
CSIE@NUTN Case Study (Cont.) Read Book Page 439 ~ 446 Dr. Chow-Sing LinArrays - CH893
94
Figure 7.24 Hospital Revenue Summary Main Function
95
Figure 7.25 Function scan_table and Helper Function initialize
96
Figure 7.25 Function scan_table and Helper Function initialize (cont’d)
98
Figure 7.26 Function display_table and Helper Functions display_quarter and whole_thousands
99
1-99 Figure 7.26 Function display_table and Helper Functions display_quarter and whole_thousands (cont’d)
100
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 LinArrays - CH8100
101
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 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 LinArrays - CH8101 access violation at line no. 28
102
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 LinArrays - CH8102
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.