560 likes | 700 Views
Arrays in C++ Lecture 5. one thing after another. 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
E N D
Arrays in C++ Lecture 5 one thing after another
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 • x1, x2, x3 and so on • in programming languages, use syntax • x [1], x[0], table[3], point[i]
C++ Arrays • An array is a consecutive group of memory locations. • Each group is called an element of the array. • The contents of each element are of the same type. • Could be an array of int, double, char, … • We can refer to individual elements by giving the position number (index) of the element in the array.
Array Usage • Powerful storage mechanism • Can issue command like: • "Do this to ith indexed variable"where i is computed by program • "Display all elements of array score" • "Fill elements of array score from user input" • "Find highest value in array score" • "Find lowest value in array score"
Memory and Arrays 4 bytes Each int is 4 bytes foo[0] foo[1] int foo[6]; foo[5]
C++ Arrays start at 0 !!!!!!! • The first element is the 0th element! • If you declare an array of n elements, the last one is number n-1. • If you try to access element number n it is an error! Create bogus values.
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
Array Subscripts • The element numbers are called subscripts. foo[i] Array name subscript A subscript can be any integer expression: These are all valid subscripts: foo[17] foo[i+3] foo[a+b+c]
Initialization • You can initialize an array when you declare it (just like with variables): int foo[5] = { 1,8,3,6,12}; double d[2] = { 0.707, 0.707}; char s[] = { 'R', 'P', 'I' };
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
Arrays of char are special • C++ provides a special way to deal with arrays of characters: char string1[] = "RPI without PI is like meat without eat"; • char arrays can be initialized with string literals.
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
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!
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? 7000 7004 7008 7012 7016 99.4 ? 98.6 101.2 50.6 temps[0] temps[1] temps[2] temps[3] temps[4]
What values are assigned? float temps[5];// Allocates memory int m; for (m = 0; m < 5; m++) { temps[m] = 100.0 + m * 0.2 ; } 7000 7004 7008 7012 7016 ? ? ? ? ? temps[0] temps[1] temps[2] temps[3] temps[4]
Now what values are printed? float temps[5];// Allocates memory int m; . . . . . for (m = 4; m >= 0; m--) { cout << temps[m] << endl; } 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 temps[0] temps[1] temps[2] temps[3] temps[4]
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
Variable Subscripts float temps[5];// Allocates memory int m = 3; . . . . . . What is temps[m + 1] ? What is temps[m] + 1 ? 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 temps[0] temps[1] temps[2] temps[3] temps[4]
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;
Arrays of Arrays • You can create an array of arrays: int a[2][2]; for (int i=0;i<2;i++) for (int j=0;j<2;j++) a[i][j] = i+j;
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]
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 component’s position in each dimension DataType ArrayName[ConstIntExpr][ConstIntExpr]...;
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] [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 Arizona’s high for August
Rows Of A 2D Array a[0][0] a[0][1] a[0][2] a[0][3] row 0 a[1][0] a[1][1] a[1][2] a[1][3] row 1 a[2][0] a[2][1] a[2][2] a[2][3] row 2
Columns Of A 2D Array a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] column 0 column 1 column 2 column 3
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];
Finding the average high temperature for Arizona // assumes Arizona’s 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];
Declaring Multidimensional Arrays Example of three-dimensional array const NUM_DEPTS = 5; // mens, womens, childrens, electronics, furniture const NUM_MONTHS = 12; const NUM_STORES = 3; // White Marsh, Owings Mills, Towson int monthlySales[NUM_DEPTS][NUM_MONTHS][NUM_STORES]; rows columns sheets