Download presentation
Presentation is loading. Please wait.
Published byArnold Butler Modified over 8 years ago
1
Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions Learning & Development Team http://academy.telerik.com Telerik Software Academy
2
1. What are Arrays? 2. Declaring and Initializing Arrays 3. Accessing Array Elements 4. Array Input and Output 5. Multidimensional Arrays 6. STL vectors 2
3
Compound Data
4
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 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 Index 012345 Value 13105100-31000 int a[6] = {13, 10, 5, 100, -3, 1000};
6
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
Creating C++ arrays
8
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 int numberArray[5]; //"undefined" values char characterArray[2];//"undefined" values
9
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 int numberArray[5] = {42, 13, 7, -1, 5}; int characterArray[] = {'a', 'z'}; //array has size 2 int someDefaults[3] = {1}; //array has values 1, 0, 0 int allDefaults[3] = {}; //array has values 0, 0, 0 int initListArr[] {1, 2, 3}; //using an initializer list //initializer list only available at declaration until C++11
10
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 const int N = 100;... double arr[N]; for(int i=0; i<N; i++) { arr[i] = sqrt(i); }
11
Live Demo
12
Reading and Writing the Values of Arrays
13
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 int numberArray[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
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
Example: sum of elements of an array const int numElements = 10; int arr[numElements] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; int sum = 0; for(int i=0; i<numElements; i++) { sum += arr[i]; sum += arr[i];}cout<<sum;
16
Example: reversing an array const int numElements = 11; int arr[numElements] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; for(int i=0; i<numElements/2; i++) { int mirrorIndex = numElements - i - 1; int mirrorIndex = numElements - i - 1; int currentIndexValue = arr[i]; int currentIndexValue = arr[i]; arr[i] = arr[mirrorIndex]; arr[i] = arr[mirrorIndex]; arr[mirrorIndex] = currentIndexValue; arr[mirrorIndex] = currentIndexValue; ///or just use the built-in swap method ///or just use the built-in swap method //swap(arr[i], arr[mirrorIndex]); //swap(arr[i], arr[mirrorIndex]);} //arr is now {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
17
Live Demo
18
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
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
Live Demo
21
Reading and Printing Arrays on the Console
22
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 22
23
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]; cin>>arr[i];}
24
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 // Print each element on a separate line cout << arr[index] << endl; cout << arr[index] << endl;} 24
25
Live Demo
26
Arrays of arrays, Representing Tabular Data
27
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 IndexValue 042 19 2101 3121 4-11 5-101 IndexValue 0index01234 value20141983194219811945 1index01234 value429101121-11 2index01234 value43210 int array 2D int array
28
2D arrays Represent tables, mathematical matrices, etc. A 2D array is usually called a "matrix" Usually perceived as tables/spreadsheets 01234 020141983194219811945 1429101121-11 243210 Second dimension (columns) First dimension (rows)
29
Live Demo
30
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" 012 0012012012 255 15030100 12 1012012012 341777634177763417776 2012012012 237255362372553623725536 Note: blurred by magnification
31
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, //10 one-dimensional int arrays, //each 15 elements long //each 15 elements long //Simply said a 2D array with 10 rows and 15 cols int m[2][3] = { {1, 2, 3}, {1, 2, 3}, {4, 5, 6} {4, 5, 6}} m 012 0123 1456
32
Accessing elements of multidimensional arrays Multidimensional arrays contain other arrays Additional [] for each additional dimension E.g. mat[5][3] accesses the 3 rd element of the 5 th array in mat In other words, the cell at 5 th row and 3 rd 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 //array ({4,5,6}) in m
33
Traversing multidimensional arrays Extra nested loop for traversing each dimension Reading a matrix from the console Printing matrices is similar (consider new lines) const int ROWS =..., COLS =...; int matrix[ROWS][COLS]; for(int row = 0; row < ROWS; row++) { for(int col = 0; col < COLS; col++) for(int col = 0; col < COLS; col++) { cin>>matrix[row][col]; cin>>matrix[row][col]; }}
34
Syntax, How it Works
35
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
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(int arr[], int numElements) { int sum = 0; int sum = 0; for(int i=0; i<numElements; i++) for(int i=0; i<numElements; i++) { sum += arr[i]; sum += arr[i]; } return sum; return sum;} int main() { int numbers[] = {1,2,3}; int numbers[] = {1,2,3}; cout<<Sum(numbers, 3); //prints 6 cout<<Sum(numbers, 3); //prints 6}
37
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 row = 0; row < rows; row++) { for(int col = 0; col < 3; col++) { for(int col = 0; col < 3; col++) { cout<<matrix[row][col] cout<<matrix[row][col] } cout << endl; //new line for each row cout << endl; //new line for each row }} int main() { int matrix[2][3] = {{1,2,3},{4,5,6}}; int matrix[2][3] = {{1,2,3},{4,5,6}}; Print3ColMatrix(matrix, 2); Print3ColMatrix(matrix, 2);}
38
Live Demo
39
Using the STL vector, Array vs. Vector
40
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
The Standard Template Library has a template for a dynamic array vector, 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 //required header … vector numbers; numbers.push_back(42); //numbers is now {42} numbers.push_back(13); //numbers is now {42, 13} int consoleNumber; cin>>consoleNumber; numbers.push_back(consoleNumber)
42
Live Demo
43
Accessing vector elements Done the same way as with arrays, i.e. [] Vector size and can be obtained by calling size() vector 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 numbers; numbers.push_back(42);numbers.push_back(13); cout<<numbers.size(); //prints 2
44
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
Live Demo
46
форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране http://algoacademy.telerik.com
47
1. 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. 2. Write a program that reads two arrays from the console and compares them element by element. 3. Write a program that compares two char arrays lexicographically (letter by letter). 4. 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}. 47
48
5. Write a program that finds the maximal increasing sequence in an array. Example: {3, 2, 3, 4, 2, 2, 4} {2, 3, 4}. 6. 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. 7. 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. 48
49
8. 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)? 9. 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) 10. 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} 49
50
11. Write a program that finds the index of given element in a sorted array of integers by using the binary search algorithm (find it in Wikipedia). binary search binary search 12. 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). sieve of Eratosthenessieve of Eratosthenes 50
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.