1 / 25

Arrays

Arrays. Dr. Jose Annunziato. Arrays. Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances of data of the same type Arrays contain (or refer) to several pieces data stored in contiguous memory spaces.

nubia
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 Dr. Jose Annunziato

  2. Arrays • Up to this point we have been working with individual primitive data types • Arrays allow working with multiple instances of data of the same type • Arrays contain (or refer) to several pieces data stored in contiguous memory spaces

  3. Declaring and Sizing Arrays • Arrays are declared using square brackets arrayTypearrayName [ arraySize ]; • Here are several arrays of various primitive types char letters [ 25 ]; int miles [ 100 ]; float temperatures [ 12 ]; double distances [ 200 ]; • The total amount of space allocated is the size of the array times the size of type

  4. Reading and Writing to Arrays • Array content can be referenced by a zero-basedindex or subscript • Use the assignment operator to write to the array temperatures [ 12 ] = 77.34; • Use the array in right hand expression to read float tonightsTemperature = temperatures [ 12 ];

  5. Input and Output to/from Arrays • Individual array elements behave as variables int balances [ DAYS_IN_WEEK ]; cin >> balances [ 0 ]; cin >> balances [ 1 ]; … cin >> balances [ 4 ]; cout << balances [ 0 ]; … cout << balances [ 4 ];

  6. Iterating Over Arrays • Since indices are integers, we can iterate over the size of the array int balance [ DAYS_IN_WEEK ]; for ( int d = 0; d < DAYS_IN_WEEK; d++ ) cin >> balance [ d ]; for ( int d = 0; d < DAYS_IN_WEEK; d++ ) cout << balance [ d ];

  7. Avoid Edge Condition Errors • Note that array indices are 0 based • The first 1st index of an array of size of 100 is 0 and the last index is 99 int a [ 100 ]; int a [ 0 ] = 123; … int a [ 99 ] =234; • When iterating make sure to stay within bounds for ( inti = 0; i < 100; i++ ) count << a [ i ] << endl;

  8. Reading An Account Into an Array • We can use an array to represent each of the columns in an array • Consider reading the first 10 rows of an account string date [ 10 ]; string type [ 10 ]; string description [ 10 ]; float amount [ 10 ]; float balance [ 10 ];

  9. Get Each Row and Parse Into Array accountFile.open ("checking.csv"); string row; for( int r = 0; r < 10; r++ ) { getline (accountFile,row); date [ r ] = parseCsvRow ( row, 0 ); type [ r ] = parseCsvRow ( row, 1 ); description [ r ] = parseCsvRow ( row, 2 ); amount [ r ] = atof ( parseCsvRow ( row, 3 ).c_str() ); balance [ r ] = atof ( parseCsvRow ( row, 4 ).c_str() ); } accountFile.close();

  10. ParseCsvRowDemo.cpp

  11. Writing Arrays Into An Account ofstreamaccountFile; accountFile.open(fileName, ios::out | ios::app); for ( int r = 0; r < 10; r++ ) { accountFile << date[ r ] << ","; accountFile << type [ r ] << ","; accountFile << description [ r ] << ","; accountFile << amount [ r ] << ","; accountFile << balance [ r ] << endl; } accountFile.close();

  12. Array Initialization • Arrays can be initialized when they are declared int days [ MONTHS ] = {31, 28, 31, 30, …, 31}; string planets [ 9 ] = { "Mercury", … "Pluto?" }; float coins [ 5 ] = { 0.05, 0.1, 0.25, 0.5, 1.0 }; • Arrays can be partially initialized int numbers[ 7 ] = { 1, 2, 4, 8 }; • Uninitialized elements will be set to 0

  13. Implicit Sizing • When an array is initialized, the size can be inferred from the initialization double ratings [] = { 1.0, 1.5, 2.0, 2.5, 3.0 }; • You can't skip over initializers int array [ 6 ] = { 2, 4, , 8, , 12 };

  14. Copying Arrays • You can't assign an array to another array :( int array1 [ 5 ] = { 1, 2, 3, 4, 5 }; int array2 [ 5 ]; array1 = array2; • But u can assign individual elements to each other array1 [ 2 ] = array2 [ 2 ]; • To copy an array, just iterate over both for ( int j = 0; j < 5; j++ ) array1 [ j ] = array2 [ j ];

  15. Printing An Array • To print an array you need to iterate over it for ( int j = 0; j < 5; j++ ) cout << array1 [ j ] << endl; • Unfortunately you can't just stream the array cout << array1 << endl;

  16. Summing Up an Array • Iterate over the array and keep track of a running total int total = 0; for ( int j = 0; j < 5; j++ ) total += array1 [ j ];

  17. Computing the Average of an Array • Add up the total array and divide the number of values int total = 0; for ( int j = 0; j < 5; j++ ) total += array1 [ j ]; float average = total / 5.0;

  18. Finding the Max and Min • Keep track of the max and min so far as you iterate over the array int max = array1 [ 0 ]; int min = array1 [ 0 ]; for ( int j = 0; j < 5; j++ ) { if ( max > array1 [ j ] ) max = array1 [ j ]; if ( min < array1 [ j ] ) min = array1 [ j ]; }

  19. Comparing Arrays • To compare arrays compare each element, the first discrepancy means arrays are different boolarraysAreEqual = true; int array1 [ 5 ], array2 [ 5 ]; for ( int k = 0; k < 5; k++ ) if ( array1 [ k ] != array2 [ k ] ) { arraysAreEqual = false; break; }

  20. Arrays as Function Arguments boolareArraysEqual ( inta[], intb[], int size ) { for ( int k = 0; k < size; k++ ) O(n) if ( a [ k ] != b [ k ] ) return false; return true; } int main () { int x[ 4 ] = {1, 2, 3, 4}; int y[ 4 ] = {1, 2, 3, 4}; cout << areArraysEqual( x, y, 4 ) << endl; }

  21. arrayMax ( int [] ) intarrayMax ( int array[], size ) { O(n) int max = array [ 0 ]; for ( int j = 0; j < 5; j++ ) { if ( max > array [ j ] ) max = array [ j ]; return max; } int main() { int[] a = {1, 2, 3, 4, 5}; cout << arrayMax ( a, 5 ) << endl; }

  22. Multidimentional Arrays • Arrays can have more than one dimension int scores [ rows ] [ columns ]; • Use an index per dimension to refer to each element scores [ 3 ] [ 4 ] = 97;

  23. Initializing Multidimensional Arrays • Multidimensional arrays are just arrays of arrays int scores[][] = { { 89, 78, 67, 78, 87 }, { 98, 87, 78, 98, 90 }, {76, 87, 89, 87, 89 } }

  24. Iterating Over Dimensions • Use nested for loops to iterate over each dimension for ( int row = 0; row < ROWS; row++ ) { O(n2) for ( intcol = 0; col < COLS; col++ ) { int value = scores [ row ] [ col ];

  25. ArraysDemo.cpp

More Related