Unformatted text preview: Lecture 19: Introduction to Arrays
PIC 10A Todd Wittman Sec 6.5: Declaring an Array
An array is a list of multiple values of the same type. array The general form of an array declaration is: The type array_name [size]; type array_name
For example, a list of 5 integers is declared: For int list[5]; Note that without [5] it would be just a single integer. Note We can declare any data type, even classes. We double double_list[20]; double string words[100]; //List of 100 words. //List Card deck[52]; //A deck of 52 cards. Card //A Just like before, when we declare the array it has no useful values in it. Just We can initialize an array with: type name[size] = {val1, val2,...valN}; name[size int llist[5] = {11, 12, 42, 38, 105}; //Also could omit the [5]. ist[5] 12, 105}; //Also This often is not practical, since we usually don’t know the values right This know away and/or the array size is very large. away 1 Using an Array
An individual element of an array can be accessed by its index: array_name[index] array_name[index Array indices always start at 0. Array So the last index is always size1. So What does the code below print? What list[0] list[1] list[2] list[3] list[4] int llist[5] = {11, 12, 42, 38, 105}; ist[5] 12, cout << list[3]; What is the index of the last element? What 3 Simple Examples
We often use for loops to assign array values. We Ex Store the first 100 even integers. Ex int evens[100]; evens[100]; for (int i = 0; i<100; i++) for 0; evens[i] = 2*i+2; evens[i Ex Read in 10 doubles and compute the sum. Ex double list[10]; double sum = 0; for (int i = 0; i < 10; i++) { cin >> list[i]; >> list[i sum += list[i]; sum list[i } cout << “\nThe sum is: “ << sum; << sum Ex Read in 4 hobbit names. Ex string hobbits[4]; for (int i = 0; i < 4; i++) { cout << “Enter the name of hobbit #” << i+1 <<“: “; << cin >> hobbits[i]; >> hobbits[i } 2 Thing1 to Watch Out For
DON’T FORGET: For an array of size N, the DON For array indices run from 0 to N1. array Visual Studio will not give you an error if you run past the length of the array. But you’lll get very l past strange results. strange int values[3] = {10, 20, 30}; for (int i=0; i<=3; i++) cout << values[i] << “ “; << values[i << OUTPUT 10 20 30 858993460 10 Thing2 to Watch Out For
The code below will give you an error. The int my_size = 3; //BAD!! 3; //BAD!! int values[my_size]; //ERROR!! ]; //ERROR!! Gives the error: “expected constant size” The size of the array must be a constant. For example: The const int my_size = 3; //GOOD!! const int 3; //GOOD!! int values[my_size]; Once you’ve set up an array, its size cannot be changed. Once Why does the code below not work? Why int size; cin >> size; int my_array[size]; 3 Example: Find Max & Min
Ex Find the maximum and minimum of an a given Ex Find integer array list of length N. list int min = list[0]; int max = list[0]; for (int i = 1; i < N; i++) { if ( list[i] < min ) if list[i min = list[i]; min list[i if ( list[i] > max ) if list[i max = list[i]; max list[i } cout << “The maximum is “ << max << “.\n”; << The << cout << “The minimum is “ << min << “.\n”; << The << Arrays in Functions
In a function declaration, we denote that a parameter is an array with blank brackets . an We usually pass the size of the array as well, unless the size is available as a global constant. size void my_fun (double my_array, int size) { void my_fun (double my_array, int When we call the function, we just give the variable name. name. double list[100]; my_fun (list, 100); Unlike vectors, arrays are always passed by reference always passed even without the &. This is to save memory. So we don't include the & because changes are always recorded. recorded. Also unlike vectors, arrays cannot be a return type. Also 4 Arrays in Functions
Ex Write the max/min routine as a function. Ex
void maxmin (int list, int N, int& max, int& min) void maxmin list, int N, int max, int min = list[0]; max = list[0]; for (int i = 1; i < N; i++) { if ( list[i] < min ) if list[i min = list[i]; min list[i if ( list[i] > max ) if list[i max = list[i]; max list[i } return; } { Class Arrays
We can even create arrays with a userWe defined class. Triangle my_triangles[100]; Card deck[52]; Each element is an object. So we can call a member function for each element. member my_triangles[5].draw(); string suitCard25 = deck[25].get_suit(); if (deck[11] < deck[12] ) 5 Debug This!
Ex Write a function which rewrites the elements of a double array in reverse order. double llist = 1 2 3 4 5.1 ist list = 5.1 4 3 2 1 list The code below does not work properly. Why? not void reverseArray (double list[ ], int size) { void reverseArray (double int for (int i = 0; i < size ; i++) { list[i] = list[sizei]; list[sizei] = list[i]; } return; } Debugged!
The last example had several problems. The
1. 2. 3. Index sizei runs one past the array size. The element swapping does not work. We should only proceed through the first half of the array. void reverseArray (double list[ ], int size) { void reverseArray (double int double temp; for (int i = 0; i < size/2; i++) { temp = list[i]; temp list[i]; list[i] = list[sizei1]; list[i] 1]; list[sizei1] = temp; list[size } return; } 6 Sec 9.5.4: 2D Arrays
Often data appears in two dimensions, like in a spreadsheet, data table, or an image. spreadsheet, 12.2 6.9 1.0 3.1 4.27 2.1 8.8 3.2 12.8 6.1 2.6 14.42 42.14 12.12 92.87 To declare a 2D array, use To type variable_name [num_rows] [num_columns];
For example, to create the data table above use: For double table [3] [5]; To assign individual elements, give it a row # and column #. column table [2] [4] = 92.87; 2D Arrays
When you pass a 2D array to a function, tell the function the # rows and columns. void my_function (double table [rows] [cols]) { ... void (Actually, just the # columns is required. But specifying the # rows too doesn’t hurt.) specifying
So to pass these numbers, probably best to declare the array size as global constants. array At the top of your program, right under the #includes state the size of your array. state Good style to attach the variable name to these values. Good const int table_rows = 10; const int const in table_cols = 20; const 7 Printing A Table.
Ex Write a function which prints the values of a 3x5 table. Ex #include <iomanip> const int table_rows = 3; const int const int table_cols = 5; const int
void printTable (double table [table_rows] [table_cols]) { void printTable for (int i = 0; i < table_rows; i++) { for (int j=0; j < table_cols; j++) { cout << setw(10) << table [i] [j]; } cout << "\n"; } return; } Matrix Transpose
Here’s a llittle something for students who are ittle Here sweating through Linear Algebra this semester. sweating The transpose of a matrix changes every row into a column. column. An MxN matrix becomes a NxM matrix. MxN matrix NxM 1 2 3 A= 4 5 6 1 4 AT = 2 5 3 6 Write a function which computes the matrix transpose of A. of T Key observation: A[i ][ j ] = A [ j ][i ] 8 Matrix Transpose
const int A_rows = 2; const int A_rows const int A_cols = 3; const int //Or whatever sizes you want. //Or void transpose (int A[A_rows][A_cols], A[A_rows][A_cols], int Atrans [A_cols][A_rows]) { int for (int i = 0; i < A_rows; i++) for (int j=0; j < A_cols; j++) Atrans [j][i] = A[i][j]; return; } Vectors vs. Arrays
We recommend using vectors, but there are situations in which you will use arrays. which
Arrays Dynamic? Arrays are static, they Arrays cannot change size. cannot Type Size Arrays are a primitive Arrays (builtin) data type. (built The array size is The generally kept as a global constant. global Arrays extend naturally Arrays to 2D. to Arrays are much faster Arrays on older compilers. on Arrays are more Arrays common in business. common Vectors Vectors are dynamic, they can Vectors change size using resize, push_back, and pop_back. push_back and pop_back Vectors are a class defined in the Vectors <vector> library. <vector> Vectors can look up their own size Vectors with the size() member function. with Vectors are a little awkward at 2D Vectors tables. tables. Vectors are almost as fast as arrays Vectors on newer compilers. on Vectors are gaining popularity. 2D Speed Usage 9 ...
View
Full Document
 Fall '10
 Wittman
 Array, Return statement, Type theory, Programming constructs, Symmetric matrix, Transpose

Click to edit the document details