1 / 50

Arrays

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

neola
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 Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions Learning & Development Team http://academy.telerik.com Telerik Software Academy

  2. Table of Contents • What are Arrays? • Declaring and Initializing Arrays • Accessing Array Elements • Array Input and Output • Multidimensional Arrays • STL vectors

  3. What are Arrays? Compound Data

  4. 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"

  5. 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};

  6. 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.

  7. Declaring and Initializing Arrays Creating C++ arrays

  8. 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

  9. 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

  10. 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); }

  11. Creating Arrays Live Demo

  12. Accessing Array Elements Reading and Writing the Values of Arrays

  13. 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

  14. 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

  15. 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;

  16. 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}

  17. Accessing Array Elements Live Demo

  18. 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

  19. 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

  20. Exceeding Array Bounds Live Demo

  21. Arrays: Input and Output Reading and Printing Arrays on the Console

  22. 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

  23. 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]; }

  24. 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; }

  25. Input and Output of Arrays Live Demo

  26. Multidimensional Arrays Arrays of arrays, Representing Tabular Data

  27. 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

  28. 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)

  29. Declaring and Initializing Multidimensional Arrays Live Demo

  30. 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

  31. 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} }

  32. 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

  33. 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]; } }

  34. Arrays as Parameters Syntax, How it Works

  35. 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

  36. 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 }

  37. 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); }

  38. Accessing Multidimensional Arrays Live Demo

  39. STL Vectors Using the STL vector, Array vs. Vector

  40. 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

  41. 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)

  42. Creating Vectors Live Demo

  43. 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

  44. 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"

  45. Working with Vectors Live Demo

  46. Arrays http://algoacademy.telerik.com

  47. 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}.

  48. 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.

  49. 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}

  50. 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).

More Related