chapter 8 arrays dr. jiung-yao huang dept. comm. eng. nat. chung cheng univ. e-mail :...
Post on 21-Dec-2015
228 views
TRANSCRIPT
Chapter 8Arrays
Dr. Jiung-yao HuangDept. Comm. Eng.Nat. Chung Cheng Univ.E-mail : [email protected]: 鄭筱親 陳昱豪
3-2中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
本章重點
Declaring and referencing arraysWhen the array name with no subscript, it
represents an address, the address of the initial array element (陣列與指標的曖昧關係 )
const
3-3中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
3-4中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
3-6中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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]
3-7中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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];
3-9中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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}
3-10中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
ARRAY DECLARATION
SYNTAX: element-type aname [size];
EXAMPLE: #define A_SIZE 5
double a[A_SIZE];
char vowels [ ] = {‘A’, ‘E’, ‘I’, ‘O’, ‘U’};
3-11中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
8.2 ARRAY SUBCRIPTS
SYNTAX: aname [subscript]
EXAMPLE:
int prime[] = {2, 3, 5, 7} , i = 1;
printf(“%d”,prime[i]); /*result is 3*/
3-12中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
3-13中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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;
0 1 4 9 16 25 36 49 64 81 100
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]
3-14中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 loopfor (i=0; i<MAX_ITEM; ++i);
scanf(“%lf”, &x[i]);
3-15中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.3 Program to Print a Table of Differences
3-16中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.3 Program to Print a Table of Differences (cont’d)
3-17中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.4void do_it (double arg_1, double *arg2_P, double *arg3_p);do_it (p, &q, &r);do_it (x[0], &x[1], &x[2]);
3-18中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.4 Data Area for Calling Module and Function do_it
3-19中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
3-20中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
3-22中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
3-23中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.6 Data Areas Before Return from fill_array (x, 5, 1);
3-24中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
USE OF *list INSTEAD OF list[ ] IN A FORMAL PARAMETER LIST
Use either parameter declaration int list[ ] int *list
The first tells us that the actual argument is an array.
The second declaration would be equally valid for an integer array parameter.
3-25中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
3-26中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.7 Function to Find the Largest Element in an Array
3-27中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
3-28中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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);}
3-29中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.8 Diagram of a Function That Computes an Array Result
In C, it is not legal for a function’s return type to be an array.
3-30中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
3-32中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.10 Function Data Areas for add_arrays(x, y, x_plus_y, 5);
3-33中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.5 6.7 4.7 9.1 12.2
x_plus_y after call to add_arrays
& Not used
3-34中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
3-35中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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)
3-36中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.11 Diagram of Function fill_to_sentinel
3-37中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.12 Function Using a Sentinel-Controlled Loop to Store Input Data in an Array
3-39中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
STACKS
Stack A data structure in which only the top element
can be accessed.pop
Remove the top element of a stackpush
Insert a new element at the top of the stack應用
老鼠走迷宮,算式計算,呼叫副程式,改遞迴
3-40中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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+2
3-43中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
3-44中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 elements4. 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 element7. if the target was found
8. Return the target index as the search result else
9.Return -1 as the search result
3-45中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.15 Function That Searches for a Target Value in an Array
3-46中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
SORTING AN ARRAYALGORITHM 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
3-49中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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];
3-50中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.18 A Tic-tac-toe Board Stored as Array tictac
3-51中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Multidimensional Array Declaration
SYNTAX:element-type aname [size1] [size2] …[sizen]
element-type aname [ ] [size2] …[sizen] // prototype
EXAMPLES:double table [NROWS][NCOLS];
void process_matrix(int in[ ][4], int out[ ][4], int nrows)
3-52中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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'} };
3-53中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
3-54中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.19 Function to Check Whether Tic-tac-toe Board Is Filled
3-55中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
ARRAYS WITH SEVERAL DIMENSIONS
The array enroll declared int enroll [MAXCRS][5][4]
course campus year
year campus
course
3-57中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
8.8 ARRAY PROCESSING ILLUSTRATEDCASE 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.
3-59中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
CASE STUDY : Analysis of Sales Data(2/4)
Step 2: AnalysisData requirements
New typequarter_t {fall, winter, spring, summer}
Problem constantsNUM_SALES_PEOPLE 5NUM_QUARTERS 4
Problem inputsSales transaction filedouble sales [NUM_SALES_PEOPLE][NUM_QUARTERS]
Problem outputsdouble person_totals [NUM_SALES_PEOPLE]double quarter_totals [NUM_QUARTERS]
3-60中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
3-61中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
CASE STUDY : Analysis of Sales Data(4/4)
Step 4: Implementation (Figure 8.22 、 Figure 8.23)
Step 5: Testing
3-63中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.23 Function scan_table and Helper Function initialize
3-64中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.23 Function scan_table and Helper Function initialize (cont’d)
3-65中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.23 Function scan_table and Helper Function initialize (cont’d)
3-66中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.24 Function display_table and Helper Function display_quarter
3-67中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 8.24 Function display_table and Helper Function display_quarter (cont’d)
3-68中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 */
3-69中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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*/
…..
3-70中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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*/
3-71中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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[ ]
3-72中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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].
3-73中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.