Problem Given 5 numbers, read them in and calculate their average THEN print out the ones that were above average Data Structure Needed Need some way to hold onto all the individual data items after processing them making individual identifiers x1, x2, x3,... is not practical or flexible the answer is to use an ARRAY a data structure - bigger than an individual variable or constant an Array you need a way to have many variables all with the same name but distinguishable! in math they do it by subscripts or indexes x 1 , x 2 , x 3 and so on in programming languages, hard to use smaller fonts, so use a different syntax x [1], x[0], table[3], point[i] Semantics numbered from 0 to n-1 where n is the number of elements all elements of an array have the same type 0 1 2 3 4 5 Properties of an array Homogeneous Contiguous Have random access to any element Ordered (numbered from 0 to n-1) Number of elements does not change - MUST be a constant when declared Syntax Declaration "type name[howmany];" refer to individual elements uses [ ] with index in the brackets most of the time cannot refer to the whole array as one thing, or just by the array name (only time you can is when passing a whole array to a function as an argument)
8 Declaration of an Array The index is also called the subscript In C++, the first array element always has subscript 0, the second array element has subscript 1, etc. The base address of an array is its beginning address in memory
Using a named constant it is very common to use a named constant to set the size of an array const int SIZE = 15; int arr[SIZE]; useful because it can be used to control loops throughout program easy to change if size of array needs to be changed Solution to problem int ct = 0, n[5], total = 0; float average; while (ct < 5) { cout << "enter a number "; cin >> n[ct]; total = total + n[ct]; ct = ct + 1; } cont'd on next slide Solution to problem - cont'd average = total / 5; ct = 0; while (ct < 5) { if (n[ct] > average) cout << n[ct]; ct = ct + 1; } the for loop since you need a loop with a counter often with an array, use a specialized one syntax for (initialization; condition; increment) body as usual, body can be one statement or a block of statements initialization usually sets a counter to zero condition tests counter for upper limit increment adds a value to counter Semantics of a for loop initialization happens ONCE, at start of loop execution the condition is tested next if the condition is true, body is executed increment is executed then condition is tested again if the condition is false, continue with statements AFTER body Scope of counter in a for loop if declare counter outside of the loop, it has usual scope (body of the function) can declare counter in header of loop for (int i = 0; i < 5; i++) then the scope is JUST the body of the loop - not outside the loop some old code assumed that was not true - when standard changed to state that, broke a lot of code! for and while loops are equivalent for (i = 0; i < 5; i++) { body } VERSUS i = 0; while (i < 5) { body i++; } Initialization of arrays int a[] = {1, 2, 9, 10}; // has 4 elements int a[5] = {2, 5, 4, 1, -2, 5}; // error! int a[5] = {2, 3}; // rest are zero int a[5] = {0}; // all are zero don't use this "zero initialization" with strings! objects don't take well to being set to a zero can use it with char, float, even bool Watch out index out of range! subscripts range from 0 to n-1 the compiler will NOT tell you if an index goes out of that range - it cannot detect can make very bad bugs from just garbage values in your data to crashing your computer to damaging your hard drive! 18 Assigning Values to Individual Array Elements float temps[5]; int m = 4; // Allocates memory temps[2] = 98.6; temps[3] = 101.2; temps[0] = 99.4; temps[m] = temps[3] / 2.0; temps[1] = temps[3] - 1.2; // What value is assigned?
temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 99.4 ? 98.6 101.2 50.6 19 What values are assigned? float temps[5]; // Allocates memory int m;
for (m = 0; m < 5; m++) { temps[m] = 100.0 + m * 0.2 ; } temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 ? ? ? ? ? 20 Now what values are printed? float temps[5]; // Allocates memory int m; . . . . . for (m = 4; m >= 0; m--) { cout << temps[m] << endl; }
temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 Indexes subscripts can be constants or variables or expressions if i is 5, a[i-1] refers to a[4] and a[i*2] refers to a[10] you can use i as a subscript at one point in the program and j as a subscript for the same array later - only the value of the variable matters 22 Variable Subscripts float temps[5]; // Allocates memory int m = 3; . . . . . . What is temps[m + 1] ?
What is temps[m] + 1 ? temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 Random access of elements problem : read in numbers from a file, only single digits - and count them - report how many of each there were use an array as a set of counters ctr [0] is how many zero's, ctr[1] is how many ones, etc. ctr[num] ++; is the crucial statement
Parallel arrays Sometimes you have data of different types that are associated with each other like name (string) and GPA (float) or name (string) and letter grade (char) cannot store them in the same array so use two different arrays "side by side" Parallel arrays, cont'd for (i = 0; i < 5; i ++) cin >> name[i] >> gpa[i]; logically the name in position i corresponds to the gpa in position i nothing in the syntax forces this to be true, you just have to program it to be so
26 Parallel Arrays
Parallel arrays are two or more arrays that have the same index range and whose elements contain related information, possibly of different data types
EXAMPLE const int SIZE 50; int idNumber[SIZE]; float hourlyWage[SIZE]; parallel arrays 27 const int SIZE 50; int idNumber[SIZE]; // Parallel arrays hold float hourlyWage[SIZE]; // Related information
idNumber[0] 4562 hourlyWage[0] 9.68
idNumber[1] 1235 hourlyWage[1] 45.75
idNumber[2] 6278 hourlyWage[2] 12.71
. . . . . . . . . . . .
idNumber[48] 8754 hourlyWage[48] 67.96
idNumber[49] 2460 hourlyWage[49] 8.97 Selection sort - 1-d array Algorithm for the sort 1. find the maximum in the list 2. put it in the highest numbered element by swapping it with the data that was at that location 3. repeat 1 and 2 for shorter unsorted list - not including highest numbered location 4. repeat 1-3 until list goes down to one Find the maximum in the list // n is number of elements max = a[0]; // value of largest element // seen so far for (i = 1; i < n; i++) // note start at 1, not 0 if (max < a[i]) max = a[i]; // now max is value of largest element in list Find the location of the max max = 0; // max is now location of the max for (i = 1; i < n; i++) if (a[max] < a[i]) max = i;
Swap with highest numbered element at right end of list is numbered n-1
temp = a[max]; a[max] = a[n-1]; a[n-1] = temp; Find next largest element and swap max = 0; for (i = 1; i < n-1; i++) // note n-1, not n if (a[max] < a[i]) max = i; temp = a[max]; a[max] = a[n-2]; a[n-2] = temp; put a loop around the general code to repeat for n-1 passes for (pass = n-1; pass >= 0; pass --) { max = 0; for (i = 1; i < pass; i++) if (a[max] < a[i]) max = i; temp = a[max]; a[max] = a[pass]; a[pass] = temp; }
2-dimensional arrays data sometimes has more structure to it than just "a list" has rows and columns uses two subscripts to locate an item syntax int a[5][4]; // row then column twenty elements, numbered from [0][0] to [4][3] 35 Two-Dimensional Array A two-dimensional array is a collection of components, all of the same type, structured in two dimensions, (referred to as rows and columns) Individual components are accessed by a pair of indexes representing the components position in each dimension DataType ArrayName[ConstIntExpr][ConstIntExpr]...; 36 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11] 66 64 72 78 85 90 99 105 98 90 88 80 row 2, col 7 might be Arizonas high for August EXAMPLE -- Array for monthly high temperatures for all 50 states
const int NUM_STATES = 50; const int NUM_MONTHS = 12; int stateHighs[NUM_STATES][NUM_MONTHS];
[0] [1] [2] . . stateHighs[2][7] . [48] [49]
Processing a 2-d array by rows finding the total for the first row for (i = 0; i < 5; i++) total = total + a[0][i]; finding the total for the second row for (i = 0; i < 5; i++) total = total + a[1][i];
Processing a 2-d array by rows total for ALL elements by adding first row, then second row, etc.
for (i = 0; i < 5; i++) for (j = 0; j < 4; j++) total = total + a[i][j];
Processing a 2-d array by columns total for ALL elements by adding first column, second column, etc.
for (j = 0; j < 4; j++) for (i = 0; i < 5; i++) total = total + a[i][j];
40 Finding the average high temperature for Arizona // assumes Arizonas data is in row 2 int total = 0; int month; int average; for (month = 0; month < NUM_MONTHS; month ++) total = total + stateHighs[2][month]; average = int (total / 12.0 + 0.5);
average 85
Passing an array as an argument by default arrays are passed by reference, do not need an & int fun1 (int arr[]); prototype and header nothing between the [] ! call the function as x = fun1 (myarr); // no [] at all! Arrays versus Files Arrays are usually smaller than files Arrays are faster than files Arrays are temporary, in RAM - files are permanent on secondary storage Arrays can do random or sequential, files we have seen are only sequential Passing a 2-d array as a argument a little bit different from 1-d arrays int fun1 (int arr [][SIZE]); only first subscript is left blank second (and more if higher dimensions) subscripts have to have values called as x = fun1 (myarr); where myarr is declared as int myarr[5][SIZE]; 44 Declaring Multidimensional Arrays Example of three-dimensional array