750 likes | 762 Views
Learn how to declare and reference arrays in C programming, including array subscripts, array initialization, and using for loops for sequential access. Explore array arguments and common programming errors.
E N D
Chapter 8 Arrays Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. E-mail : comjyh@ccu.edu.tw TA: 鄭筱親 陳昱豪
本章重點 • Declaring and referencing arrays • When the array name with no subscript, it represents an address, the address of the initial array element (陣列與指標的曖昧關係) • const
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
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
id [0] gpa [0] 2.71 5503 id [1] gpa [1] 4556 3.09 id [2] 5691 2.98 gpa [2] … … id [49] 9146 1.92 gpa [49] PARALLEL ARRAYS • Two or more arrays with the same number of elements used for storing related information about a collection of data objects
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];
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}
ARRAY DECLARATION • SYNTAX: • element-type aname [size]; • EXAMPLE: #define A_SIZE 5 double a[A_SIZE]; char vowels [ ] = {‘A’, ‘E’, ‘I’, ‘O’, ‘U’};
8.2 ARRAY SUBCRIPTS • SYNTAX: • aname [subscript] • EXAMPLE: int prime[] = {2, 3, 5, 7} , i = 1; printf(“%d”,prime[i]); /*result is 3*/
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.
0 1 4 9 16 25 36 49 64 81 100 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; [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [0]
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]);
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]);
8.5 ARRAY ARGUMENTS • Formal array parameters • When an array name with no subscript appears in the argument list of a function call, theaddress 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
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.
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
Figure 8.6 Data Areas Before Return from fill_array (x, 5, 1);
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.
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
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
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); }
Figure 8.8 Diagram of a Function That Computes an Array Result In C, it is notlegal for a function’s return type to be an array.
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
Figure 8.10 Function Data Areas for add_arrays(x, y, x_plus_y, 5);
3.5 6.7 4.7 9.1 12.2 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 & Not used x_plus_y after call to add_arrays
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.
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)
Figure 8.12 Function Using a Sentinel-Controlled Loop to Store Input Data in an Array
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 • 應用 • 老鼠走迷宮,算式計算,呼叫副程式,改遞迴
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
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.
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
Figure 8.15 Function That Searches for a Target Value in an Array
SORTING AN ARRAYALGORITHM FOR SELECTING SORT • 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
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];