1 / 56

Arrays

Arrays. One Dimensional Arrays. A data structure used for storage of a collection of data items that are all the same type. Individual data items are stored in adjacent cells of main memory. . Declaring Arrays.

ave
Download Presentation

Arrays

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. Arrays

  2. One Dimensional Arrays • A data structure used for storage of a collection of data items that are all the same type. • Individual data items are stored in adjacent cells of main memory.

  3. Declaring Arrays • Assign one variable name to a collection of two or more adjacent memory cells. Must declare: typearray-name [size];

  4. Declaring Arrays • Examples:double temperature [5];

  5. double temperature [5]; 12.3 temperature [0] 7.5 temperature [1] 65.0 temperature [2] 72.1 temperature [3] 87.5 temperature [4]

  6. double temperature [5]; 12.3 temperature [0] 7.5 temperature [1] 65.0 temperature [2] Elements 72.1 temperature [3] 87.5 temperature [4]

  7. double temperature [5]; 12.3 temperature [0] 7.5 temperature [1] 65.0 temperature [2] SubscriptorIndex 72.1 temperature [3] 87.5 temperature [4]

  8. Printing the Array cout<<temperature [0];cout<<temperature [1];cout<<temperature [2];cout<<temperature [3];cout<<temperature [4];

  9. Printing the Array for(int i=0; i<5; i++) { cout<<temperature[i]<<endl; } Subscript Variable

  10. Assignment Statement temperature [4] = 12.7;orN = 4;temperature [N] = 12.7;

  11. Three ways to get values into array elements • Use assignment statements • Initialize arrays in the variable declaration statement • Read input values into the array from the keyboard or from a file

  12. Reading Arrays for(int i=0; i<5; i++) { cout<<“enter temperature “<<i<< “ “; cin>>temperature[i]; } cin>>temperature[0]>>temperature[1]>> temperature[2]>>temperature[3]>> temperature[4];

  13. Average Temperature double sum = 0.0; for(int i=0; i<5; i++) { sum += temperature[i]; } average = sum / 5.0;

  14. More About Array Declarations • We may use constants for the size in an array declaration:const int SIZE = 6;int score[SIZE];

  15. declaration: int score [6]; score: 49 75 65 90 77 70 index: 0 1 2 3 4 5 (Subscript) score[2] = 65; score[0] = 49;

  16. Accessing the Individual Elements of an Array • If a variable represents an array, we refer to the whole array when we use just the name of the variable ex. score

  17. Accessing Individual Elements • We access a particular array element by using the array name followed by the index in square brackets: sumTwo = score[3] + score[0];

  18. 1. Assigning Values • We cannot use assignment statements with entire arrays (some languages allow this, but most, including C++, do not handle it) • Instead, we must assign values to individual elements • We can use them as values in assignment statements: score[0] = 30; grade[3] = ‘A’; price[2] = 10.39;

  19. Using Array Elements • All of the following are valid:score[0] = 4;score[0] += 7;score[1] = score[0] -2;score[2] = score[1] + 5 * score[0]; score[j] = score[j + 1]; • Note: index can be any integral expression.

  20. 2. Declaration-Initialization • We can put initial values into an array at declaration time • We must list all of the values: they must all be constants:int num[5] = {58, 43, 60, 21, 38}; • We don’t have to specify the dimension of the array when we initialize it:int x[ ] = {4, 8, 30, 21, 56, 87};will be an array of six elements • Exception: you may initialize all elements of an array to 0 with int score_ary[10] = {0};

  21. Lec p. 132 Array Practice • Declare an array to hold the tax for up to 10 different sales. • Declare an array to hold the final letter grades for a class with up to 40 students • Declare an array of integers which holds the final average for those 40 students and initialize its values to 0 • Declare an array of characters called letter_ary with initial values ‘a’, ‘d’, ‘y’, and ‘w’. What is the value of letter_ary[1]?

  22. 3. Enter from keyboard or file • A for loop is an ideal way to read data into an array. This loop assumes we’re reading exactly 5 elements. for (i = 0; i < 5; i++) { cout << “Please enter a score: ”; cin >> score[i]; }

  23. Lec p. 133 More Array Practice • Write a loop to initialize all 50 elements of array salary_ary to 100. • Write C++ code to read values from the keyboard to fill the array scores. Input should stop when a negative number is entered. The maximum size of the array is in a constant ARR_SIZE. • Write C++ code to add up the first num_elements values in the array my_vals and store the sum in the variable my_sum.

  24. More Array Practice • Assume that your third array already has values. Now write a function to put the appropriate letter grades into the second function.

  25. Error! #include <iostream> using namespace std; int main() { int x[10] = {0, 1,2,3,4,5,6,7,8,9}; int n; cin >> n; int y[n]; //Line 10 - Here we have (illegally) declared //an array of non-constant size for( int i = 0; i < n; i++) cout << (y[i] = x[i]) << " " ; cout<< endl; return 0; } Must be a constant

  26. Display 9.1 Program using an Array //Reads in 5 scores and shows how much each //score differs from the highest score. #include <iostream> using namespace std; int main( ) { int i, score[5], max; cout << "Enter 5 scores:\n"; cin >> score[0]; max = score[0]; for (i = 1; i < 5; i++) { cin >> score[i]; if (score[i] > max) max = score[i]; //max is the largest of the values score[0],..., score[i]. } cout << "The highest score is " << max << endl << "The scores and their\n" << "differences from the highest are:\n"; for (i = 0; i < 5; i++) cout << score[i] << " off by " << (max - score[i]) << endl; return 0; }

  27. Dice Example • Write a C++ program to find the frequency distribution of all possible sums of the roll of two dice.

  28. What Do We Do with Arrays? • The most common tasks we perform with arrays are to: • Load information into an array for later processing • Process each element of an array • Find a particular element in an array • Write out the contents of an array

  29. Importance of Loops • Since we usually want to do something with all of the elements of an array, one at a time, we use loops constantly in array processing • Sometimes pre-testing loops are appropriate • Most often, we use counting loops that start with the first index and end with the last index

  30. Using Arrays with Functions • We can pass individual array elements to functions either by value or by reference • treat array element same as other variables in the call • prototype: void modifyElement(int num); • call: modifyElement(arr[3]); • function header: void modifyElement(int num) {

  31. Arrays and Functions, cont. • It’s often useful to have a function which passes an entire array as a parameter • Prototype:void ReadScores(int score[], int NumPlayers); • Call:ReadScore(score, NumPlayers); • Header: void ReadScores(int score[], int NumPlayers);

  32. Arrays and Functions, cont. • Once inside the function: we handle the elements just as we would elsewhere:ReadScores(int score[], int NumPlayers) { int i; for (i = 0; i < NumPlayers; i++) { cin >> score[i]); }}

  33. Note! • We cannotreturn arrays • However, if we pass an array to a function, we can modify its contents. So arrays are as if passed by reference. • To keep the elements of an array from being accidentally modified in a function use the const keyword in the prototype and header: • void PrintScores(const int score[],int numPlayers);

  34. Parallel Arrays • Sometimes we have more than one piece of information to go in our array. • For example, we might want an array of students • Each one should have an ID number, an average, and a letter grade • We would use three arrays • an ID array • an average array • and a letter grade array • The items found at a given index would all relate to the same student

  35. Parallel Arrays ID_arr: 222 123 445 346 771 708 index: 0 1 2 3 4 5 87.5 75.2 94.0 90.0 77.9 83.9 avg_arr: index: 0 1 2 3 4 5 grade_arr: B C A A C B index: 0 1 2 3 4 5

  36. Arrays of Structures struct StudentInfo { int stu_id; double avg; char grade; } to declare: StudentInfo Our_class[40]; to use members: Our_class[1].stu_id = 123; Our_class[0].grade = ‘A’;

  37. More Array Practice • Write a loop to initialize all 50 elements of array salary_ary to 100. • Suppose array elements chairs_ary[0] through chairs_ary[49] hold the number of chairs in Room 101 through 150, respectively. Write a loop to print the room number and number of chairs for each room.

  38. More Practice • Given an array containing the basketball scores for the 26 games played by the Redbirds this season, write a function to find and return the highest score to the calling function. Also write the function prototype and function call.

  39. Array and File Practice • Assume you have a file containing information about a store’s inventory. Each line of the file has a part number, a price, and a number on hand. Write a function to read data from this file into three parallel arrays. Remember that we don’t know ahead of time how many parts there are, but we will need to know later in the program.

  40. PROGRAMMING EXAMPLE: Searching an Array • The tasks of searching a data structure and sorting (rearranging data in a data structure to obey some order relation) and analysis to determine the time and space these tasks require as a function of the size of the data structure covers much of Computer Science. • We illustrate the search task using the sequential search algorithm on an array in Display 9.11. • This algorithm examines each element of the array in turn until the element is found, or there are no more array elements to examine.

  41. Shows the difference between each of a list of golf scores and their average. #include <iostream> using namespace std; const int MAX_NUMBER_SCORES = 10; void fill_array(int a[ ], int size, int& number_used); double compute_average(const int a[ ], int number_used); void show_difference(const int a[ ], int number_used); int main( ) { int score[MAX_NUMBER_SCORES], number_used; cout << "This program reads golf scores and shows\n" << "how much each differs from the average.\n"; cout << "Enter golf scores:\n"; fill_array(score, MAX_NUMBER_SCORES, number_used); show_difference(score, number_used); return 0; }

  42. void fill_array(int a[ ], int size, int& number_used) { cout << "Enter up to " << size << " nonnegative whole numbers.\n" << "Mark the end of the list with a negative number.\n"; int next, index = 0; cin >> next; while ((next >= 0) && (index < size)) { a[index] = next; index++; cin >> next; } number_used = index; }

  43. double compute_average(const int a[], int number_used) { double total = 0; for (int index = 0; index < number_used; index++) total = total + a[index]; if (number_used > 0) { return (total/number_used); } else { cout << "ERROR: number of elements is 0 in compute_average.\n" << "compute_average returns 0.\n"; return 0; } }

  44. void show_difference(const int a[ ], int number_used) { double average = compute_average(a,number_used); cout << "Average of the " << number_used << " scores = " << average << endl << "The scores are:\n"; for (int index = 0; index < number_used; index++) cout << a[index] << " differs from average by " << (a[index] - average) << endl; }

  45. Searches a partially filled array of nonnegative integers. const int DECLARED_SIZE = 20; void fill_array(int a[ ], int size, int& number_used); int search(const int a[ ], int number_used, int target); int main( ) { int arr[DECLARED_SIZE], list_size, target; fill_array(arr, DECLARED_SIZE, list_size); char ans; int result; do { cout << "Enter a number to search for: "; cin >> target; result = search(arr, list_size, target); if (result == -1) cout << target << " is not on the list.\n"; else cout << target << " is stored in array position " << result << endl << "(Remember: The first position is 0.)\n"; cout << "Search again?(y/n followed by return): "; cin >> ans; }while ((ans != 'n') && (ans != 'N')); cout << "End of program.\n"; return 0; }

  46. void fill_array(int a[ ], int size, int& number_used) { cout << "Enter up to " << size << " nonnegative whole numbers.\n" << "Mark the end of the list with a negative number.\n"; int next, index = 0; cin >> next; while ((next >= 0) && (index < size)) { a[index] = next; index++; cin >> next; } number_used = index; }

  47. int search(const int a[ ], int number_used, int target) { int index = 0; bool found = false; while ((!found) && (index < number_used)) if (target == a[index]) found = true; else index++; if (found) return index; else return -1; }

  48. PROGRAMMING EXAMPLE: Sorting an Array • Sorting an array means rearranging data in a data structure to obey some order relation. An array that contains objects that can be compared is sorted if for every pair of indices i and j. if i < j then array[i] <= array[j] • Said differently: a[0] <= a[1] <= a[2] <= . . . <= a[number_used - 1] • We illustrate sorting using the selection sort algorithm in Display 9.13. • The array is partially filled so we must pass an additional array parameter that specifies how many array elements are used.

  49. Selection Sort

  50. Tests the procedure sort. void fill_array(int a[ ], int size, int& number_used); void sort(int a[ ], int number_used); void swap_values(int& v1, int& v2); int index_of_smallest(const int a[ ], int start_index, int number_used); int main( ) { cout << "This program sorts numbers from lowest to highest.\n"; int sample_array[10], number_used; fill_array(sample_array, 10, number_used); sort(sample_array, number_used); cout << "In sorted order the numbers are:\n"; for (int index = 0; index < number_used; index++) cout << sample_array[index] << " "; cout << endl; return 0; }

More Related