10/06/08MET CS Fall Arrays and Vectors 1 Multidimensional Types: 5. Arrays and Vectors Need: ability to define and manipulate variable objects that have multiple values and access the individual values separately f(x), x=1, 2,…,100 m(i, j), i=1,..5, j=1,…3 student(first="adam", last="smith", id=7814) all values are of the same type arrays and vectors values are of the different type structures and classes
Questions Asked When Introducing New Types: How do we declare / define objects initialize objects access objects and, if multidimensional, access values of individual elements/fields compute with objects and their individual fields: operators, IO, functions; pass object as parameter to & returned value from function 10/06/08MET CS Fall Arrays and Vectors 2
10/06/08MET CS Fall Arrays and Vectors Arrays: Declaration Examples 1. points in space with three coordinates (x, y, z): array with 3 elements of type float: float point[3]; 2. scores of a class of 30 students int scores[30]; point[0] point[1] point[2] point scores scores[0] scores[1] … scores[29] element or indexed variable [ ] - 1 index starts with 0, not 1
10/06/08MET CS Fall Arrays and Vectors 4 Declaration – Syntax: [ ] ;Notes: capacity is the maximal number of elements an array can hold size is the number of elements in array, size <= capacity the index starts from 0, not from 1; thus the index of the last element is - 1, while index points to the first free slot array occupies contiguous space in memory array-name a-name[0] … a-name[size-1] a-name[size] … a-name[capacity - 1 ] last element slot 1 st elementlast element 1 st free element slot must be const integral value
10/06/08MET CS Fall Arrays and Vectors 5 Array Access Examples: 1.cout << point[1]; 2. scores[9] = 89; cout << scores[6]; 3.Adding the values of all array elements: two alternative styles for loops: for ( i = 0; i < arraySize ; i++ ) total += a[ i ]; for ( i = 0; i < = arraySize - 1 ; i++ ) total += a[ i ]; Note: Note: The array element is a single valued variable of the corresponding type and behaves/can be manipulated as any other data object of this type. The 10th element of array point is assigned the value 89 The 7th element of array point is printed Indicates size of the array: PREFERRED Indicates range of index
10/06/08MET CS Fall Arrays and Vectors 6 Array Initialization Examples: 1. float point[3]= {1, 2, 3}; 2. int scores[30] = {0}; //all elements are initialized to 0 3. int scores[30] = {1, 2,3}; //first three elements are initialized to 1,2,3 //the remaining elements are initialized to 0 point[0]point[1]point[2]
10/06/08MET CS Fall Arrays and Vectors 7 Example: arrayBasics.cpp declaration initialization print array, ten elements per row sum all array elements increment all array elements add/remove elements from array (within capacity) and keep track of changes in array size
10/06/08MET CS Fall Arrays and Vectors 8 Definition: (vectorParameters.cpp) /** Prints array ten elements per a – int size - number of elements */ void print(int a[], int size) { for ( int i = 0; i < size ; i++ ){ cout<<setw(4)<< a[ i ]; if ( i % 10 == 9) cout << endl; } Call: const int CAPACITY = 30; int a[ CAPACITY ] = { 1, 3, 5, 4, 7}; int a_size = 5; … print(a, CAPACITY); print(a, a_size); Arrays as Parameters to Functions--Example Prototype: void print(int [], int);
10/06/08MET CS Fall Arrays and Vectors 9 Definition: return_type fct_name ( element_type ar_name [],type1 par1,…){…} void print ( int a[], int size) {…} Prototype: return_type fct_name ( element_type [],type1,…); void print( int [], int); Call: fct_name (ar_name, par1,…) print(a, CAPACITY); print(a, a_size); Arrays as Parameters to Functions--Syntax
10/06/08MET CS Fall Arrays and Vectors 10 Arrays Are Passed "By Reference" Important Implementation Fact: name of array a = address of first element and a[0] accesses the 1 st element … a[i] accesses the (i-1) element Therefore passing the name of the array to a function gives the function access to the actual object of the calling environment and allows the function to make changes to it, i.e. Arrays are always passed by reference!
10/06/08MET CS Fall Arrays and Vectors 11 The print function does not change any array elements. Good style requires that this is indicated by the const qualifier in the parameter list: void print(int a[], int size) {…} one should write void print( const int a[], int size) {…} The functionality remains exactly the same, but the addition explicitly shows entities that are not affected by the function. Use const to Indicate Function Does Not Change the Array—Example
10/06/08MET CS Fall Arrays and Vectors 12 Returning Arrays from Functions—Somewhat Tricky When passing an array to function we used the syntax el_type ar_name[] e.g. int a[] in the parameter list and el_type [] e.g. int [] in the prototype. It would seem logical to use the latter as a return type for an array, e.g. int [] doubler(int a[], int size);//ILLEGAL! Unfortunately this is illegal. (It also produces a bunch of syntax error messages not related to the real cause of the problem.) el_type [] is not a separate array type but just a notation to be used in the list of parameters passed to the function to indicate that the name of an array will be passed to the function. Arrays can be function parameters but not function return types!
10/06/08MET CS Fall Arrays and Vectors 13 Returning Arrays from Functions— References and Pointers We saw that there is no array return type. To still return an array from a function one must consider the following constraints: A function returns a single value An array has multiple values These two contradictory constraints can be satisfied in two ways: the array is changed directly in the function, which is in fact equivalent to a function returning values. Implementation is not a problem because the array is passed by reference to define and use a return type that can hold the name of the array, i.e. a memory address pointers
10/06/08MET CS Fall Arrays and Vectors 14 Example: arrayParameters.cpp Define and use the functions: void print( const int [], int ); void arrayIncrement(int [], int, int ); void arrayAddElements(int [], int&, int );
10/06/08MET CS Fall Arrays and Vectors 15 Example: Adding Elements to Array /** Adds elements to array as specified by user and reads in their a – int capacity - maximum number elements array can size - number of elements */ void arrayAddElements(int a[], int& size, int capacity) { cout << "How many elements do you want to add " <<"(at most " << capacity - size << " )"; int number; cin >> number; int init = size; cout << "Enter values for " << number << " new elements " << endl; for ( int i = init; i < init + number ; i++ ){ cin >> a[i]; size++; } Function needs both capacity and size size must be passed as a reference
10/06/08MET CS Fall Arrays and Vectors 16 // Fig. 5.1: Array Initialization and Adding All Elements const int arraySize = 12; int a[ arraySize ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 }; int total = 0; cout << "Print array a \n"; for ( int i = 0; i < arraySize ; i++ ) cout<< setw(4)<< a[ i ]; for ( i = 0; i < arraySize ; i++ ) total += a[ i ]; cout << "\nTotal of array element values is " << total << endl; int b[ arraySize ] = { 0 }; cout << "\nPrint array b \n"; for ( i = 0; i < arraySize ; i++ ) cout<<setw(4)<< b[ i ]; int c[ arraySize ] = {3, 3, 3, 0 }; cout << "\nPrint array c \n"; for ( i = 0; i < arraySize ; i++ ) cout<<setw(4)<< c[ i ]; return 0; Print array a Total of array element values is 383 Print array b Print array c
10/06/08MET CS Fall Arrays and Vectors 17 Sorting an array of integers In ascending order: Bubble Sort Pass through the array comparing any two neighbor elements a[i] and a[i+1], i = 0,1,…, - 2 and swapping them if a[i] > a[i+1] At the end of the 1st pass the largest value will "bubble up" to the last array position. Repeat the procedure till the entire array is sorted, i.e. a total of - 1 times (passes) Similarly when sorting in descending order the largest value will “sink” to the bottom of the array. This is why the bubble sort is also referred to as sink sort Files: swap.cpp, swap.h, arraysBubbleSort.cpp
10/06/08MET CS Fall Arrays and Vectors 18 Bubble Sort ( Bubble Sort (arraysBubbleSort.cpp) Enter 10 integers: You entered the following 10 integers: #include "swap.h" #include using namespace std; int main() { int const CAPACITY=20; int a[CAPACITY]; int size = 10; cout << "Enter " << size << " integers: \n"; for (int i=0; i < size; i++) cin >> a[i]; cout << "You entered the following " << size << " integers: \n"; for (int i=0; i < size; i++) cout << setw(4) << a[i];
10/06/08MET CS Fall Arrays and Vectors 19 // Bubble Sort - descending order The array sorted in descending order is: traversal from highest to lowest index Note: array elements are passed by value in function calls unless otherwise specified, as they are regular one-valued variables and treated as such. arrays are passed by reference as the name of the array is an address for (int pass=1; pass < size; pass++) for (int i=size-1; i > 0; i--) if(a[i-1] < a[i]) swap(a[i],a[i-1]); cout << "\n\nThe array sorted in descending order is:\n"; for (int i=0; i < size; i++) cout << setw(4) << a[i];
Function Definition and Header Files 10/06/08 MET CS Fall Arrays and Vectors 20 swap.cpp: #include "swap.h" void swap(int& a, int& b) { int s; s=a; a=b; b=s; } swap.h: #ifndef SWAP #define SWAP void swap(int&, int&); #endif SWAP