Download presentation
Presentation is loading. Please wait.
Published byDuane Barnett Modified over 9 years ago
1
Chapter 8 Arrays Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. E-mail : comjyh@ccu.edu.tw TA: 鄭筱親 陳昱豪
2
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-2 本章重點 Declaring and referencing arrays When the array name with no subscript, it represents an address, the address of the initial array element ( 陣列與指標的曖昧關係 ) const
3
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-3 Outline 8.1 DECLARING AND REFERENCING ARRAYS 8.2 ARRAY SUBCRIPTS 8.3 USING FOR LOOPS FOR SEQUENTIAL ACCESS 8.4 USING ARRAY ELEMENTS AS FUNCTION ARGUMENTS 8.5 ARRAY ARGUMENTS 8.6 SEARCHING AND SORTING AN ARRAY 8.7 MULTIDIMENSIONAL ARRAYS 8.8 ARRAY PROCESSING ILLUSTRATED CASE STUDY: ANALYSIS OF SALES DATA 8.9 COMMON PROGRAMMING ERRORS
4
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-4 8.1 DECLARING AND REFERENCING ARRAYS To group data items together is more efficient and comprehensible Data structure A composite of related data items stored under the same name Array A collection of data items of the same type Array element A data item that is part of an array Subscripted variable A variable followed by a subscript in brackets, designating an array element Array subscript A value or expression enclosed in brackets after the array name, specifying which array element to access
5
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-5 Figure 8.1 The Eight Elements of Array x
6
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-6 PARALLEL ARRAYS Two or more arrays with the same number of elements used for storing related information about a collection of data objects 5503 4556 5691 … 9146 id [0] id [1] id [2] id [49] 2.71 3.09 2.98 … 1.92 gpa [0] gpa [1] gpa [2] gpa [49]
7
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-7 EXAMPLE 8.3 #define NUM_QUEST 10 #define NUM_CLASS_DAYS 5 typedef enum {monday, tuesday, wednesday, thursday, friday} class_days_t; char answer [NUM_QUEST]; int score [NUM_CLASS_DAYS];
8
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-8 Figure 8.2 Arrays answer and score
9
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-9 ARRAY INITIALIZATION Initialize a 25-elements 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}
10
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-10 ARRAY DECLARATION SYNTAX: element-type aname [size]; EXAMPLE: #define A_SIZE 5 double a[A_SIZE]; char vowels [ ] = {‘A’, ‘E’, ‘I’, ‘O’, ‘U’};
11
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-11 8.2 ARRAY SUBCRIPTS SYNTAX: aname [subscript] EXAMPLE: int prime[] = {2, 3, 5, 7}, i = 1; printf(“%d”,prime[i]); /*result is 3*/
12
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-12 8.3 USING FOR LOOPS FOR SEQUENTIAL ACCESS Use an indexed for loop, a counting loop whose loop control variable runs from zero to one less than the array size. Use the loop counter as an array index (subscript) gives access to each array element in turn.
13
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-13 EXAMPLE 8.7 The array square will be used to store the squares of the integers 0 through 10. The name SIZE has been defined to be 11. int square[SIZE], i; for (i=0;i<SIZE;++i) square [i]= i * i; 0149162536496481100 [0] [1][2][3][4][5][6][7][8][9][10]
14
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-14 STATISTICAL COMPUTATIONS USING ARRAYS One common use of arrays is for storage of a collection of related data values. Once the values are stored, we can perform some simple statistical computations. Figure 8.3 first for loop for (i=0; i<MAX_ITEM; ++i); scanf(“%lf”, &x[i]);
15
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-15 Figure 8.3 Program to Print a Table of Differences
16
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-16 Figure 8.3 Program to Print a Table of Differences (cont’d)
17
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-17 8.4 USING ARRAY ELEMENTS AS FUNCTION ARGUMENTS EXAMPLE 8.9: The function prototype below shows one type double input parameter(arg_1) and two double * output parameters(arg2_p and arg3_p). Figure 8.4 void do_it (double arg_1, double *arg2_P, double *arg3_p); do_it (p, &q, &r); do_it (x[0], &x[1], &x[2]);
18
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-18 Figure 8.4 Data Area for Calling Module and Function do_it
19
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-19 8.5 ARRAY ARGUMENTS Formal array parameters When an array name with no subscript appears in the argument list of a function call, the address of the initial array element is actually stored in the function’s corresponding formal parameter. The function manipulates the original array, not its own personal copy, so an assignment changes the original array
20
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-20 EXAMPLE 8.10 The statement list[i]=in_value stores in_value in element i of its actual array argument In function fill_array, the array parameter is declared as int list[ ] The argument declaration does not indicate the size of list. Since we do not provide the size, we have the flexibility to pass to the function an array of any number of integers.
21
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-21 Figure 8.5 Function fill_array
22
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-22 ARGUMENT CORRESPONDENCE FOR ARRAY PARAMETERS fill_array(y, 10, num) store the value num in the ten elements of array y fill_array(x, 5, 1) store 1 in five elements of array x Because C stores the address of the type int variable x[0] in list, the call of fill_array fill_array(&x[0], 5, 1) execute exactly like the call above
23
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-23 Figure 8.6 Data Areas Before Return from fill_array (x, 5, 1);
24
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-24 USE OF *list INSTEAD OF list[ ] IN A FORMAL PARAMETER LIST Use either parameter declaration int list[ ] int *lilst The first tells us that the actual argument is an array. The second declaration would be equally valid for an integer array parameter.
25
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-25 EXAMPLE 8.11 Function get_max in Fig. 8.7 can be called to find the largest value in an array. Use list as an array input parameter. If x is a five-element array of type int values, the statement x_large = get_max(x,5) used to search for largest element
26
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-26 Figure 8.7 Function to Find the Largest Element in an Array
27
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-27 ARRAY AS INPUT ARGUMENTS ANSI C provides a qualifier in the declaration of the array formal parameter in order to notify the C compiler that the array is only an input to the function and that the function does not intend to modify the array. const
28
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-28 ARRAY INPUT PARAMETER SYNTAX: const element-type array-name [ ] const element-type *array-name EXAMPLE: int get_min_sub(const double data[ ], int data_size) { int i, small_sub; small_sub=0; for (i=1; i<data_size; ++i) if (data[i] < data[small_sub]) small_sub=i; return(small_sub); }
29
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-29 Figure 8.8 Diagram of a Function That Computes an Array Result
30
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-30 EXAMPLE 8.12 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. n specifies how many corresponding elements are summed. The formal parameter list declaration const double ar1[ ] const double ar2[ ] double arsum[ ] int n
31
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-31 Figure 8.9 Function to Add Two Arrays
32
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-32 Figure 8.10 Function Data Areas for add_arrays(x, y, x_plus_y, 5);
33
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-33 x_plus_y after call to add_arrays We assume that a calling function has declared three five-element arrays x, y, and x_plus_y and has filled x and y with data. The call add_arrays(x, y, x_plus_y, 5) lead to 3.56.74.79.112.2 x_plus_y after call to add_arrays & Not used
34
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-34 PARTIALLY FILLED ARRAYS In order to reuse an array for processing more than one data set, the programmer declares an array large enough to hold the largest data set anticipated.
35
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-35 EXAMPLE 8.13 The purpose of function fill_to_sentinel is to fill a type double array with data until the designated sentinel value is encountered in the input data. (Figure 8.11)
36
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-36 Figure 8.11 Diagram of Function fill_to_sentinel
37
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-37 Figure 8.12 Function Using a Sentinel- Controlled Loop to Store Input Data in an Array
38
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-38 Figure 8.13 Driver for Testing fill_to_sentinel
39
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-39 STACKS Stack A data structure in which only the top element can be accessed. pop Remove the top element of a stack push Insert a new element at the top of the stack 應用 老鼠走迷宮,算式計算,呼叫副程式,改遞迴
40
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-40 EXAMPLE char s[STACK_SIZE]; Int s_stop = -1; push(s, ‘2’, &s_stop, STACK_SIZE); push(s, ‘+’, &s_stop, STACK_SIZE); push(s, ‘C’, &s_stop, STACK_SIZE); C+2C+2
41
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-41 Figure 8.14 Functions push and pop
42
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-42 Figure 8.14 Functions push and pop (cont’d)
43
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-43 8.6 SEARCHING AND SORTING AN ARRAY Array search In order to search an array, we need to know the search target. The search loop should be exited when the target value is found that the process is called a linear search.
44
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-44 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 else 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 the search result
45
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-45 Figure 8.15 Function That Searches for a Target Value in an Array
46
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-46 SORTING AN ARRAY ALGORITHM FOR SELECTING SORT 1.for each value of fill from 0 to n-2 2. Find index_of_min, the index of the smallest 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 with the one at position fill
47
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-47 Figure 8.16 Trace of Selection Sort
48
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-48 Figure 8.17 Function select_sort
49
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-49 8.7 MULTIDIMENSIONAL ARRAYS Multidimensional array An array with two or more dimensions A two-dimensional object that many are familiar with is a tic-tac-toe board. The array declaration char tictac[3][3];
50
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-50 Figure 8.18 A Tic-tac-toe Board Stored as Array tictac
51
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-51 Multidimensional Array Declaration SYNTAX: element-type aname [size 1 ] [size 2 ] …[size n ] element-type aname [ ] [size 2 ] …[size n ] // prototype EXAMPLES: double table [NROWS][NCOLS]; void process_matrix(int in[ ][4], int out[ ][4], int nrows)
52
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-52 Initialization of Multidimensional Arrays You can initialize multidimensional arrays in their declarations just like you initialize one- dimensional arrays. Instead of listing all table values in one list, the values are usually grouped by rows. Example: char array[2][2] = { { 'a‘, ‘b'}, {‘c', ‘d'} };
53
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-53 EXAMPLE 8.15 Function filled checks whether a tic-tac-toe board is completely filled. If board contains no cells with the value ‘ ‘, the function returns 1 for true; otherwise, it returns 0 for false.
54
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-54 Figure 8.19 Function to Check Whether Tic-tac-toe Board Is Filled
55
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-55 ARRAYS WITH SEVERAL DIMENSIONS The array enroll declared int enroll [MAXCRS][5][4] course campusyear campus course
56
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-56 Figure 8.20 Three-Dimensional Array enroll
57
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-57 8.8 ARRAY PROCESSING ILLUSTRATED CASE STUDY : Analysis of Sales Data(1/4) ( 自修 ) Step 1: Problem The sales manager of your company needs a sales analysis program to track sales performance by salesperson and by quarter. The program will read all sales transactions from a text file. The data for each transaction will be the salesperson’s number, the quarter in which the sale took place, and the sales amount. The sales transactions are in no particular order. After scanning all sales transactions, the program should display a table in the form shown in Fig. 8.21, which totals by person and by quarter.
58
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-58 Figure 8.21 Sales Analysis Output
59
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-59 CASE STUDY : Analysis of Sales Data(2/4) Step 2: Analysis Data requirements New type quarter_t {fall, winter, spring, summer} Problem constants NUM_SALES_PEOPLE 5 NUM_QUARTERS 4 Problem inputs Sales transaction file double sales [NUM_SALES_PEOPLE][NUM_QUARTERS] Problem outputs double person_totals [NUM_SALES_PEOPLE] double quarter_totals [NUM_QUARTERS]
60
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-60 CASE STUDY : Analysis of Sales Data(3/4) Step 3: Design Initial algorithm 1.Scan sales data, posting by salesperson and quarter, and returning a value to show success or failure of the data scan. 2.if the data scan proceeded without error 3. Compute salesperson totals (row sums) 4. Compute quarterly totals (column sums) 5. Display the sales table along with the row and column sums
61
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-61 CASE STUDY : Analysis of Sales Data(4/4) Step 4: Implementation (Figure 8.22 、 Figure 8.23) Step 5: Testing
62
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-62 Figure 8.22 Sales Analysis Main Function
63
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-63 Figure 8.23 Function scan_table and Helper Function initialize
64
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-64 Figure 8.23 Function scan_table and Helper Function initialize (cont’d)
65
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-65 Figure 8.23 Function scan_table and Helper Function initialize (cont’d)
66
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-66 Figure 8.24 Function display_table and Helper Function display_quarter
67
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-67 Figure 8.24 Function display_table and Helper Function display_quarter (cont’d)
68
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-68 Common Programming Errors (1/4) The most common error in using arrays is a subscript-range error. Ecample: int array[10]; array[10] = 10; /*the value is */ /* from 0 to 9 */
69
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-69 Common Programming Errors (2/4) If a subscript-range error occurs inside an indexed loop, verify that the subscript is in range for both the initial and the final values of the loop control variable. Example: int array[5], i; for ( i = 1; i <= 5; i++) /*range is 0 to 4*/ …..
70
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-70 Common Programming Errors (3/4) Not to apply the address-of operator to the array name even if the array is an output argument. Example: int array[5]; go(&array); /*Wrong using*/
71
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-71 Common Programming Errors (4/4) Use the correct forms for declaring array input and output parameters in function prototypes. Example: int *z /*It could represent a single integer output*/ /*parameter or an integer array parameter.*/ int z[ ]
72
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-72 Chapter Review(1/2) An array is a data structure used to store a collection of data items of the same type. An individual array element is referenced by replacing immediately after the array name a square-bracketed subscript for each dimension. The initial element of a one-dimensional array x is referenced as x[0]. If x has n elements, the final element is referenced as x[n-1].
73
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-73 Chapter Review(2/2) For an array declared as a local variable, space is allocated in the function data area for all the array elements. For an array declared as a function parameter, space is allocated in the function data area for only the address of the initial element of the actual argument passed. The name of an array with no subscript always refers to the address of the initial array element. A function that creates an array result should require the calling module to pass an output argument array in which to store the result.
74
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-74 Question?
75
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-75 Array 的宣告跟使用 宣告時, 只有兩種情況可以少填第一個維度, 其他均要填 [ ] 內的值 未配置空間,僅作定義用 Formal parameters int getmax(int n, int list[]) External variables extern int a[]; Initialization 可得知第一個維度的個數時 使用時, 均要填 [ ] 內的值
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.