1 / 25

Chapter 7

Chapter 7. Arrays. Introductions. Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students. int score1, score2; Declare 100 variables to store a test score of 100 students. int score1; … ; score100; Is it a smart ways? NO

Download Presentation

Chapter 7

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 7 Arrays

  2. Introductions • Declare 1 variable to store a test score of 1 student. int score; • Declare 2 variables to store a test score of 2 students. int score1, score2; • Declare 100 variables to store a test score of 100 students. int score1; … ; score100; • Is it a smart ways? NO • Solution: Arrays

  3. Array • a composite structure consisting of a list of data of the same type. • Syntax: type name[size]; //1-dimensional array type name[size1][size2]; //2-dimensional array • Examples int score[25]; //1-dimensional array int matrix[2][3]; //2-dimensional array

  4. Array Notes • subscripts start from 0. Can be any integral type. • may store data of any type – including structs, objects or other arrays. • Declaration: Square brackets after identifier indicate array. Number in brackets indicates number of elements in array. Must be a constant. • Size of array is determined at compiler time (static allocation); cannot be changed during runtime.

  5. Array Elements • Individual elements are accessed by using the name of the array and its index. int score[8], n=4; cin>> score[0] ; // user input and stored in score[0]. score[2]=3; // assign 3 to value stored in score[2] score[n+1]=8; // assign 8 to value stored in score[5] score[0]++;// increment value stored in score[3] score[n++] = 6; // assign 6 to value stored in score[4] and increase n by 1 (n=5) score[++n] = 10; // increment index to move to next value in the array (score[6]) and assign 10 to it. • By incrementing the subscript, we can access entire array in 1 loop. • Use a FOR loop to process. int size=8; for (int i=0;i<size;i++) { cout << “Enter the score #” << i ; cin >> score[i]; } • We can use WHILE loop, too. int n=0; while (n<size) { cout << “Score[” << n << “]: ” << score[n++] << endl; } 4 5 1020 score[0] 1022 score[1] 1024 3 score[2] 1026 score[3] 1028 6 score[4] 8 1030 score[5] 1032 score[6] 10 1034 score[7] 1036 1038

  6. Array Memory Allocation • Array elements are stored contiguously. • Need only know address of a[0]-compiler increments by size of type of array to find next value. • Caution: index out of range won’t produce error, just garbage and may overwrite good data. int a = score[8]; score[9] = 10; 1020 score[0] 5 1022 score[1] 7 1024 score[2] 3 1026 score[3] 7 1028 score[4] 6 1030 score[5] 8 1032 score[6] 10 1034 score[7] 4 1036 5 1038 10

  7. Array Initialization • No array size specified. Numbers of items will be used to determine the size int a[] = {3,4,5,2}; // sets up array from a[0] to a[3] (4 elements) • If number of initialized elements is less than array size then remaining elements are initialized to zero. int a[3] = {1}; // {1,0,0}; • Initialized all to zero. int a[3] = {0};

  8. Arrays in Functions (Single element) • An element of an array can be passed into any function requiring a variable of that type. • We can process each element of the array as a single value. • Can pass to a function as call-by-value or call-by-reference.

  9. Arrays in Functions (Single element) void main () { int score[5] = {7, 10, 8, 5, 9}; addOne(score[3]); isPass(score[4]); } void addOne (int& point) { point++; } bool isPass (int point) { return (++point >= 8); } score[0] 1020 7 score[1] 1022 10 score[2] 1024 8 score[3] 1026 5 score[4] 1028 9 score[0] 1020 7 score[1] 1022 10 score[2] 1024 8 score[3] 1026 6 9 score[4] 1028 9 score[0] 1020 7 score[1] 1022 10 score[2] 1024 8 score[3] 1026 6 score[4] 1028 9

  10. Entire Array as Function Arguments • Always passes in functions as call-by-reference. • The array name is the address of the first element. It is called the base address. • The ampersand (&) is implied and not written. • The [] in the formal parameter list tells the compiler that it is an array. We also need to pass in the size of the array. • The function call just passes in the array name.

  11. Entire Array as Function Arguments score[0] 1020 ? void main () { int score[5]; getScore(score, 5); } void getScore (int s[], int size) { for (int i=0; i<size; i++) { cout << “Enter score# ” << i; cin >> s[i]; } } score[1] 1022 ? score[2] 1024 ? score[3] 1026 ? score[4] 1028 ? score[0] 1020 7 score[1] 1022 10 score[2] 1024 8 score[3] 1026 5 score[4] 1028 9

  12. Entire Array as Function Arguments score[0] 1020 ? void main () { int score[5]; getScore(score, 5); printScore(score, 5); } void getScore (int s[], int size) { for (int i=0; i<size; i++) { cout << “Enter score# ” << i; cin >> s[i]; } } void printScore (int s[], int size) { for (int i=0; i<size; i++) { cout << “Score# ” << i << s[i] << endl; s[i]--; } } score[1] 1022 ? score[2] 1024 ? score[3] 1026 ? score[4] 1028 ? score[0] 1020 7 score[1] 1022 10 score[2] 1024 8 score[3] 1026 5 score[4] 1028 9 score[0] 1020 6 score[1] 1022 9 score[2] 1024 7 score[3] 1026 4 score[4] 1028 8

  13. const Array Argument • Passing in an array is a new kind of argument called an array argument • Since arrays are always passed-by-reference, if we want to prevent the contents of the array from changing, use const. • The word constin the function declaration prevents us from inadvertently changing the contents of the array. • Used in both function prototype and definition, not in function call. Failure to be consistent in using const in both places results in a linkage error.

  14. Entire Array as Function Arguments score[0] 1020 ? void main () { int score[5]; getScore(score, 5); printScore(score, 5); } void getScore (int s[], int size) { for (int i=0; i<size; i++) { cout << “Enter score# ” << i; cin >> s[i]; } } void printScore (const int s[], int size) { for (int i=0; i<size; i++) { cout << “Score# ” << i << s[i] << endl; //s[i]--; syntax error } } score[1] 1022 ? score[2] 1024 ? score[3] 1026 ? score[4] 1028 ? score[0] 1020 7 score[1] 1022 10 score[2] 1024 8 score[3] 1026 5 score[4] 1028 9 score[0] 1020 7 score[1] 1022 10 score[2] 1024 8 score[3] 1026 5 score[4] 1028 9

  15. Functions that Return an Array • Since to return an array is to return an address, a special type of variable is used. This is called a pointer. • At this point, we have no way to return a whole array. • We can, however, omit the const modifier and change the array that way.

  16. Programming with Arrays • Partially Filled Arrays • Since array allocation is static, may not use whole array. Choose array size to be largest possible amount but keep track of number of valid values entered. • Must pass in a parameter (int size) to indicate how many spaces have valid data.

  17. Partially Filled Arrays void main () { int score[25], count=0; getScore(score, 25, count); int indexOf5 = search(5, count); } void getScore(int s[], int size, int& num_used) { cout << “Enter up to ” << size << “non-negative numbers. \n” << “Enter a negative number to end.” << endl; int next, index=0; cin >> next; while (next >=0 && index < size) { s[index++] = next; cin >> next; } num_used = index; } Notes: • getScore must return number_used (call-by-reference) • Process until a sentinel value is read or max-size-1 reached. • Functions to process array functions must pass in number_used

  18. Sequential Search of an array • Go element by element until either target is found or reach end of list. //Pre-Condition: num_used cannot greater than the declared size // Also, s[0] through s[num_used] have values. //Post-Condition: return the index of the first occurrence of the target. // Otherwise, return -1 int search (const int s[], int num_used, int target) { for (int i=0; i<num_used; i++) { if (s[i] == target) return i; } return -1; }

  19. Find the smallest/largest Number • Go element by element to find the smallest/largest number. //Pre-Condition: size: numbers of elements in the array // Also, s[0] through s[size-1] have values. //Post-Condition: return the smallest number in the array. int smallest (const int s[], int size) { int theSmallest = s[0]; for (int i=0; i < size; i++) { if (s[i] < theSmallest) theSmallest = s[i]; } return theSmallest; }

  20. Sorting an Array • Arrange the elements of an array in a specific order. • Sorting algorithms: • Bubble sort • Selection sort • Insertion sort • Merge sort • Heapsort • Quicksort • …

  21. Selection Sort • Algorithm: finds the minimum value, swaps it with the value in the first position, and repeats these steps for the remainder of the list. • For Array:Finds the smallest element in an array and swaps it with the element in position 0. Then, finds the smallest element in the remaining array and swaps it with the element in position 1, etc.

  22. Index Of Smallest int IndexOfSmallest (const int a[], int startIndex, int num_used) { int min = a[startIndex], indexOfMin = startIndex; for (int i = startIndex+1; i < num_used; i++) if (a[i] < min) { min = a[i]; // min is the smallest number of a[startIndex] through a[i] indexOfMin = i; } return indexOfMin; } void swap (int& v1, int& v2) { int temp = v1; v1 = v2; v2 = temp; }

  23. SelectionSort() int SelectionSort(int a[], int num_used) { int indexOfNextSmallest; for (int i = 0; i < num_used-1; i++) { indexOfNextSmallest = IndexOfSmallest (a, i, num_used); swap (a[i], a[indexOfNextSmallest ]); } } a[0] a[1] a[2] a[5] a[4] a[5] a[6] a[7] a[8] a[9] i = 0 8 6 10 2 16 4 18 14 12 20 i = 1 2 6 10 8 16 4 18 14 12 20 i = 2 2 4 10 8 16 6 18 14 12 20 i = 3 2 4 6 8 16 10 18 14 12 20 i = 4 2 4 6 8 16 10 18 14 12 20 i = 5 2 4 6 8 10 16 18 14 12 20

  24. Multidimensional Arrays • Are arrays of arrays • Syntax: Type ArrayName[ROW][COL] //2-dimensional Type ArrayName[Width][Height][Depth] //3-dimensional • Examples: int matrix[2][3] //2x3 matrix int rubik[3][3][3] //cube

  25. 2-Dimensional Arrays • Initialization: int matrix[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; • if row size is unspecified, it is taken from the number of arrays in the brackets. Must always give column size. int matrix[][3] = { {1,2,3}, {4,5,6} }; // 2x3 int matrix[][3] = { {1,2,3}, {4,5,6}, {7,8,9} }; // 3x3 int matrix[][2] = { {1,2}, {3,4}, {5,6} }; // 3x2 • C++ stores all arrays as a single one-dimensional array. • The array name is a constant pointer to the first dimensional array. Col 1 Col 2 Col 3 1 2 3 Row 1 4 5 6 Row 2 7 8 9 Row 3 matrix[2][3] 1020 matrix[0][0] 1 1022 matrix[0][1] 2 1024 matrix[0][2] 3 matrix[1][0] 1026 4 1028 matrix[1][1] 5 matrix[1][2] 6 1030

More Related