Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements are accessed using the base name with a numerical (integer) subscript Subscript numbering starts at zero Ends at N-1 where N is the number of elements in the array Array elements are stored in sequential memory locations
Declaring an Array Syntax: type arrayName[size]; type can be any valid C++ type Ex: int, float, double, char, string, … arrayName can be any valid C++ variable name size can be any positive integer (i.e. greater than zero) Specifies the number of elements in the array
Example Declarations int scores[10]; float salaries[25]; An array of 10 integers float salaries[25]; An array of 25 floating point numbers string names[4]; An array of 4 string variables
Accessing array elements Array elements are accessed using the subscript operator Square brackets [num] Num: an integer between 0 and N-1, where N is the number of elements Error if num is less than zero or greater than or equal to N // an array of 10 integers int scores[10]; scores[0] is the first element of array scores[4] is the fifth element of array scores[9] is the last element of array
Working with array elements Individual array elements are variables They can be used the same way simple variables are Examples: int scores[10]; string names[4]; scores[0] = 80; names[1] = “Bob”; int sum= scores[5] + scores [6]; cout << “hello “ << names[1] << endl; if(scores[3] > scores[4]) { cout << “yes!” << endl; }
Sequential vs. Random access Access any element at any time using a valid subscript number Sequential access Access in numerical order Example: int square[8]; for (int i = 0; i < 8; i++) { square[i] = i * i; } (stored in sequential memory locations) [0] [1] [2] [3] [4] [5] [6] [7] 1 4 9 16 25 36 49
Array Initialization Case 1: type arrayName[N] = { val0, val1, …, val(N-1) }; Specify N initial values If fewer than N are given, unspecified values are uninitialized (random values) Case 2: type arrayName[] = { val0, val1, …, val(N-1) }; Size not specified – array automatically becomes size of initialization list Example float cube[5]= { 0.0, 1.0, 8.0, 27.0, 64.0 }; [0] [1] [2] [3] [4] 0.0 1.0 8.0 27.0 64.0
Passing Arrays to Functions Arrays are always passed by reference (actually by pointer) Which means the elements can be changed by the function Pass entire array to a function by writing just its name (no subscripts or brackets) in the argument list of the function call In function definition and prototype, use empty brackets ([ ]) to indicate an array
Passing Arrays to Functions (example) // function definition void func(int A[], int size) { if(size >= 3) A[2]= 10; } // prototype void func(int[], int); main() { int array[3]= { 2, 4, 6 }; // call the function func(array, 3); cout << array[2] << endl; } This will output “10”
More on passing arrays Use keyword const to indicate that array argument cannot be changed by function Compiler will not allow changes to arrays passed with a const prefix This will not compile // function definition void func(const int A[], int size) { if(size >= 3) A[2]= 10; // error: attempting to change a value in a const array }
Individual elements are passed by value Individual elements are treated like any other variable Individual elements are passed by value // function definition void func(int a) { a=3; } Neither func(x) or func(array[2]) will change the value passed in i.e. both x and array[2] will retain their original values after the “func()” is finished its execution
Parallel Arrays Parallel arrays: a set of arrays that store related information in separate arrays, but with the same index number permits storage of multiple pieces of information for a collection of items For Example: string name[4]= { "John", "Mary", "Lucy", "George" }; string gender[4]= { "male", "female", "female", "male" }; int age[4]= { 20, 21, 19, 23 }; Information about Mary is stored in each array at index 1…
Parallel Array Use // find the oldest int oldest=age[0], indx=0; for (int i=1; i<4; i++) { if(age[i] > oldest) { oldest= age[i]; indx=i; } cout << name[indx] << “is oldest”; string name[4]= { "John", "Mary", "Lucy", "George" }; string gender[4]= { "male", "female", "female", "male" }; int age[4]= { 20, 21, 19, 23 };
Multidimensional Arrays Arrays can have more than one dimension Example: 2D array Commonly used to represent a table char ticTacToe[3][3]; Access ticTacTie[1][2] Note: The total number of elements is just the product of the sizes of each dimension: int array[3][5]; Number of elements is 15 (3*5)
Accessing a Multidimensional Array Indexing starts at zero (like a 1D array)
Initialization Each inner pair of braces contains initial values for one row of the array matrix const int NUM_ROWS = 2; const int NUM_COLS = 3; float matrix[NUM_ROWS][NUM_COLS] = { {5.0, 4.5, 3.0}, {-16.0, -5.9, 0.0} };
Strings and Arrays of Characters string object uses an array of char Can reference individual character of a string object in different ways name[ i ] name.at( i ) A useful member function of string class name.length()