Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays and Records.

Similar presentations


Presentation on theme: "Arrays and Records."— Presentation transcript:

1 Arrays and Records

2 Overview To solve many programming problems, it is more efficient to group data items together in main memory than to allocate an individual memory cell for each variable. C allows a programmer to group such related data items together into a single composite data structure. In this chapter, we look at one such data structure: the array, which is a collection of data items of the same type.

3 Introduction to arrays, sequential access, and array arguments (CHAPTER 7.1-7.5)

4 Declaring and Referencing Arrays
An array is a collection of two or more adjacent memory cells, called array elements. Declaration double x[8]; instructs the compiler to associate eight memory cells with the 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 so, eight double number may be stored and referenced using the array name x

5 Example 7.1 Array x Statements that manipulate array x double x[8];
16.0 12.0 6.0 8.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

6 Example 7.1 Array x Statements that manipulate array x double x[8];
16.0 12.0 6.0 8.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); // Display the value of x[0], which is 16.0 x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

7 Example 7.1 Array x Statements that manipulate array x double x[8];
16.0 12.0 6.0 25.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; // Stores the value 25.0 in x[3] sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

8 Example 7.1 Array x Statements that manipulate array x double x[8];
16.0 12.0 6.0 25.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; // Stores x[0] + x[1], 28.0, in variable sum sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

9 Example 7.1 Array x Statements that manipulate array x double x[8];
16.0 12.0 6.0 25.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; // Adds x[2] to sum, = 34.0 x[3] += 1.0; x[2] = x[0] + x[1];

10 Example 7.1 Array x Statements that manipulate array x double x[8];
16.0 12.0 6.0 26.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; // Adds 1.0 to x[3], = 26.0 x[2] = x[0] + x[1];

11 Example 7.1 Array x Statements that manipulate array x double x[8];
16.0 12.0 28.0 26.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1]; // Stores x[0] + x[1], = 28.0 in x[2]

12 Initializing Arrays You can declare a variable without initialization
double average; /* Not initialized */ You can also declare a variable with initialization int sum = 0; /* Initialized to 0 */ Similarly, you can declare arrays without initialization double x[20]; /* Not initialized */ You can also declare an array and initialize it int prime[5] = {2, 3, 5, 7, 11}; No need to specify the array size when initializing it int prime[] = {2, 3, 5, 7, 11};

13 Array Initialization In the following statement, 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}; Array element prime_lt_100[24] is 97

14 Storing a String in an Array of Characters
If the list is long, you can use string instead of an initialization list char vowels[] = “This is a long string”; In this case, vowels[0] stores ‘T’, vowels[1] stores ‘h’, and so on.

15 Visualizing an Array in Memory
/* Array A has 6 elements */ int A[] = {9, 5, -3, 10, 27, -8}; 342900 342904 342908 342912 342916 342920 Memory Addresses 9 5 -3 10 27 -8 Array A 1 2 3 4 All arrays start at index 0 Array Index (subscript) Array Element

16 Array Subscripts Array subscript is used to differentiate between the individual array elements and to specify which array element is to be manipulated. The value of this subscript must be an integer between 0 and one less than the declared size of the array. Example: x[0] x[1] x[2] x[3] x[4] x[5] x[6] Subscripted variable x [ i ] , jika nilai i =2, maka subscript value =2

17 Array Subscripts Example: Array x Statement Explanation
16.0 12.0 6.0 8.0 2.5 14.0 -54.5 Statement Explanation i = 5; printf(“%d %.lf”, 4, x[4]); Displays 4 and 2.5 (value of x[4]) printf(“%.lf”, x[i] + 1) Display 13.0 (value of x[5] plus 1) printf(“%.lf”, x[i +1]) Display 14.0 (value of x[6]) printf(“%.lf”, x[i] + i) Display 17.0 (value of x[5] plus 5) printf(“%.lf”, x[2*i - 3]) Display (value of x[7])

18 Array Subscripts Example: Array x Statement Explanation
16.0 12.0 6.0 8.0 2.5 14.0 -54.5 Statement Explanation i = 5; printf(“%d %.lf”, x[(int)x[4]]); Displays 6.0 (value of x[2]) printf(“%.lf”, x[i++]) Display 12.0 (value of x[5]) then assign 6 to i printf(“%.lf”, x[--i]) Assign 5 (6-1) to i and then display 12.0 (value of x[5])

