1 / 35

Chapter 7 – One-Dimensional Arrays

x[0]. y[0]. x[1]. y[1]. y[9]. x[9]. array x. Array (subscripted variable, indexed variable) An array is a data structure in C++ that consists of a group of like-type data where each element in the array is easily referred to by an index. Example: int main() {

brooke
Download Presentation

Chapter 7 – One-Dimensional 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. x[0] y[0] x[1] y[1] y[9] x[9] array x Array (subscripted variable, indexed variable)An array is a data structure in C++ that consists of a group of like-type data where each element in the array is easily referred to by an index. Example: • int main() • { • const int N = 10; //10 elements in the array • double x[N],y[N]; //define arrays x and y • x[0] = 10; //assign value to x[0] • x[1] = 20; • y[0] = 33; • y[1] = 43; • …. array y Chapter 7 – One-Dimensional Arrays 1 1

  2. Declaring arrays Arrays are declared like other variables, except that the identifier is followed by brackets containing a value specifying the size of the array. Form: type ArrayName[ArraySize]; ArrayName – any valid identifier ArrayValue – a constant variable, expression, or literal Examples: const int N = 30; int A[N], B[2*N], C; double Grades[100], Monthly_Sales[12], Total; char Initials[3];

  3. Working with arrays elements Elements in an array are easily referred to using the subscript (or index). The index for the first element is 0. If an array has size N, then the indices run from 0 to N-1. A(2) refers the third element in array A and may be treated as any other variable. Example: const int N = 4; // specify the array size * int A[N]; // declare the array A[0]=10; // assigning a value to A[0] A[1]=20; A[2] = A[0] + A[1]; // array elements used in expressions A[N-1] = A[N-2]; // array indices can be expressions cout << A[2]; // printing one value of the array // *Note: It is good practice to use variables for array sizes

  4. Initializing arrays Elements in array may be initialized in two ways: Explicitly (using an assignment statement for each element) Using a list. A list is denoted using braces, with element in the list separated by a comma. Initializing arrays explicitly Easily accomplished using a for loop. Example: Explicitly initialize all elements in an array to 5.0 const int Asize = 100; int A[Asize]; for (int i = 0; i < Asize; i++) A[i] = 5.0;

  5. Example: - Initializing arrays explicitly. Determine the contents of each array below after the following instructions. const int Size = 8; int A[Size], B[Size], C[Size], D[Size], E[Size]; for (inti = 0; i < Size; i++) A[i] = 10 + i%2*10; for (int j = Size-1; j >=0; j--) B[j] = j*j; for (int k = 0; k < Size; k++) { C[Size-1-k] = 5*k – A[k]; if(A[k] > B[k]) D[k] = A[k]; else D[k] = B[k]; } for (int m = 0; m < Size/2; m++) { E[m] = m; E[Size-1-m] = m; }

  6. Initializing arrays using a list Elements in array may be initialized using a list of values in braces. If the number of values listed is less than the size of the array, the remaining elements are initialized to zero (treated as null characters ‘\0’ in char arrays). If the array size is omitted when using a list, then the array size is set to the number of elements in the list. Example: double X[4] = {1.1, 2.2, 3.3, 4.4}; // initialize array X with a list Using the list above is equivalent to: double X[4]; X[0] = 1.1; X[1] = 2.2; X[2] = 3.3; X[3] = 4.4;

  7. Example: - Initializing arrays using a list int A[5] = {11,22}; // initializes array values to 11,22,0,0,0 double Sum[7] = {0.0}; // initializes all 7 sums to 0.0 int B[ ] = {2,4,6,8}; // array B is assigned an array size of 4 char Vowels[8] = “aeiou”; // Vowels[0] = ‘a’, Vowels[1] = ‘e’, etc. \0 is the “null character”

  8. Printing arrays Arrays are easily printed using for loops. However, formatting the output may require some thought. Determine the output in each case shown below. Example 1: int Grades[12]={78,80,82,84,86,88,90,92,94,96,98,100}; for (int j = 0; j < 12; j++) cout << Grades[ j ] << endl; Example 2: int Grades[12]={78,80,82,84,86,88,90,92,94,96,98,100}; for (int j = 0; j < 12; j+=3) cout << Grades[ j ] << Grades[j+1] << Grades[j+2] << endl;

  9. Example 3: int Grades[12]={78,80,82,84,86,88,90,92,94,96,98,100}; for (int Row = 0; Row <= 2; Row++) for (int Col = 0; Col <=3; Col++) cout << Grades[ 4*Row+Col ] << endl; Example 4: int Grades[12]={78,80,82,84,86,88,90,92,94,96,98,100}; for (int Row = 0; Row <= 2; Row++) { for (int Col = 0; Col <=3; Col++) cout << Grades[ 4*Row+Col ]; cout << endl; }

  10. Functions and Arrays Arrays may be passed as arguments of functions, but some important notes should be made: Function declaration - include the data type and empty brackets Function call – include the array name with no brackets Function header – include the data type, name, and empty brackets Reference parameters – Arrays are always treated as reference parameters, but no ampersand (&) is required. Since reference parameters can be used for input or output, making an array a constant will protect it from being changed by the function (i.e., it will be treated as an input only). Dimensioning arrays - Arrays are typically dimensioned in the main calling function, not in the function to which the array is passed. The array size is often passed to the function along with the array. This keeps functions general in nature so that they can work with any size array.

  11. Example – Passing an array to a function Comments on highlighted sections:

  12. Examples: Write functions for one or more of the following examples (along with a main program to call them) in class: Find the max value in an array Add two arrays Find the average value in an array and then form another array containing the difference between each element and the average. Find the standard deviation of the elements in an array as defined below:

  13. So far we have used one-dimensional (1D) arrays, but we can also use arrays with 2 or more dimensions. 2D arrays essentially correspond to matrices. Example: • int A; // single variable • int B[6]; // 1D array • int C[3][4]; // 2D array (matrix) • int D[3][4][5]; // 3D array • int E[3][4][5][3]; // 4D array • //etc Multi-Dimensional Arrays How many variables are stored in each case?

  14. Multi-dimensional Arrays Col 0 Col 1 Col 2 Col 3 A[0][0] Row 0 A[1][2] Row 1 A[2][3] Row 2 • One subscript for each dimension • Use square brackets for each subscript • Each subscript begins with 0 • A 2D array is typically represented as a matrix Example: • int A[3][4]; // 2D array (matrix) with 3 rows and 4 columns

  15. Specifying values in arrays As with 1D arrays, values can be loaded into multidimensional arrays: • explicitly (referring to each element by its indices) or • using a list Example: Loading values into a matrix explicitly • int A[2][3]; // 2D array (matrix) with 2 rows and 3 columns • A[0][0] = 1; • A[0][1] = 2; • A[0][2] = 3; • A[1][0] = 4; • A[1][1] = 5; • A[1][2] = 6; Results for matrix A:

  16. Example: Values can be loaded into an array efficiently using for loops. The array can also be displayed using for loops.

  17. Example: Loading values into a matrix from the keyboard and displaying the results.

  18. Visualizing multi-dimensional arrays We often use sketches to help us visualize arrays, such as: • 1D array - single row or column • 2D array – matrix • 3D array – cube of cells • 4D array – row or column of cubes? Example: • int A, B1[6], B2[6], C[3][4], D[3][4][5], E[3][4][5][3]; E A B1 C D B2

  19. Visualizing multi-dimensional arrays D Although we might find the visualizations on the previous slide to be useful, note that C++ stores the variables linearly, with the last index varied first (then the second index from the last, etc). This is important when loading an array with a list. Example: int C[3][4], D[2][3][4]; C Note that matrices are filled in by row when using a list. Note that the indices increase numerically for any array. In this case: (..,111,112,113,120,..)

  20. Loading values into a matrix using a list Example: Fill out the matrices indicated below. • int A[2][3] = {3,6,9,12,15,18}, B[2][3] = {7,8,9}, • C[][2] = {2,4,6,8,10,12,14,16}; • // Note: If the leftmost index is omitted, the array is sized according • // to the number of list elements. • // Recall from 1D arrays the effect of listing fewer values than the • // size of the array. Matrix A: Matrix C: Matrix B:

  21. Loading values into a matrix using a list Lists can also be grouped (i.e., a list of lists) to make it easier to read the row and column values for a matrix.

  22. Multi-dimensional Arrays and Functions The material covered for using 1D arrays with functions also applies for multi-dimensional arrays with one important difference. Only the first set of brackets in the function declaration and function definition can be empty. To summarize some key points: • Include empty brackets for the leftmost index, but use specific dimensions for all other indices (along with the type) for all arrays in the function declaration (prototype). Example: void MFunction(int[][10], int); • The function definition is similar to the prototype, but must also include variable names. Example: void MFunction(int A[][10], int Asize) { statement(s); // body of the function } • No brackets are needed in the function call statement. Example: MFunction(A,Size); • Arrays are always reference parameters, so can be inputs or outputs. • Input arrays can be protected by making them constants. • const int CMax = 4; // global variable • void MFunction(const int A[][CMax], int); // Example • // prototype protecting contents of matrix A

  23. Example: Passing a matrix to a function

  24. Arrays with 3 or more dimensions Using 1D and 2D arrays is common and somewhat natural. Applications using 3 or more dimensions are harder to find. Text example: The text (Programming in C++, by D’Orazzio) includes an example where rainfall is recorded over a 10-year period. Notes: • Using a 1D array is awkward as there are 10*365 = 3650 days (not counting leap years). Using the following declaration: • double Rain[3650]; // declare 1D array • Rain[2125] = 0.25; // it is hard to tell what date this is! • Using a 3D array is clearer, where the 3 indices correspond to the year, month, and day. • const int Year = 10, Month = 13, Day = 32; • double Rain[Year][Month][Day]; // declare 3D array • Rain[1][4][25] = 0.25; // 1/4 “ of rain on April 25 in • // Year 1 of the study • Why use 13 months and 32 days above? Discuss in class.

  25. Matrix Examples Try one or more of the following examples in class: • Load values into matrices A and B with a list and then form matrix C = A + B (A and B must have the same dimensions) • Read matrix A from a file and call one or more functions to find the max, min, and average of the elements in matrix A. For example, the function calls might be: • Avg = MatrixAverage(A,Size); • Max = MatrixMax(A,Size); • Min = MatrixMin(A,Size);

  26. Expanding and Contracting Lists of Data • We have seen so far that we must specify the size of an array at the beginning of the program. • If we are not sure of the number of elements to be loaded into an array we could declare a large size for the worst case scenario, but this would waste memory. For example, we could list the number of students as 500 for an unknown class size, but this is wasteful for a class size of 20. • Two other ways to handle this are listed below. Both involve dynamic memory allocation. • Dynamically create new arrays and delete arrays as needed using the new and delete operators. We will see how to do this in a later chapter once pointers are introduced. • Use the vector class in the Standard Template Library (STL). C++ includes a useful set of classes in the STL that allow the programmer to easily modify, expand, and contract structures. Additionally, functions are included in the STL for sorting and searching lists of data.

  27. The Standard Template Library • Standard Template Library (STL): Generic set of data structures that can be modified, expanded, and contracted • Each STL class is coded as a template to permit the construction of a container • Container: A generic data structure, referring to a set of data items that form a natural group • Also called list or collection • Containers include vectors, deques, lists, sets, multisets, maps, and multimaps. Here we will only look at vectors. • Vector: Similar to an array • Uses a zero-relative index, but automatically expands as needed

  28. The Standard Template Library (continued) • STL Vector class provides many useful methods (functions) for vector manipulation: • insert(pos, elem); // inserts elem at position pos • name.push_back(elem); //append elem at the end of the vector • name.size(); //return the size of the vector • STL also provides generic functions called algorithms • sort(name.begin(), name.end()); //sort the vector in ascending order • reverse(name.begin(), name.end()); //reverse the order of the elements in the vector • accumulate(name.begin(), name.end()); //sum the elements in the vector • max_element(name.begin(), name.end()); //returns the position (iterator) of the max value in the vector – see note in Example 2.

  29. The Standard Template Library (continued) • Must include the header files: #include <vector> // required to use vector<T> class #include <algorithm> // needed for some algorithms or functions //such as reverse( ), replace( ), etc. #include <numeric> // needed for some algorithms or functions // such as accumulate( ) • Create and initialize a vector: Form: vector<dataType> vectorName(start,end); Examples: vector<int> X; // vector of unspecified size vector<double> Y(50); // vector with 50 elements (indices 0 to 49) vector<double> Z(N); // vector of size N (perhaps after the user //enters a value for N)

  30. The Standard Template Library (continued) • Syntax: • To modify a specific element: vectorName[index] = newValue; • To insert a new element: vectorName.insert(index, newValue); • STL provides other containers, algorithms, and iterators

  31. STL Example 1: Use the vector <T> class in the STL to read in an unknown number of grades and sort the grades.

  32. STL Example 1: (continued)

  33. Output for STL Example 1 on previous page.

  34. STL Example 2: Use the vector <T> class in the STL to create a fixed size vector and to create a second vector of size N to be specified by the user.

  35. Output for STL Example 2:

More Related