500 likes | 612 Vues
Arrays. Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions. Learning & Development Team. http://academy.telerik.com. Telerik Software Academy. Table of Contents. What are Arrays? Declaring and Initializing Arrays Accessing Array Elements Array Input and Output
E N D
Arrays Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions Learning & Development Team http://academy.telerik.com Telerik Software Academy
Table of Contents • What are Arrays? • Declaring and Initializing Arrays • Accessing Array Elements • Array Input and Output • Multidimensional Arrays • STL vectors
What are Arrays? Compound Data
What are Arrays? • Arrays are collections of data (variables) • Under the same name • Sequential • All members have an index • i.e. number/position • Each member is accessed through • The array name • Combined with the member's index • "Members" are also called "elements"
What are Arrays? • What an int array looks like (sort of) • Sequence of int variables, each with a value • Each variable has an index, starting at 0 (zero) • E.g. variable at index 1 has a value of 10 • An array can be of any type • char, string, double, etc. • But only one type – cannot mix different types inta[6] = {13, 10, 5, 100, -3, 1000};
What are Arrays? • Arrays are essential to programming • Allow group operations (i.e. looping through) on elements • Part of many fundamental algorithms • Easy to manage by just tracking indices • Can represent real life concepts • Queues, Grades of students, Protons per element in the Periodic table, etc.
Declaring and Initializing Arrays Creating C++ arrays
Declaring & Initializing Arrays • Array declaration requires • Data type, Identifier • Array size (could be inferred from initialization) • If defined, array size must be constant • Declared arrays assume random values • When they are not initialized • And are local to functions • Memory is always assigned at declaration intnumberArray[5]; //"undefined" values char characterArray[2];//"undefined" values
Declaring & Initializing Arrays • Array initialization • Values provided in braces {}, size can be skipped • If array size is given explicitly • Items in braces less than (or equal to) array size • If number of items is less than array size • Remaining items initialized to default values intnumberArray[5] = {42, 13, 7, -1, 5}; intcharacterArray[] = {'a', 'z'}; //array has size 2 intsomeDefaults[3] = {1}; //array has values 1, 0, 0 intallDefaults[3] = {}; //array has values 0, 0, 0 intinitListArr[] {1, 2, 3}; //using an initializer list //initializer list only available at declaration until C++11
Declaring & Initializing Arrays • Looping through arrays also a popular method • E.g. initializing with square roots of the indices • Once created, an array cannot be re-assigned • Only way to create an array is declaration • i.e. no way to assign an array to a variable constint N = 100; ... double arr[N]; for(inti=0; i<N; i++) { arr[i] = sqrt(i); }
Creating Arrays Live Demo
Accessing Array Elements Reading and Writing the Values of Arrays
Accessing Array Elements • Elements are accessed through their index • Index is placed inside brackets [] • Indexing starts from 0 to the size of the array • Access is both read and write intnumberArray[5] = {42, 13, 7, -1, 5}; cout<numberArray[1]<<endl; //prints 13 numberArray[1] = 9; numberArray[3] += numberArray[1]; cout<<numberArray[1]; //prints 9 cout<<endl; cout<<numberArray[3]; //prints 8
Accessing Array Elements • Loops can provide an arbitrary number of executions of a piece of code • Arrays can provide an arbitrary number of elements • Hence, arrays and loops are often used together • i.e. starting a loop going through each index • Often called "iterating" or "traversing" an array
Accessing Array Elements • Example: sum of elements of an array constintnumElements = 10; intarr[numElements] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; int sum = 0; for(inti=0; i<numElements; i++) { sum += arr[i]; } cout<<sum;
Accessing Array Elements • Example: reversing an array constintnumElements = 11; intarr[numElements] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; for(inti=0; i<numElements/2; i++) { intmirrorIndex = numElements - i - 1; intcurrentIndexValue = arr[i]; arr[i] = arr[mirrorIndex]; arr[mirrorIndex] = currentIndexValue; ///or just use the built-in swap method //swap(arr[i], arr[mirrorIndex]); } //arr is now {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Accessing Array Elements Live Demo
Exceeding Array Bounds • When accessing by index in an array of size N • The following bounds for index apply:0 <= index < N • Arrays are not protected against bad indices • Neither compile-time nor runtime • Exceeding array bounds is not defined in the standard, i.e. unpredictable
Exceeding Array Bounds • Common results of accessing outside the array • You access some part of the program's memory – the access will be successful • Very hard to track this type of error • You access memory outside the program's address space – the OS should deny access • Error 0xC000005 in Windows • Don't rely on that, it could be a fatal error for an unprotected system
Exceeding Array Bounds Live Demo
Arrays: Input and Output Reading and Printing Arrays on the Console
Input of an Array from Console • Need to know the max size the array can be • Usually known in algorithmic problems • Further on, we will discuss how to do it even without knowing the max size in advance • Create an array with the max size • Read the actual number of elements • Start a loop and input each of the elements • Using the loop's "control variable" • for loops are good for this
Input of an Array from Console • Example of Reading an Array from the Console const int MAX_SIZE = 100; //asume we know it //need to initialize array with constant expression int arr[MAX_SIZE]; int actualSize = 0; cin>>actualSize; for (int i=0; i<actualSize; i++) { cin>>arr[i]; }
Printing Arrays on the Console • Assume we know the array size • Probably stored it on creation • Loop through each element index in the array • Print each element to the console const int numElements = 5; ... int arr[numElements] = ... for (int index = 0; index < numElements; index++) { // Print each element on a separate line cout << arr[index] << endl; }
Input and Output of Arrays Live Demo
Multidimensional Arrays Arrays of arrays, Representing Tabular Data
Multidimensional Arrays • Multidimensional arrays are arrays of arrays • Every element of the array is an array itself • Nesting can be as deep as needed (3D, 4D …) • Useful for multi-dimensional data, e.g. tables int array 2D int array
Multidimensional Arrays • 2D arrays • Represent tables, mathematical matrices, etc. • A 2D array is usually called a "matrix" • Usually perceived as tables/spreadsheets Second dimension (columns) First dimension (rows)
Declaring and Initializing Multidimensional Arrays Live Demo
Multidimensional Arrays • 3D arrays • Represent matrices with more than one value per cell (e.g. an RGB image) • Some representations of objects in 3D space • Sometimes called "cubes" Note: blurred bymagnification
Multidimensional Arrays • Declaring multidimensional arrays • Just like normal arrays, with an extra pair of [] • Initializing multidimensional arrays • The {} are filled with initializations of arrays • If provided arrays are less, default values are assigned int matrix[10][15]; //creates a 2D int array containing //10 one-dimensional int arrays, //each 15 elements long //Simply said a 2D array with 10 rows and 15 cols int m[2][3] = { {1, 2, 3}, {4, 5, 6} }
Multidimensional Arrays • Accessing elements of multidimensional arrays • Multidimensional arrays contain other arrays • Additional [] for each additional dimension • E.g. mat[5][3] accesses the 3rd element of the 5th array in mat • In other words, the cell at 5th row and 3rd column int m[2][3] = { {1, 2, 3}, {4, 5, 6} } cout<<m[0][0]; //prints 1 cout<<m[1][2]; //prints 6 cout<<m[1]; //prints the memory address of the second //array ({4,5,6}) in m
Multidimensional Arrays • Traversing multidimensional arrays • Extra nested loop for traversing each dimension • Reading a matrix from the console • Printing matrices is similar (consider new lines) constint ROWS = ..., COLS = ...; int matrix[ROWS][COLS]; for(int row = 0; row < ROWS; row++) { for(int col = 0; col < COLS; col++) { cin>>matrix[row][col]; } }
Arrays as Parameters Syntax, How it Works
Arrays as Parameters • Arrays can be parameters for functions • Array data itself is not passed • Instead, a "reference" is passed • Much faster than copying the entire array • A reference points to the original object • Modifying a reference in the function leads to modifying the object • i.e. changing array elements effects the array in the caller
Arrays as Parameters • Syntax for passing an array as a parameter • Much like declaration syntax • Size of first dimension can be omitted • i.e. normal (1D) arrays can have empty [] int Sum(intarr[], intnumElements) { int sum = 0; for(int i=0; i<numElements; i++) { sum += arr[i]; } return sum; } int main() { int numbers[] = {1,2,3}; cout<<Sum(numbers, 3); //prints 6 }
Arrays as Parameters • Syntax for passing 2D array as a parameter • Multi-dimensional arrays need to specify size in each dimension, except the first int Print3ColMatrix(int matrix[][3], int rows) { for(int row = 0; row < rows; row++) { for(int col = 0; col < 3; col++) { cout<<matrix[row][col] } cout << endl; //new line for each row } } int main() { int matrix[2][3] = {{1,2,3},{4,5,6}}; Print3ColMatrix(matrix, 2); }
Accessing Multidimensional Arrays Live Demo
STL Vectors Using the STL vector, Array vs. Vector
STL Vectors • The typical C++ array has a very big problem • Declared and allocated with a constant size • i.e. cannot instantiate an array based on input • Dynamic Array • Concept in programming as a whole • Can change its size – grow, shrink (fast) • And knows its size • Can have elements added and removed (fast) • Has all functionality of a normal array
STL Vectors • The Standard Template Library has a template for a dynamic array • vector<T>, where T can be any type • Can grow indefinitely (depends on RAM) • Initialized dynamically (E.g. based on input) • Declaring and initializing a vector #include<vector> //required header … vector<int> numbers; numbers.push_back(42); //numbers is now {42} numbers.push_back(13); //numbers is now {42, 13} intconsoleNumber; cin>>consoleNumber; numbers.push_back(consoleNumber)
Creating Vectors Live Demo
STL Vectors • Accessing vector elements • Done the same way as with arrays, i.e. [] • Vector size and can be obtained by calling size() vector<int> numbers; numbers.push_back(42); numbers.push_back(13); cout<<numbers[1]; //prints 13 cout<<endl; numbers[1] = numbers[0]; cout<<numbers[1]; //prints 42 vector<int> numbers; numbers.push_back(42); numbers.push_back(13); cout<<numbers.size(); //prints 2
STL Vectors • Vectors vs. Arrays • Vectors are dynamic, with fast resize • Vector parameters are copied (slow) • Except when parameter is a reference (fast) • Vectors allocate in dynamic memory (default) • Arrays are allocated on the stack – much smaller • Large arrays can cause a Stack overflow, vectors are safe in this manner • Vectors allocate twice the memory needed • Not all of the time, can be manually "fixed"
Working with Vectors Live Demo
Arrays http://algoacademy.telerik.com
Exercises • Write a program that allocates array of 20 integers and initializes each element by its index multiplied by 5. Print the obtained array on the console. • Write a program that reads two arrays from the console and compares them element by element. • Write a program that compares two char arrays lexicographically (letter by letter). • Write a program that finds the maximal sequence of equal elements in an array. Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} {2, 2, 2}.
Exercises (2) • Write a program that finds the maximal increasing sequence in an array. Example: {3, 2, 3, 4, 2, 2, 4} {2, 3, 4}. • Write a program that reads two integer numbers N and K and an array of N elements from the console. Find in the array those K elements that have maximal sum. • Sorting an array means to arrange its elements in increasing order. Write a program to sort an array. Use the "selection sort" algorithm: Find the smallest element, move it at the first position, find the smallest from the rest, move it at the second position, etc.
Exercises (3) • Write a program that finds the sequence of maximal sum in given array. Example: {2, 3, -6, -1, 2, -1, 6, 4, -8, 8} {2, -1, 6, 4} Can you do it with only one loop (with single scan through the elements of the array)? • Write a program that finds the most frequent number in an array. Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} 4 (5 times) • Write a program that finds in given array of integers a sequence of given sum S (if present). Example: {4, 3, 1, 4, 2, 5, 8}, S=11 {4, 2, 5}
Exercises (6) • Write a program that finds the index of given element in a sorted array of integers by using the binarysearchalgorithm (find it in Wikipedia). • Write a program that finds all prime numbers in the range [1...10 000 000]. Use the sieve of Eratosthenes algorithm (find it in Wikipedia).