19 Using for Loops for Sequential Access
In C, we can process the elements of an array in sequence using an indexed for loop, a counting loop whose loop control variable runs from 0 to one less than the array size. Example: (assume SIZE has been defined to be 11) int square[SIZE], i; for (i=0; i < SIZE; i++) square[i] = i * i; [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 1 4 9 16 25 36 49 64 81 100

20 Using for Loops for Sequential Access
Statistical Computations Using Arrays One common use of arrays is for storage of a collection of related data values, which are used to perform some simple statistical computations. Example: sum = 0; for (i = 0; i < MAX_ITEM; i++){ sum += x[i]; }

21 Using for Loops for Sequential Access
sum_sqr = 0; for (i = 0; i < MAX_ITEM; i++){ sum_sqr += x[i] * x[i]; } st_dev = sqrt(sum_sqr / MAX_ITEM – mean * mean);

22 Using Array Elements as Function Arguments
The call printf(“%3d%4c%9.2f%5c%9.2f\n”, i, ‘ ‘, x[i], ‘ ‘, x[i] - mean); uses array element x[i] as an input argument to function printf. scanf(“%lf”, &x[i]); uses array element x[i] as an output argument to function scanf.

23 Using Array Elements as Function Arguments
Suppose that we have a function do_it defined as: void do_it(double x, double *p1, double *p2) { *p1 = x + 5; *p2 = x * x; } Let y be an array of double elements declared as: double y[6]; /* not initialized */ y[0] = 3.0; /* initialize y[0] */ We can call the function do_it as follows: do_it(y[0], &y[1], &y[2]); It will change the values of y[1] and y[2]

24 do_it(y[0], &y[1], &y[2]) Data Area of Caller do_it Data Area Array y
x y[0] y[1] y[2] y[3] y[4] y[5] 3.0 8.0 9.0 ? 3.0 p1 &y[1] p2 &y[2]

25 Array Arguments Argument Correspondence for Array Parameters
To call function fill_array, you must specify the actual array argument, the number of array elements, and the value to be stored in the array. If y is an 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.

26 Calling Function fill_array
To call fill_array, you must pass 3 arguments: Actual array name to fill Number of array elements to fill Value to store in array Examples of calling fill_array: /* fill 5 elements of x with 1 */ fill_array(x, 5, 1); /* fill 10 elements of y with num */ fill_array(y, 10, num);

27 fill_array(x, 5, 1); The address of array x is passed to list

28 Array Arguments Argument Correspondence for Array Parameters
In the declaration for function fill_array, we can use either parameter declaration: int list[] int *list The first tells us that the actual argument is an array. However, the second declaration would be equally valid for an integer array parameter as C passes an array argument py passing the address of its initial element.

29 Arrays as Input Arguments
The const keyword indicates that list[] is an input parameter that cannot be modified by the function /* Returns the max in an array of n elements */ /* Pre: First n elements of list are defined */ double get_max(const double list[], int n) { int i; double max = list[0]; for (i=1; i<n; ++i) if (list[i] > max) max = list[i]; return max; }

30 Array Arguments Returning an Array Result
In C, defining a function of the variety modeled in the figure below requires use of an output parameter to send the result array back to the calling module. input array (output parameters result parameter) When we use simple output parameters, the calling function must declare variables into which the function subprogram will store its results. function

31 Array Arguments Returning an Array Result Example:
void add_arrays (const double ar1[], const double ar2[], double arsum[], int n) { int i; /* Adds corresponding elements of ar1 and ar2 */ for (i=0; i<n; i++) arsum[i] = ar1[i] + ar2[i]; }

32 The formal parameter list declaration const double ar1[ ], const double ar2[ ], double arsum[ ], int n indicates that formal parameters ar1 , ar2 , and arsum stand for actual argument arrays whose elements are of type double and that ar1 and ar2 are strictly input parameters, as is n . The function can process type double arrays of any size as long as the preconditions stated in the initial block comment are met. If 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); would lead to the memory setup pictured

33

34 Partially Filled Arrays
The format of array declaration requires that we specify the array size at the point of declaration Moreover, once we declare the array, its size cannot be changed. The array is a fixed size data structure There are many programming situations where we do not really know the array size before hand For example, suppose we want to read test scores from a data file and store them into an array, we do not know how many test scores exist in the file. So, what should be the array size?

35 Partially Filled Arrays (cont'd)
One solution is to declare the array big enough so that it can work in the worst-case scenario For the test scores data file, we can safely assume that no section is more than 50 students We define the SIZE of the array to be 50 However, in this case, the array will be partially filled

36 Array Arguments Partially Filled Arrays
To reuse an array for processing more than one data set, the programmer often declares an array large enough to hold the largest data set anticipated. int main(void) { double arr[A_SIZE]; int in_use, i; fill_to_sentinel(A_SIZE, SENT, arr, &in_use); printf(“List of data values\n”); for (i=0; i<in_use; i++) printf(“%l3.3f\n”, arr[i]); return (0); }

37 SEARCHING AND SORTING AN ARRAY (CHAPTER 7.6)

38 Searching Traversing an array to locate a particular item
It requires the user to specify the target item If the target item is found, its index is returned If the target item is NOT found, -1 is returned Two searching algorithms Linear Search (works with any array) Binary Search (works if the searched array is sorted)

39 Linear Search Algorithm
Initialize a flag (zero) to indicate whether target is found Start at the first array element (at index 0) Repeat while the target is not found and there are more array elements If the current element matches the target then Set the flag to indicate that the target is found Else, Advance to the next array element If the target is found then Return the target index as the search result Else, Return -1 as the search result

40 Linear Search Implementation
/* Search array a[] for target using linear search * Returns index of target or -1 if not found */ int linear_search(const int a[], int target, int n) { int i = 0, found = 0; while (!found && i<n) { if (a[i] == target) found = 1; else ++i; } if (found) return i; else return -1;

41 Binary Search Algorithm
If an array is ordered, it is a waste of time to look for an item using linear search. It would be like looking for a word in a dictionary sequentially. Binary search works by comparing the target with the item at the middle of the array: If the target is the middle item, we are done. If the target is less than the middle item, we search the first half of the array. If the target is bigger than the middle item, we search the second half of the array. Repeat until target is found or nothing to search

42 Binary Search first mid last 5 11 target = 22 4 7 8 10 14 21 22 36 54 71 85 92 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] first mid last 6 8 11 4 7 10 14 21 22 36 54 71 85 92 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 22>21 first mid last 6 7 4 8 10 14 21 22 36 54 71 85 92 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 22<54 22==22

43 Sorting an Array Algorithm for each value of fill from 0 to n-1
Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n-1]. If fill is not the position of the smallest element (index_of_min) Exchange the smallest element with the one at position fill.

