1 / 41

Arrays and Vectors Based on the original work of Dr. Roger deBry Version 1.0

Arrays and Vectors Based on the original work of Dr. Roger deBry Version 1.0. Topics. Arrays Multi-dimensional Arrays Vectors (STL). Objectives. At the completion of this topic, students should be able to:. Write programs that correctly * Declare and use arrays

luce
Download Presentation

Arrays and Vectors Based on the original work of Dr. Roger deBry Version 1.0

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 and VectorsBased on the original work of Dr. Roger deBryVersion 1.0

  2. Topics Arrays Multi-dimensional Arrays Vectors (STL)

  3. Objectives At the completion of this topic, students should be able to: Write programs that correctly * Declare and use arrays * Use loops to manipulate array elements * Pass arrays to functions Explain what an out of bounds error is Declare and use 2-dimensional arrays in a program Use the Vector from the Standard Template Library (STL)

  4. Motivation • Write a program that does the following: • Reads in 10 integer values from the user • Displays the sum of the values • Adds 5 to each value • Displays the new values and their sum

  5. int number1; int number2; int number3; int number4; . . . cout << “\nEnter in an integer value:”; cin >> number1; cout << “\nEnter in an integer value:”; cin >> number2; cout << “\nEnter in an integer value:”; cin >> number2; . . .

  6. int sum = number1 + number2 + … + number10; cout << “\nThe sum = “ << sum; number1 = numerb1 + 5; number2 = number2 + 5; number 3 = number3 + 5; . . . cout << “\nNumber1 = “ << number1; cout << “\nNumber2 = “<< number2; cout << “\nNumber3 = “ << number3; . . .

  7. What if I asked you to write a program like this, but let the user type in 1000 values? It could get pretty ugly!

  8. 0 1 2 3 4 5 6 7 8 9 An array is a list of values examScores All values must be of the same type 89 Values are stored in consecutive memory locations 94 78 The position where a value is stored in an array is given by its index. We sometimes refer to this as the subscript. 93 75 99 82 Indexing always begins with zero 77 To access an element of an array, we use the array name, followed by the index inside of square brackets 53 87

  9. 0 1 2 3 4 5 6 7 8 9 index examScores array name 89 94 78 93 75 value of examScores[4] 99 you can also use an expression, such as examScores[n+1]; or even *(examScores+n+1); 82 77 53 87

  10. 0 1 2 3 4 5 6 7 8 9 index examScores (examScores) base address 1200 89 1204 94 1208 78 examScores[4] 1212 93 1216 75 Array elements are stored in consecutive memory locations. The compiler calculates the address of a specific array element using the equation address = base address + index * element size 99 82 77 53 1200 + 4 * 4 87

  11. 0 1 2 3 4 5 6 7 8 9 Declaring an Array examScores array size data type of array elements int examScores[10]; the declaration Good programming style uses a constant for the array size. For example const int SIZE = 10; int examScores[SIZE];

  12. 0 1 2 3 4 5 6 7 8 9 Accessing Array Elements examScores 12 examScores [ 0 ] = 12; array name index (must be an integer value ) cout << examScores[0];

  13. 0 1 2 3 4 5 6 7 8 9 Arrays and Loops examScores int main ( ) { const int SIZE = 10; const int MULTIPLE = 3; int examScores [ SIZE ]; for ( int i = 0; i < SIZE; i++ ) { examScores[ i ] = i * MULTIPLE; } } 0 3 6 9 12

  14. Out of Bounds Errors When a C++ program is executing, it does not notice or even care, when a calculation results in an array index that is out of bounds. The address of the element is calculated using the equation given previously, and that place in memory is accessed, even if it does not belong to the array!

  15. index 0 0 someInts 1 someInts +4 1 int someInts[5], badNum; badnum = 100; for ( int indx = 0; indx <=5; indx++) { someInts[indx] = indx; } 2 someInts +8 2 3 someInts +12 3 4 someInts +16 4 badNum 100 5 Notice that we over-wrote the variable badNum with the value of 5! This destroys the original value in badNum.

  16. Initializer lists intexamScores [ ] = { 87, 83, 94, 99, 74, 66, 88 }; intexamScores[20] = {0}; //Values in array? the array size is automatically determined by the number of items in the initializer list

  17. Array Elements as Parameters Array elements can be passed just as any other parameter… for example given the function void printInteger (int n); we can pass an element of an integer array as printInteger (someData[n]);

  18. Arrays as Parameters the square brackets tell the compiler that an array will be passedor as void printEm(int* r, int size) void printEm( int r[], int size ) { for( int i = 0; i < size; i++ ) { cout << r[i] << “\n”; } } int main( ) { int mine[ ] = { 1, 2, 3, 4, 5 }; printEm ( mine, 5 ); } } it is normal to also pass the size of the array as a parameter. the array is passed in what is often called a simulated pass-by-reference, because it is just a pointer to the array that gets passed..

  19. const array parameters the const modifier prevents the function from changing any data in the array or void printEm(const int* r,int size) void printEm( constint r[], int size ) { for( inti = 0; i < size; i++ ) { cout << r[i] << “\n”; } } int main( ) { int mine[ ] = { 1, 2, 3, 4, 5 }; printEm ( mine, 5 ); } }

  20. Partially Filled Arrays Often in a program, you don’t know how much data will be stored in an array. So, you make the array some very large maximum size, and then keep track of how much data is in the array.

  21. Developing a Program that Uses An Array

  22. Arrays are used most often when writing an application that deals with tabular data, for example … Year Average rainfall (in) 4.5 5.4 3.9 7.1 6.9 7.3 5.8 4.9 4.4 5.1 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950

  23. Suppose that we are given the average amounts of rainfall • for each of ten consecutive years, and we want to find • The average over the ten year period • The standard deviation of the rainfall data Year Average rainfall (in) 4.5 5.4 3.9 7.1 6.9 7.3 5.8 4.9 4.4 5.1 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950

  24. Since we are going to process each of these data elements in turn as we do the calculations, an array is a handy way of storing the data. Year Average rainfall (in) 4.5 5.4 3.9 7.1 6.9 7.3 5.8 4.9 4.4 5.1 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950

  25. Declare the array float rainfall[10]; Year Average rainfall (in) 4.5 5.4 3.9 7.1 6.9 7.3 5.8 4.9 4.4 5.1 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950

  26. Read the data into the array (assume that the user enters data from the keyboard) float rainfall[10]; 4.5 5.4 3.9 7.1 6.9 7.3 5.8 4.9 4.4 5.1 const int TEN = 10; for (int i = 0; i < TEN; i++) { cout << “\nEnter the amount of rainfall” << “ for year “ << (i + 1) << “:”; cin >> rainfall[i]; }

  27. Calculate the average float rainfall[10]; float sum = 0; for (int i = 0; i < TEN; i++) { sum += rainfall[ i ]; } float average = sum / TEN; 4.5 5.4 3.9 7.1 6.9 7.3 5.8 4.9 4.4 5.1

  28. Calculate the standard deviation float rainfall[10]; • Standard deviation is a measure of how • closely the data points are clustered • around the mean. The standard deviation • is found by • Finding how much each data point differs • from the average. • (2) Squaring this difference. • (2) Summing up the squares of the differences • (3) Dividing by the number of data points - 1 • (4) And taking the square root of the result. 4.5 5.4 3.9 7.1 6.9 7.3 5.8 4.9 4.4 5.1

  29. Calculate the standard deviation float rainfall[10]; float sumDeviation = 0; float variation = 0; for (int i = 0; i < TEN; i++) { variation = (average – rainfall[ i ]); sumDeviation += variation * variation; } float stdDeviation = sqrt(sumDeviation / (TEN - 1 ) ); 4.5 5.4 3.9 7.1 6.9 7.3 5.8 4.9 4.4 5.1

  30. Two Dimensional Arrays columns rows How we think of a two dimensional array

  31. examScores 78 89 65 97 student 1 student 2 76 79 82 85 student 3 83 89 91 90 exam 1 exam 2 exam 3 exam 4

  32. An Array of Arrays 78 89 65 97 student 1 student 2 76 79 82 85 student 3 83 89 91 90 exam 1 exam 2 exam 3 exam 4

  33. int main( ) { // declare an array 3 x 4 intexamScores[ ][ ]= { {78, 89, 65, 97}, {76, 79, 82, 85}, {83, 89, 91, 90} }; const int STUDENT = 3; const int EXAMS = 4; for ( inti = 0; i < STUDENT; i++ ) { int sum = 0; for ( int j = 0; j < EXAMS; j++ ) sum = sum + examScores [ i ][ j ]; float avg = ((float)sum)/EXAMS; cout << “Student # “ << (i+1) << “: “ << avg << “\n”; } }

  34. Multi-dimensional array as a parameter… We do not give the size of the first dimension of an array when passing it, but we do give the sizes of the remaining dimensions. The size of the first dimension is passed as a separate argument. void getPage (char p[][100], int sizeOne);

  35. Vectors Vectors can be thought of as arrays that grow as required, while a program is executing. Vectors are formed from a template class in the Standard Template Library (STL). We will study templates and the Standard Template Library (STL) in some detail in CS 1410 .

  36. Declaring a Vector #include <vector> using namespace std; . . . vector <int> v; the notation <int> defines the type of vector. In this case, we have declared a Vector of integers. vector<double> vd; This is a vector of ??

  37. Accessing Vector Elements You can use the square bracket notation [ ] to access elements of a vector, just as you do for an array. Note however, that you can only access existing Vector elements this way, you cannot initialize them!

  38. Initializing Vector Elements To add an element to a Vector for the first time, you must use the push_back function. push_back adds an element in the next available position. v.push_back ( 23 );

  39. The size of a Vector As noted, the size of a Vector changes as needed, to accommodate new elements. The current size of a Vector ( the number of elements in the Vector ) can be found by unsigned int n = v.size( ); note that the size( ) function returns an unsigned int. This can be automatically converted to an int by most compilers. To be safe, do an explicit cast or use the unsigned int data type, as shown above.

  40. Example

  41. #include <iostream> #include <vector> using namespace std; int main ( ) { vector<int> v; cout << “Enter a list of positive numbers.\n”; cout << “End the list with a negative number.\n”; int next; cin >> next; while ( next > 0 ) { v.push_back( next ); cout << next << “ added to the Vector\n.”; cout << “v.size( ) = “ << v.size( ) << endl; cin >> next; } cout << “You entered:\n”; for ( unsigned int i = 0; i < v.size( ); i++ ) cout << v[ i ]; return 0; }

More Related