44 Sorting an Array Trace of Selection Sort fill is 0. [0] [1] [2] [3] 74
45 83 16

45 Sorting an Array Trace of Selection Sort fill is 0.
Find the smallest element in subarray list[0] through list[3] and swap it with list[0]. [0] [1] [2] [3] 74 45 83 16

46 Sorting an Array Trace of Selection Sort fill is 0.
Find the smallest element in subarray list[1] through list[3] and swap it with list[0]. [0] [1] [2] [3] 74 45 83 16

47 Sorting an Array Trace of Selection Sort fill is 0.
Find the smallest element in subarray list[1] through list[3] and swap it with list[0]. [0] [1] [2] [3] 16 45 83 74

48 Sorting an Array Trace of Selection Sort fill is 1.
Find the smallest element in subarray list[1] through list[3] and swap it with list[1]. [0] [1] [2] [3] 16 45 83 74

49 Sorting an Array Trace of Selection Sort fill is 1.
Find the smallest element in subarray list[1] through list[3] and swap it with list[1]. No exchange needed. [0] [1] [2] [3] 16 45 83 74

50 Sorting an Array Trace of Selection Sort fill is 2.
Find the smallest element in subarray list[2] through list[3] and swap it with list[2]. [0] [1] [2] [3] 16 45 83 74

51 Sorting an Array Trace of Selection Sort fill is 2.
Find the smallest element in subarray list[2] through list[3] and swap it with list[2]. [0] [1] [2] [3] 16 45 83 74

52 Sorting an Array Trace of Selection Sort fill is 2.
Find the smallest element in subarray list[2] through list[3] and swap it with list[2]. [0] [1] [2] [3] 16 45 74 83

53 Sorting an Array Trace of Selection Sort fill is 2.
Find the smallest element in subarray list[2] through list[3] and swap it with list[2]. [0] [1] [2] [3] 16 45 74 83

54 Sorting an Array Trace of Selection Sort [0] [1] [2] [3] 16 45 74 83

55 Sorting an Array

56 Smallest Element in Sub-Array
/* Find the smallest element in the sub-array list[first] * through list[last], where first<last * Return the index of the smallest element in sub-array */ int get_min_range(int list[], int first, int last) { int i; int index_min = first; for (i=first+1; i<=last; i++) { if (list[i] < list[index_min]) index_min = i; } return index_min;

57 PARALLEL ARRAYS, ENUMERATED TYPES, AND MULTIDIMENSIONAL ARRAYS (CHAPTER 7.7 & 7.8)

58 Two-Dimensional Arrays
A 2D array is a contiguous collection of elements of the same type, that may be viewed as a table consisting of multiple rows and multiple columns. To store the grades of 30 students in five courses, it is better to use a 2D array than five 1D arrays. Column Row 1 2 3

59 2D Array Declaration A 2D array is declared by specifying the type of element, the name of the variable, followed by the number of rows and the number of columns As with 1D arrays, it is a good practice to declare the row and column sizes as named constants: #define ROWS 3 #define COLS 4 . . . int table[ROWS][COLS]; Both rows and columns are indexed from zero. Column Row 1 2 3

60 Indexing 2D Arrays A 2D array element is indexed by specifying its row and column indices. The following statement stores 51 in the cell with row index 1, and column index 3: table[1][3] = 51; Here is another example: table[2][3] = table[1][3] + 6; 1 2 51 3 1 2 51 57 3 60

61 It is ok to omit the number of rows but not the number of columns
Initializing 2D Arrays As with 1-D arrays, you can declare and initialize a 2D array at the same time. A nested list is used, where each inner list represents a row. For example: int table[][4] = {{1,2,2,5},{3,4,6},{5,6,7,9}}; If you provide less values than the declared size, the remaining cells are set to zero (NOT a good practice!) 1 2 3 5 4 6 7 9 It is ok to omit the number of rows but not the number of columns


Download ppt "Arrays and Records."

Similar presentations


Ads by Google